commit
stringlengths
40
40
old_file
stringlengths
2
205
new_file
stringlengths
2
205
old_contents
stringlengths
0
32.9k
new_contents
stringlengths
1
38.9k
subject
stringlengths
3
9.4k
message
stringlengths
6
9.84k
lang
stringlengths
3
13
license
stringclasses
13 values
repos
stringlengths
6
115k
d232d345dc58c851f2903e34000571c19a507992
awa/src/awa-permissions-services.ads
awa/src/awa-permissions-services.ads
----------------------------------------------------------------------- -- awa-permissions-services -- Permissions controller -- Copyright (C) 2011, 2012, 2013, 2017 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with AWA.Applications; with Util.Beans.Objects; with EL.Functions; with ADO; with ADO.Sessions; with ADO.Objects; with Security.Policies; with Security.Contexts; with Security.Policies.Roles; package AWA.Permissions.Services is -- Register the security EL functions in the EL mapper. procedure Set_Functions (Mapper : in out EL.Functions.Function_Mapper'Class); type Permission_Manager is new Security.Policies.Policy_Manager with private; type Permission_Manager_Access is access all Permission_Manager'Class; -- Get the permission manager associated with the security context. -- Returns null if there is none. function Get_Permission_Manager (Context : in Security.Contexts.Security_Context'Class) return Permission_Manager_Access; -- Get the application instance. function Get_Application (Manager : in Permission_Manager) return AWA.Applications.Application_Access; -- Set the application instance. procedure Set_Application (Manager : in out Permission_Manager; App : in AWA.Applications.Application_Access); -- Add a permission for the current user to access the entity identified by -- <b>Entity</b> and <b>Kind</b> in the <b>Workspace</b>. procedure Add_Permission (Manager : in Permission_Manager; Entity : in ADO.Identifier; Kind : in ADO.Entity_Type; Workspace : in ADO.Identifier; Permission : in Permission_Type); -- Check that the current user has the specified permission. -- Raise NO_PERMISSION exception if the user does not have the permission. procedure Check_Permission (Manager : in Permission_Manager; Entity : in ADO.Identifier; Kind : in ADO.Entity_Type; Permission : in Permission_Type); -- Add a permission for the user <b>User</b> to access the entity identified by -- <b>Entity</b> which is of type <b>Kind</b>. procedure Add_Permission (Session : in out ADO.Sessions.Master_Session; User : in ADO.Identifier; Entity : in ADO.Identifier; Kind : in ADO.Entity_Type; Workspace : in ADO.Identifier; Permission : in Permission_Type := READ); -- Add a permission for the user <b>User</b> to access the entity identified by -- <b>Entity</b>. procedure Add_Permission (Session : in out ADO.Sessions.Master_Session; User : in ADO.Identifier; Entity : in ADO.Objects.Object_Ref'Class; Workspace : in ADO.Identifier; Permission : in Permission_Type := READ); -- Create a permission manager for the given application. function Create_Permission_Manager (App : in AWA.Applications.Application_Access) return Security.Policies.Policy_Manager_Access; -- Check if the permission with the name <tt>Name</tt> is granted for the current user. -- If the <tt>Entity</tt> is defined, an <tt>Entity_Permission</tt> is created and verified. -- Returns True if the user is granted the given permission. function Has_Permission (Name : in Util.Beans.Objects.Object; Entity : in Util.Beans.Objects.Object) return Util.Beans.Objects.Object; -- Delete all the permissions for a user and on the given workspace. procedure Delete_Permissions (Session : in out ADO.Sessions.Master_Session; User : in ADO.Identifier; Workspace : in ADO.Identifier); private type Permission_Manager is new Security.Policies.Policy_Manager with record App : AWA.Applications.Application_Access; Roles : Security.Policies.Roles.Role_Policy_Access; end record; end AWA.Permissions.Services;
----------------------------------------------------------------------- -- awa-permissions-services -- Permissions controller -- Copyright (C) 2011, 2012, 2013, 2017 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with AWA.Applications; with Util.Beans.Objects; with EL.Functions; with ADO; with ADO.Sessions; with ADO.Objects; with Security.Policies; with Security.Contexts; with Security.Policies.Roles; package AWA.Permissions.Services is -- Register the security EL functions in the EL mapper. procedure Set_Functions (Mapper : in out EL.Functions.Function_Mapper'Class); type Permission_Manager is new Security.Policies.Policy_Manager with private; type Permission_Manager_Access is access all Permission_Manager'Class; -- Get the permission manager associated with the security context. -- Returns null if there is none. function Get_Permission_Manager (Context : in Security.Contexts.Security_Context'Class) return Permission_Manager_Access; -- Get the application instance. function Get_Application (Manager : in Permission_Manager) return AWA.Applications.Application_Access; -- Set the application instance. procedure Set_Application (Manager : in out Permission_Manager; App : in AWA.Applications.Application_Access); -- Add a permission for the current user to access the entity identified by -- <b>Entity</b> and <b>Kind</b> in the <b>Workspace</b>. procedure Add_Permission (Manager : in Permission_Manager; Entity : in ADO.Identifier; Kind : in ADO.Entity_Type; Workspace : in ADO.Identifier; Permission : in Permission_Type); -- Check that the current user has the specified permission. -- Raise NO_PERMISSION exception if the user does not have the permission. procedure Check_Permission (Manager : in Permission_Manager; Entity : in ADO.Identifier; Kind : in ADO.Entity_Type; Permission : in Permission_Type); -- Get the role names that grant the given permission. function Get_Role_Names (Manager : in Permission_Manager; Permission : in Security.Permissions.Permission_Index) return Security.Policies.Roles.Role_Name_Array; -- Add a permission for the user <b>User</b> to access the entity identified by -- <b>Entity</b> which is of type <b>Kind</b>. procedure Add_Permission (Session : in out ADO.Sessions.Master_Session; User : in ADO.Identifier; Entity : in ADO.Identifier; Kind : in ADO.Entity_Type; Workspace : in ADO.Identifier; Permission : in Permission_Type := READ); -- Add a permission for the user <b>User</b> to access the entity identified by -- <b>Entity</b>. procedure Add_Permission (Session : in out ADO.Sessions.Master_Session; User : in ADO.Identifier; Entity : in ADO.Objects.Object_Ref'Class; Workspace : in ADO.Identifier; Permission : in Permission_Type := READ); -- Create a permission manager for the given application. function Create_Permission_Manager (App : in AWA.Applications.Application_Access) return Security.Policies.Policy_Manager_Access; -- Check if the permission with the name <tt>Name</tt> is granted for the current user. -- If the <tt>Entity</tt> is defined, an <tt>Entity_Permission</tt> is created and verified. -- Returns True if the user is granted the given permission. function Has_Permission (Name : in Util.Beans.Objects.Object; Entity : in Util.Beans.Objects.Object) return Util.Beans.Objects.Object; -- Delete all the permissions for a user and on the given workspace. procedure Delete_Permissions (Session : in out ADO.Sessions.Master_Session; User : in ADO.Identifier; Workspace : in ADO.Identifier); private type Permission_Manager is new Security.Policies.Policy_Manager with record App : AWA.Applications.Application_Access; Roles : Security.Policies.Roles.Role_Policy_Access; end record; end AWA.Permissions.Services;
Declare the Get_Role_Names function on the permission manager
Declare the Get_Role_Names function on the permission manager
Ada
apache-2.0
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
2b1ac6cba56aa0c5ab23f0f6ecb2409568e591ce
awa/plugins/awa-mail/src/awa-mail-modules.adb
awa/plugins/awa-mail/src/awa-mail-modules.adb
----------------------------------------------------------------------- -- awa-mail -- Mail module -- Copyright (C) 2011, 2012, 2015, 2017 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with AWA.Modules.Beans; with AWA.Modules.Get; with AWA.Mail.Beans; with AWA.Mail.Components.Factory; with AWA.Applications; with ASF.Servlets; with ASF.Requests.Mockup; with ASF.Responses.Mockup; with Util.Beans.Basic; with Util.Beans.Objects; with Util.Log.Loggers; package body AWA.Mail.Modules is Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("AWA.Mail.Module"); package Register is new AWA.Modules.Beans (Module => Mail_Module, Module_Access => Mail_Module_Access); -- ------------------------------ -- Initialize the mail module. -- ------------------------------ overriding procedure Initialize (Plugin : in out Mail_Module; App : in AWA.Modules.Application_Access; Props : in ASF.Applications.Config) is begin Log.Info ("Initializing the mail module"); -- Add the Mail UI components. App.Add_Components (AWA.Mail.Components.Factory.Definition); -- Register here any bean class, servlet, filter. Register.Register (Plugin => Plugin, Name => "AWA.Mail.Beans.Mail_Bean", Handler => AWA.Mail.Beans.Create_Mail_Bean'Access); AWA.Modules.Module (Plugin).Initialize (App, Props); end Initialize; -- ------------------------------ -- Configures the module after its initialization and after having read its XML configuration. -- ------------------------------ overriding procedure Configure (Plugin : in out Mail_Module; Props : in ASF.Applications.Config) is Mailer : constant String := Props.Get ("mailer", "smtp"); begin Log.Info ("Mail plugin is using {0} mailer", Mailer); Plugin.Mailer := AWA.Mail.Clients.Factory (Mailer, Props); end Configure; -- ------------------------------ -- Create a new mail message. -- ------------------------------ function Create_Message (Plugin : in Mail_Module) return AWA.Mail.Clients.Mail_Message_Access is begin return Plugin.Mailer.Create_Message; end Create_Message; -- ------------------------------ -- Receive an event sent by another module with <b>Send_Event</b> method. -- Format and send an email. -- ------------------------------ procedure Send_Mail (Plugin : in Mail_Module; Template : in String; Props : in Util.Beans.Objects.Maps.Map; Content : in AWA.Events.Module_Event'Class) is Name : constant String := Content.Get_Parameter ("name"); begin Log.Info ("Receive event {0} with template {1}", Name, Template); if Template = "" then Log.Debug ("No email template associated with event {0}", Name); return; end if; declare Req : ASF.Requests.Mockup.Request; Reply : ASF.Responses.Mockup.Response; Ptr : constant Util.Beans.Basic.Readonly_Bean_Access := Content'Unrestricted_Access; Bean : constant Util.Beans.Objects.Object := Util.Beans.Objects.To_Object (Ptr, Util.Beans.Objects.STATIC); Dispatcher : constant ASF.Servlets.Request_Dispatcher := Plugin.Get_Application.Get_Request_Dispatcher (Template); begin Req.Set_Request_URI (Template); Req.Set_Method ("GET"); Req.Set_Attribute (Name => "event", Value => Bean); Req.Set_Attributes (Props); ASF.Servlets.Forward (Dispatcher, Req, Reply); end; end Send_Mail; -- ------------------------------ -- Get the mail module instance associated with the current application. -- ------------------------------ function Get_Mail_Module return Mail_Module_Access is function Get is new AWA.Modules.Get (Mail_Module, Mail_Module_Access, NAME); begin return Get; end Get_Mail_Module; end AWA.Mail.Modules;
----------------------------------------------------------------------- -- awa-mail -- Mail module -- Copyright (C) 2011, 2012, 2015, 2017, 2018 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with AWA.Modules.Beans; with AWA.Modules.Get; with AWA.Mail.Beans; with AWA.Mail.Components.Factory; with AWA.Applications; with Servlet.Core; with ASF.Requests.Mockup; with ASF.Responses.Mockup; with Util.Beans.Basic; with Util.Beans.Objects; with Util.Log.Loggers; package body AWA.Mail.Modules is Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("AWA.Mail.Module"); package Register is new AWA.Modules.Beans (Module => Mail_Module, Module_Access => Mail_Module_Access); -- ------------------------------ -- Initialize the mail module. -- ------------------------------ overriding procedure Initialize (Plugin : in out Mail_Module; App : in AWA.Modules.Application_Access; Props : in ASF.Applications.Config) is begin Log.Info ("Initializing the mail module"); -- Add the Mail UI components. App.Add_Components (AWA.Mail.Components.Factory.Definition); -- Register here any bean class, servlet, filter. Register.Register (Plugin => Plugin, Name => "AWA.Mail.Beans.Mail_Bean", Handler => AWA.Mail.Beans.Create_Mail_Bean'Access); AWA.Modules.Module (Plugin).Initialize (App, Props); end Initialize; -- ------------------------------ -- Configures the module after its initialization and after having read its XML configuration. -- ------------------------------ overriding procedure Configure (Plugin : in out Mail_Module; Props : in ASF.Applications.Config) is Mailer : constant String := Props.Get ("mailer", "smtp"); begin Log.Info ("Mail plugin is using {0} mailer", Mailer); Plugin.Mailer := AWA.Mail.Clients.Factory (Mailer, Props); end Configure; -- ------------------------------ -- Create a new mail message. -- ------------------------------ function Create_Message (Plugin : in Mail_Module) return AWA.Mail.Clients.Mail_Message_Access is begin return Plugin.Mailer.Create_Message; end Create_Message; -- ------------------------------ -- Receive an event sent by another module with <b>Send_Event</b> method. -- Format and send an email. -- ------------------------------ procedure Send_Mail (Plugin : in Mail_Module; Template : in String; Props : in Util.Beans.Objects.Maps.Map; Content : in AWA.Events.Module_Event'Class) is Name : constant String := Content.Get_Parameter ("name"); begin Log.Info ("Receive event {0} with template {1}", Name, Template); if Template = "" then Log.Debug ("No email template associated with event {0}", Name); return; end if; declare Req : ASF.Requests.Mockup.Request; Reply : ASF.Responses.Mockup.Response; Ptr : constant Util.Beans.Basic.Readonly_Bean_Access := Content'Unrestricted_Access; Bean : constant Util.Beans.Objects.Object := Util.Beans.Objects.To_Object (Ptr, Util.Beans.Objects.STATIC); Dispatcher : constant Servlet.Core.Request_Dispatcher := Plugin.Get_Application.Get_Request_Dispatcher (Template); begin Req.Set_Request_URI (Template); Req.Set_Method ("GET"); Req.Set_Attribute (Name => "event", Value => Bean); Req.Set_Attributes (Props); Servlet.Core.Forward (Dispatcher, Req, Reply); end; end Send_Mail; -- ------------------------------ -- Get the mail module instance associated with the current application. -- ------------------------------ function Get_Mail_Module return Mail_Module_Access is function Get is new AWA.Modules.Get (Mail_Module, Mail_Module_Access, NAME); begin return Get; end Get_Mail_Module; end AWA.Mail.Modules;
Use the Servlet.Core package instread of ASF.Servlets
Use the Servlet.Core package instread of ASF.Servlets
Ada
apache-2.0
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
22e850324917ee3d3ac0fad5895894ebd4c700c5
regtests/security-policies-tests.adb
regtests/security-policies-tests.adb
----------------------------------------------------------------------- -- Security-policies-tests - Unit tests for Security.Permissions -- Copyright (C) 2011, 2012 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Tests; with Util.Files; with Util.Test_Caller; with Util.Measures; with Security.Contexts; with Security.Policies.Roles; package body Security.Policies.Tests is use Util.Tests; package Caller is new Util.Test_Caller (Test, "Security.Policies"); procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is begin Caller.Add_Test (Suite, "Test Security.Permissions.Create_Role", Test_Create_Role'Access); Caller.Add_Test (Suite, "Test Security.Permissions.Has_Permission", Test_Has_Permission'Access); Caller.Add_Test (Suite, "Test Security.Permissions.Read_Policy", Test_Read_Policy'Access); -- These tests are identical but registered under different names -- for the test documentation. Caller.Add_Test (Suite, "Test Security.Contexts.Has_Permission", Test_Role_Policy'Access); Caller.Add_Test (Suite, "Test Security.Controllers.Roles.Has_Permission", Test_Role_Policy'Access); Caller.Add_Test (Suite, "Test Security.Permissions.Role_Policy", Test_Role_Policy'Access); end Add_Tests; -- ------------------------------ -- Returns true if the given permission is stored in the user principal. -- ------------------------------ function Has_Role (User : in Test_Principal; Role : in Security.Policies.Roles.Role_Type) return Boolean is begin return User.Roles (Role); end Has_Role; -- ------------------------------ -- Get the principal name. -- ------------------------------ function Get_Name (From : in Test_Principal) return String is begin return Util.Strings.To_String (From.Name); end Get_Name; -- ------------------------------ -- Test Create_Role and Get_Role_Name -- ------------------------------ procedure Test_Create_Role (T : in out Test) is use Security.Policies.Roles; M : Security.Policies.Roles.Role_Policy; Role : Role_Type; begin M.Create_Role (Name => "admin", Role => Role); Assert_Equals (T, "admin", M.Get_Role_Name (Role), "Invalid name"); for I in Role + 1 .. Role_Type'Last loop declare Name : constant String := "admin-" & Role_Type'Image (I); Role2 : Role_Type; begin Role2 := M.Find_Role ("admin"); T.Assert (Role2 = Role, "Find_Role returned an invalid role"); M.Create_Role (Name => Name, Role => Role2); Assert_Equals (T, Name, M.Get_Role_Name (Role2), "Invalid name"); end; end loop; end Test_Create_Role; -- ------------------------------ -- Test Has_Permission -- ------------------------------ procedure Test_Has_Permission (T : in out Test) is M : Security.Policies.Policy_Manager (1); Perm : Permissions.Permission_Type; User : Test_Principal; begin -- T.Assert (not M.Has_Permission (User, 1), "User has a non-existing permission"); null; end Test_Has_Permission; -- ------------------------------ -- Test reading policy files -- ------------------------------ procedure Test_Read_Policy (T : in out Test) is M : aliased Security.Policies.Policy_Manager (Max_Policies => 2); Dir : constant String := "regtests/files/permissions/"; Path : constant String := Util.Tests.Get_Path (Dir); User : aliased Test_Principal; Admin_Perm : Policies.Roles.Role_Type; Manager_Perm : Policies.Roles.Role_Type; Context : aliased Security.Contexts.Security_Context; R : Security.Policies.Roles.Role_Policy_Access := new Roles.Role_Policy; begin M.Add_Policy (R.all'Access); M.Read_Policy (Util.Files.Compose (Path, "empty.xml")); R.Add_Role_Type (Name => "admin", Result => Admin_Perm); R.Add_Role_Type (Name => "manager", Result => Manager_Perm); M.Read_Policy (Util.Files.Compose (Path, "simple-policy.xml")); User.Roles (Admin_Perm) := True; Context.Set_Context (Manager => M'Unchecked_Access, Principal => User'Unchecked_Access); -- declare -- S : Util.Measures.Stamp; -- begin -- for I in 1 .. 1_000 loop -- declare -- URI : constant String := "/admin/home/" & Util.Strings.Image (I) & "/l.html"; -- P : constant URI_Permission (URI'Length) -- := URI_Permission '(Len => URI'Length, URI => URI); -- begin -- T.Assert (M.Has_Permission (Context => Context'Unchecked_Access, -- Permission => P), "Permission not granted"); -- end; -- end loop; -- Util.Measures.Report (S, "Has_Permission (1000 calls, cache miss)"); -- end; -- -- declare -- S : Util.Measures.Stamp; -- begin -- for I in 1 .. 1_000 loop -- declare -- URI : constant String := "/admin/home/list.html"; -- P : constant URI_Permission (URI'Length) -- := URI_Permission '(Len => URI'Length, URI => URI); -- begin -- T.Assert (M.Has_Permission (Context => Context'Unchecked_Access, -- Permission => P), "Permission not granted"); -- end; -- end loop; -- Util.Measures.Report (S, "Has_Permission (1000 calls, cache hit)"); -- end; end Test_Read_Policy; -- ------------------------------ -- Read the policy file <b>File</b> and perform a test on the given URI -- with a user having the given role. -- ------------------------------ procedure Check_Policy (T : in out Test; File : in String; Role : in String; URI : in String) is M : aliased Security.Policies.Policy_Manager (1); Dir : constant String := "regtests/files/permissions/"; Path : constant String := Util.Tests.Get_Path (Dir); User : aliased Test_Principal; Admin_Perm : Roles.Role_Type; Context : aliased Security.Contexts.Security_Context; begin M.Read_Policy (Util.Files.Compose (Path, File)); -- -- Admin_Perm := M.Find_Role (Role); -- -- Context.Set_Context (Manager => M'Unchecked_Access, -- Principal => User'Unchecked_Access); -- -- declare -- P : constant URI_Permission (URI'Length) -- := URI_Permission '(Len => URI'Length, URI => URI); -- begin -- -- A user without the role should not have the permission. -- T.Assert (not M.Has_Permission (Context => Context'Unchecked_Access, -- Permission => P), -- "Permission was granted for user without role. URI=" & URI); -- -- -- Set the role. -- User.Roles (Admin_Perm) := True; -- T.Assert (M.Has_Permission (Context => Context'Unchecked_Access, -- Permission => P), -- "Permission was not granted for user with role. URI=" & URI); -- end; end Check_Policy; -- ------------------------------ -- Test reading policy files and using the <role-permission> controller -- ------------------------------ procedure Test_Role_Policy (T : in out Test) is begin T.Check_Policy (File => "policy-with-role.xml", Role => "developer", URI => "/developer/user-should-have-developer-role"); T.Check_Policy (File => "policy-with-role.xml", Role => "manager", URI => "/developer/user-should-have-manager-role"); T.Check_Policy (File => "policy-with-role.xml", Role => "manager", URI => "/manager/user-should-have-manager-role"); T.Check_Policy (File => "policy-with-role.xml", Role => "admin", URI => "/manager/user-should-have-admin-role"); T.Check_Policy (File => "policy-with-role.xml", Role => "admin", URI => "/admin/user-should-have-admin-role"); end Test_Role_Policy; end Security.Policies.Tests;
----------------------------------------------------------------------- -- Security-policies-tests - Unit tests for Security.Permissions -- Copyright (C) 2011, 2012 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Tests; with Util.Files; with Util.Test_Caller; with Util.Measures; with Security.Contexts; with Security.Policies.Roles; package body Security.Policies.Tests is use Util.Tests; package Caller is new Util.Test_Caller (Test, "Security.Policies"); procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is begin Caller.Add_Test (Suite, "Test Security.Permissions.Create_Role", Test_Create_Role'Access); Caller.Add_Test (Suite, "Test Security.Permissions.Has_Permission", Test_Has_Permission'Access); Caller.Add_Test (Suite, "Test Security.Permissions.Read_Policy", Test_Read_Policy'Access); Caller.Add_Test (Suite, "Test Security.Policies.Roles.Set_Roles", Test_Set_Roles'Access); -- These tests are identical but registered under different names -- for the test documentation. Caller.Add_Test (Suite, "Test Security.Contexts.Has_Permission", Test_Role_Policy'Access); Caller.Add_Test (Suite, "Test Security.Controllers.Roles.Has_Permission", Test_Role_Policy'Access); Caller.Add_Test (Suite, "Test Security.Permissions.Role_Policy", Test_Role_Policy'Access); end Add_Tests; -- ------------------------------ -- Returns true if the given permission is stored in the user principal. -- ------------------------------ function Has_Role (User : in Test_Principal; Role : in Security.Policies.Roles.Role_Type) return Boolean is begin return User.Roles (Role); end Has_Role; -- ------------------------------ -- Get the principal name. -- ------------------------------ function Get_Name (From : in Test_Principal) return String is begin return Util.Strings.To_String (From.Name); end Get_Name; -- ------------------------------ -- Test Create_Role and Get_Role_Name -- ------------------------------ procedure Test_Create_Role (T : in out Test) is use Security.Policies.Roles; M : Security.Policies.Roles.Role_Policy; Role : Role_Type; begin M.Create_Role (Name => "admin", Role => Role); Assert_Equals (T, "admin", M.Get_Role_Name (Role), "Invalid name"); for I in Role + 1 .. Role_Type'Last loop declare Name : constant String := "admin-" & Role_Type'Image (I); Role2 : Role_Type; begin Role2 := M.Find_Role ("admin"); T.Assert (Role2 = Role, "Find_Role returned an invalid role"); M.Create_Role (Name => Name, Role => Role2); Assert_Equals (T, Name, M.Get_Role_Name (Role2), "Invalid name"); end; end loop; end Test_Create_Role; -- ------------------------------ -- Test Set_Roles -- ------------------------------ procedure Test_Set_Roles (T : in out Test) is use Security.Policies.Roles; M : Security.Policies.Roles.Role_Policy; Role : Role_Type; Map : Role_Map; begin M.Create_Role (Name => "manager", Role => Role); M.Create_Role (Name => "admin", Role => Role); Assert_Equals (T, "admin", M.Get_Role_Name (Role), "Invalid name"); M.Set_Roles ("admin", Map); end Test_Set_Roles; -- ------------------------------ -- Test Has_Permission -- ------------------------------ procedure Test_Has_Permission (T : in out Test) is M : Security.Policies.Policy_Manager (1); Perm : Permissions.Permission_Type; User : Test_Principal; begin -- T.Assert (not M.Has_Permission (User, 1), "User has a non-existing permission"); null; end Test_Has_Permission; -- ------------------------------ -- Test reading policy files -- ------------------------------ procedure Test_Read_Policy (T : in out Test) is M : aliased Security.Policies.Policy_Manager (Max_Policies => 2); Dir : constant String := "regtests/files/permissions/"; Path : constant String := Util.Tests.Get_Path (Dir); User : aliased Test_Principal; Admin_Perm : Policies.Roles.Role_Type; Manager_Perm : Policies.Roles.Role_Type; Context : aliased Security.Contexts.Security_Context; R : Security.Policies.Roles.Role_Policy_Access := new Roles.Role_Policy; begin M.Add_Policy (R.all'Access); M.Read_Policy (Util.Files.Compose (Path, "empty.xml")); R.Add_Role_Type (Name => "admin", Result => Admin_Perm); R.Add_Role_Type (Name => "manager", Result => Manager_Perm); M.Read_Policy (Util.Files.Compose (Path, "simple-policy.xml")); User.Roles (Admin_Perm) := True; Context.Set_Context (Manager => M'Unchecked_Access, Principal => User'Unchecked_Access); -- declare -- S : Util.Measures.Stamp; -- begin -- for I in 1 .. 1_000 loop -- declare -- URI : constant String := "/admin/home/" & Util.Strings.Image (I) & "/l.html"; -- P : constant URI_Permission (URI'Length) -- := URI_Permission '(Len => URI'Length, URI => URI); -- begin -- T.Assert (M.Has_Permission (Context => Context'Unchecked_Access, -- Permission => P), "Permission not granted"); -- end; -- end loop; -- Util.Measures.Report (S, "Has_Permission (1000 calls, cache miss)"); -- end; -- -- declare -- S : Util.Measures.Stamp; -- begin -- for I in 1 .. 1_000 loop -- declare -- URI : constant String := "/admin/home/list.html"; -- P : constant URI_Permission (URI'Length) -- := URI_Permission '(Len => URI'Length, URI => URI); -- begin -- T.Assert (M.Has_Permission (Context => Context'Unchecked_Access, -- Permission => P), "Permission not granted"); -- end; -- end loop; -- Util.Measures.Report (S, "Has_Permission (1000 calls, cache hit)"); -- end; end Test_Read_Policy; -- ------------------------------ -- Read the policy file <b>File</b> and perform a test on the given URI -- with a user having the given role. -- ------------------------------ procedure Check_Policy (T : in out Test; File : in String; Role : in String; URI : in String) is M : aliased Security.Policies.Policy_Manager (1); Dir : constant String := "regtests/files/permissions/"; Path : constant String := Util.Tests.Get_Path (Dir); User : aliased Test_Principal; Admin_Perm : Roles.Role_Type; Context : aliased Security.Contexts.Security_Context; begin M.Read_Policy (Util.Files.Compose (Path, File)); -- -- Admin_Perm := M.Find_Role (Role); -- -- Context.Set_Context (Manager => M'Unchecked_Access, -- Principal => User'Unchecked_Access); -- -- declare -- P : constant URI_Permission (URI'Length) -- := URI_Permission '(Len => URI'Length, URI => URI); -- begin -- -- A user without the role should not have the permission. -- T.Assert (not M.Has_Permission (Context => Context'Unchecked_Access, -- Permission => P), -- "Permission was granted for user without role. URI=" & URI); -- -- -- Set the role. -- User.Roles (Admin_Perm) := True; -- T.Assert (M.Has_Permission (Context => Context'Unchecked_Access, -- Permission => P), -- "Permission was not granted for user with role. URI=" & URI); -- end; end Check_Policy; -- ------------------------------ -- Test reading policy files and using the <role-permission> controller -- ------------------------------ procedure Test_Role_Policy (T : in out Test) is begin T.Check_Policy (File => "policy-with-role.xml", Role => "developer", URI => "/developer/user-should-have-developer-role"); T.Check_Policy (File => "policy-with-role.xml", Role => "manager", URI => "/developer/user-should-have-manager-role"); T.Check_Policy (File => "policy-with-role.xml", Role => "manager", URI => "/manager/user-should-have-manager-role"); T.Check_Policy (File => "policy-with-role.xml", Role => "admin", URI => "/manager/user-should-have-admin-role"); T.Check_Policy (File => "policy-with-role.xml", Role => "admin", URI => "/admin/user-should-have-admin-role"); end Test_Role_Policy; end Security.Policies.Tests;
Implement the new unit test for Set_Roles
Implement the new unit test for Set_Roles
Ada
apache-2.0
Letractively/ada-security
4f33a73150003d0648debde2063fba3db87b18f9
regtests/util-http-clients-tests.adb
regtests/util-http-clients-tests.adb
----------------------------------------------------------------------- -- util-http-clients-tests -- Unit tests for HTTP client -- Copyright (C) 2012 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Test_Caller; with Util.Strings.Transforms; with Util.Http.Tools; with Util.Strings; with Util.Log.Loggers; package body Util.Http.Clients.Tests is -- The logger Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("Util.Http.Clients.Tests"); package body Http_Tests is package Caller is new Util.Test_Caller (Http_Test, "Http-" & NAME); procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is begin Caller.Add_Test (Suite, "Test Util.Http.Clients." & NAME & ".Get", Test_Http_Get'Access); Caller.Add_Test (Suite, "Test Util.Http.Clients." & NAME & ".Post", Test_Http_Post'Access); end Add_Tests; overriding procedure Set_Up (T : in out Http_Test) is begin Test (T).Set_Up; Register; end Set_Up; end Http_Tests; overriding procedure Set_Up (T : in out Test) is begin Log.Info ("Starting test server"); T.Server := new Test_Server; T.Server.Start; end Set_Up; overriding procedure Tear_Down (T : in out Test) is begin if T.Server /= null then Log.Info ("Stopping test server"); T.Server.Stop; T.Server := null; end if; end Tear_Down; -- ------------------------------ -- Process the line received by the server. -- ------------------------------ overriding procedure Process_Line (Into : in out Test_Server; Line : in Ada.Strings.Unbounded.Unbounded_String; Stream : in out Util.Streams.Texts.Reader_Stream'Class; Client : in out Util.Streams.Sockets.Socket_Stream'Class) is L : constant String := Ada.Strings.Unbounded.To_String (Line); Pos : Natural := Util.Strings.Index (L, ' '); begin if Pos > 0 and Into.Method = UNKNOWN then if L (L'First .. Pos - 1) = "GET" then Into.Method := GET; elsif L (L'First .. Pos - 1) = "POST" then Into.Method := POST; else Into.Method := UNKNOWN; end if; end if; Pos := Util.Strings.Index (L, ':'); if Pos > 0 then if L (L'First .. Pos) = "Content-Type:" then Into.Content_Type := Ada.Strings.Unbounded.To_Unbounded_String (L (Pos + 2 .. L'Last - 2)); elsif L (L'First .. Pos) = "Content-Length:" then Into.Length := Natural'Value (L (Pos + 1 .. L'Last - 2)); for I in 1 .. Into.Length loop declare C : Character; begin Stream.Read (C); Ada.Strings.Unbounded.Append (Into.Result, C); end; end loop; declare Output : Util.Streams.Texts.Print_Stream; begin Output.Initialize (Client'Unchecked_Access); Output.Write ("HTTP/1.1 204 No Content" & ASCII.CR & ASCII.LF); Output.Write ("Content-Length: 4" & ASCII.CR & ASCII.LF); Output.Write (ASCII.CR & ASCII.LF); Output.Write ("OK" & ASCII.CR & ASCII.LF); Output.Flush; end; end if; end if; Log.Info ("Received: {0}", Line); end Process_Line; -- ------------------------------ -- Get the test server base URI. -- ------------------------------ function Get_Uri (T : in Test) return String is begin return "http://" & T.Server.Get_Host & ":" & Util.Strings.Image (T.Server.Get_Port); end Get_Uri; -- ------------------------------ -- Test the http Get operation. -- ------------------------------ procedure Test_Http_Get (T : in out Test) is Request : Client; Reply : Response; begin Request.Get ("http://www.google.com", Reply); T.Assert (Reply.Get_Status = 200 or Reply.Get_Status = 302, "Get status is invalid"); Util.Http.Tools.Save_Response (Util.Tests.Get_Test_Path ("http_get.txt"), Reply, True); -- Check the content. declare Content : constant String := Util.Strings.Transforms.To_Lower_Case (Reply.Get_Body); begin Util.Tests.Assert_Matches (T, ".*html.*", Content, "Invalid GET content"); end; -- Check one header. declare Content : constant String := Reply.Get_Header ("Content-Type"); begin T.Assert (Content'Length > 0, "Empty Content-Type header"); Util.Tests.Assert_Matches (T, ".*text/html.*", Content, "Invalid content type"); end; end Test_Http_Get; -- ------------------------------ -- Test the http POST operation. -- ------------------------------ procedure Test_Http_Post (T : in out Test) is Request : Client; Reply : Response; Uri : constant String := T.Get_Uri; begin Log.Info ("Post on " & Uri); T.Server.Method := UNKNOWN; Request.Post (Uri & "/post", "p1=1", Reply); T.Assert (T.Server.Method = POST, "Invalid method received by server"); Util.Tests.Assert_Equals (T, "application/x-www-form-urlencoded", T.Server.Content_Type, "Invalid content type received by server"); Util.Tests.Assert_Equals (T, "OK" & ASCII.CR & ASCII.LF, Reply.Get_Body, "Invalid response"); Util.Http.Tools.Save_Response (Util.Tests.Get_Test_Path ("http_post.txt"), Reply, True); end Test_Http_Post; end Util.Http.Clients.Tests;
----------------------------------------------------------------------- -- util-http-clients-tests -- Unit tests for HTTP client -- Copyright (C) 2012 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Test_Caller; with Util.Strings.Transforms; with Util.Http.Tools; with Util.Strings; with Util.Log.Loggers; package body Util.Http.Clients.Tests is -- The logger Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("Util.Http.Clients.Tests"); package body Http_Tests is package Caller is new Util.Test_Caller (Http_Test, "Http-" & NAME); procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is begin Caller.Add_Test (Suite, "Test Util.Http.Clients." & NAME & ".Get", Test_Http_Get'Access); Caller.Add_Test (Suite, "Test Util.Http.Clients." & NAME & ".Post", Test_Http_Post'Access); end Add_Tests; overriding procedure Set_Up (T : in out Http_Test) is begin Test (T).Set_Up; Register; end Set_Up; end Http_Tests; overriding procedure Set_Up (T : in out Test) is begin Log.Info ("Starting test server"); T.Server := new Test_Server; T.Server.Start; end Set_Up; overriding procedure Tear_Down (T : in out Test) is begin if T.Server /= null then Log.Info ("Stopping test server"); T.Server.Stop; T.Server := null; end if; end Tear_Down; -- ------------------------------ -- Process the line received by the server. -- ------------------------------ overriding procedure Process_Line (Into : in out Test_Server; Line : in Ada.Strings.Unbounded.Unbounded_String; Stream : in out Util.Streams.Texts.Reader_Stream'Class; Client : in out Util.Streams.Sockets.Socket_Stream'Class) is L : constant String := Ada.Strings.Unbounded.To_String (Line); Pos : Natural := Util.Strings.Index (L, ' '); begin if Pos > 0 and Into.Method = UNKNOWN then if L (L'First .. Pos - 1) = "GET" then Into.Method := GET; elsif L (L'First .. Pos - 1) = "POST" then Into.Method := POST; else Into.Method := UNKNOWN; end if; end if; Pos := Util.Strings.Index (L, ':'); if Pos > 0 then if L (L'First .. Pos) = "Content-Type:" then Into.Content_Type := Ada.Strings.Unbounded.To_Unbounded_String (L (Pos + 2 .. L'Last - 2)); elsif L (L'First .. Pos) = "Content-Length:" then Into.Length := Natural'Value (L (Pos + 1 .. L'Last - 2)); end if; end if; if L'Length = 2 and then Into.Length > 0 then for I in 1 .. Into.Length loop declare C : Character; begin Stream.Read (C); Ada.Strings.Unbounded.Append (Into.Result, C); end; end loop; declare Output : Util.Streams.Texts.Print_Stream; begin Output.Initialize (Client'Unchecked_Access); Output.Write ("HTTP/1.1 204 No Content" & ASCII.CR & ASCII.LF); Output.Write ("Content-Length: 4" & ASCII.CR & ASCII.LF); Output.Write (ASCII.CR & ASCII.LF); Output.Write ("OK" & ASCII.CR & ASCII.LF); Output.Flush; end; end if; Log.Info ("Received: {0}", L); end Process_Line; -- ------------------------------ -- Get the test server base URI. -- ------------------------------ function Get_Uri (T : in Test) return String is begin return "http://" & T.Server.Get_Host & ":" & Util.Strings.Image (T.Server.Get_Port); end Get_Uri; -- ------------------------------ -- Test the http Get operation. -- ------------------------------ procedure Test_Http_Get (T : in out Test) is Request : Client; Reply : Response; begin Request.Get ("http://www.google.com", Reply); T.Assert (Reply.Get_Status = 200 or Reply.Get_Status = 302, "Get status is invalid"); Util.Http.Tools.Save_Response (Util.Tests.Get_Test_Path ("http_get.txt"), Reply, True); -- Check the content. declare Content : constant String := Util.Strings.Transforms.To_Lower_Case (Reply.Get_Body); begin Util.Tests.Assert_Matches (T, ".*html.*", Content, "Invalid GET content"); end; -- Check one header. declare Content : constant String := Reply.Get_Header ("Content-Type"); begin T.Assert (Content'Length > 0, "Empty Content-Type header"); Util.Tests.Assert_Matches (T, ".*text/html.*", Content, "Invalid content type"); end; end Test_Http_Get; -- ------------------------------ -- Test the http POST operation. -- ------------------------------ procedure Test_Http_Post (T : in out Test) is Request : Client; Reply : Response; Uri : constant String := T.Get_Uri; begin Log.Info ("Post on " & Uri); T.Server.Method := UNKNOWN; Request.Post (Uri & "/post", "p1=1", Reply); T.Assert (T.Server.Method = POST, "Invalid method received by server"); Util.Tests.Assert_Equals (T, "application/x-www-form-urlencoded", T.Server.Content_Type, "Invalid content type received by server"); Util.Tests.Assert_Equals (T, "OK" & ASCII.CR & ASCII.LF, Reply.Get_Body, "Invalid response"); Util.Http.Tools.Save_Response (Util.Tests.Get_Test_Path ("http_post.txt"), Reply, True); end Test_Http_Post; end Util.Http.Clients.Tests;
Fix the embedded http server
Fix the embedded http server
Ada
apache-2.0
stcarrez/ada-util,stcarrez/ada-util
0756e546acfa72d7a1b9250d449f657a145a8b07
src/el-methods-proc_1.ads
src/el-methods-proc_1.ads
----------------------------------------------------------------------- -- EL.Methods.Proc_1 -- Procedure Binding with 1 argument -- Copyright (C) 2010, 2011 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with EL.Expressions; with EL.Contexts; with Util.Beans.Methods; with Util.Beans.Basic; generic type Param1_Type (<>) is limited private; package EL.Methods.Proc_1 is use Util.Beans.Methods; -- Returns True if the method is a valid method which accepts the arguments -- defined by the package instantiation. function Is_Valid (Method : in EL.Expressions.Method_Info) return Boolean; -- Execute the method describe by the method expression -- and with the given context. The method signature is: -- -- procedure F (Obj : in out <Bean>; -- Param : in out Param1_Type); -- -- where <Bean> inherits from <b>Readonly_Bean</b> -- (See <b>Bind</b> package) -- -- Raises <b>Invalid_Method</b> if the method referenced by -- the method expression does not exist or does not match -- the signature. procedure Execute (Method : in EL.Expressions.Method_Expression'Class; Param : in out Param1_Type; Context : in EL.Contexts.ELContext'Class); -- Execute the method describe by the method binding object. -- The method signature is: -- -- procedure F (Obj : in out <Bean>; -- Param : in out Param1_Type); -- -- where <Bean> inherits from <b>Readonly_Bean</b> -- (See <b>Bind</b> package) -- -- Raises <b>Invalid_Method</b> if the method referenced by -- the method expression does not exist or does not match -- the signature. procedure Execute (Method : in EL.Expressions.Method_Info; Param : in out Param1_Type); -- Function access to the proxy. type Proxy_Access is access procedure (O : access Util.Beans.Basic.Readonly_Bean'Class; P : in out Param1_Type); -- The binding record which links the method name -- to the proxy function. type Binding is new Method_Binding with record Method : Proxy_Access; end record; type Binding_Access is access constant Binding; -- Proxy for the binding. -- The proxy declares the binding definition that links -- the name to the function and it implements the necessary -- object conversion to translate the <b>Readonly_Bean</b> -- object to the target object type. generic -- Name of the method (as exposed in the EL expression) Name : String; -- The bean type type Bean is new Util.Beans.Basic.Readonly_Bean with private; -- The bean method to invoke with procedure Method (O : in out Bean; P1 : in out Param1_Type); package Bind is -- Method that <b>Execute</b> will invoke. procedure Method_Access (O : access Util.Beans.Basic.Readonly_Bean'Class; P1 : in out Param1_Type); F_NAME : aliased constant String := Name; -- The proxy binding that can be exposed through -- the <b>Method_Bean</b> interface. Proxy : aliased constant Binding := Binding '(Name => F_NAME'Access, Method => Method_Access'Access); end Bind; end EL.Methods.Proc_1;
----------------------------------------------------------------------- -- EL.Methods.Proc_1 -- Procedure Binding with 1 argument -- Copyright (C) 2010, 2011, 2012, 2013 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with EL.Expressions; with EL.Contexts; with Util.Beans.Methods; with Util.Beans.Basic; generic type Param1_Type (<>) is limited private; package EL.Methods.Proc_1 is use Util.Beans.Methods; -- Returns True if the method is a valid method which accepts the arguments -- defined by the package instantiation. function Is_Valid (Method : in EL.Expressions.Method_Info) return Boolean; -- Execute the method describe by the method expression -- and with the given context. The method signature is: -- -- procedure F (Obj : in out <Bean>; -- Param : in out Param1_Type); -- -- where <Bean> inherits from <b>Readonly_Bean</b> -- (See <b>Bind</b> package) -- -- Raises <b>Invalid_Method</b> if the method referenced by -- the method expression does not exist or does not match -- the signature. procedure Execute (Method : in EL.Expressions.Method_Expression'Class; Param : in out Param1_Type; Context : in EL.Contexts.ELContext'Class); -- Execute the method describe by the method binding object. -- The method signature is: -- -- procedure F (Obj : in out <Bean>; -- Param : in out Param1_Type); -- -- where <Bean> inherits from <b>Readonly_Bean</b> -- (See <b>Bind</b> package) -- -- Raises <b>Invalid_Method</b> if the method referenced by -- the method expression does not exist or does not match -- the signature. procedure Execute (Method : in EL.Expressions.Method_Info; Param : in out Param1_Type); -- Function access to the proxy. type Proxy_Access is access procedure (O : access Util.Beans.Basic.Readonly_Bean'Class; P : in out Param1_Type); -- The binding record which links the method name -- to the proxy function. type Binding is new Method_Binding with record Method : Proxy_Access; end record; type Binding_Access is access constant Binding; -- Proxy for the binding. -- The proxy declares the binding definition that links -- the name to the function and it implements the necessary -- object conversion to translate the <b>Readonly_Bean</b> -- object to the target object type. generic -- Name of the method (as exposed in the EL expression) Name : String; -- The bean type type Bean is abstract new Util.Beans.Basic.Readonly_Bean with private; -- The bean method to invoke with procedure Method (O : in out Bean; P1 : in out Param1_Type); package Bind is -- Method that <b>Execute</b> will invoke. procedure Method_Access (O : access Util.Beans.Basic.Readonly_Bean'Class; P1 : in out Param1_Type); F_NAME : aliased constant String := Name; -- The proxy binding that can be exposed through -- the <b>Method_Bean</b> interface. Proxy : aliased constant Binding := Binding '(Name => F_NAME'Access, Method => Method_Access'Access); end Bind; end EL.Methods.Proc_1;
Allow the Bean type to be an abstract generic type
Allow the Bean type to be an abstract generic type
Ada
apache-2.0
stcarrez/ada-el
c8e0a80604d741570031a4ba278fa3bf96ee46b9
regtests/ado-parameters-tests.adb
regtests/ado-parameters-tests.adb
----------------------------------------------------------------------- -- ado-parameters-tests -- Test query parameters and SQL expansion -- Copyright (C) 2011, 2015, 2017 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Test_Caller; with Util.Measures; with ADO.Caches.Discrete; with ADO.Caches; package body ADO.Parameters.Tests is use Util.Tests; package Int_Cache is new ADO.Caches.Discrete (Element_Type => Integer); type Dialect is new ADO.Drivers.Dialects.Dialect with null record; -- Check if the string is a reserved keyword. overriding function Is_Reserved (D : in Dialect; Name : in String) return Boolean; -- Test the Add_Param operation for various types. generic type T (<>) is private; with procedure Add_Param (L : in out ADO.Parameters.Abstract_List; V : in T) is <>; Value : T; Name : String; procedure Test_Add_Param_T (Tst : in out Test); -- Test the Bind_Param operation for various types. generic type T (<>) is private; with procedure Bind_Param (L : in out ADO.Parameters.Abstract_List; N : in String; V : in T) is <>; Value : T; Name : String; procedure Test_Bind_Param_T (Tst : in out Test); -- Test the Add_Param operation for various types. procedure Test_Add_Param_T (Tst : in out Test) is Count : constant Positive := 100; SQL : ADO.Parameters.List; S : Util.Measures.Stamp; begin for I in 1 .. Count loop Add_Param (ADO.Parameters.Abstract_List (SQL), Value); end loop; Util.Measures.Report (S, "Add_Param " & Name & "(" & Positive'Image (Count) & " calls)"); Util.Tests.Assert_Equals (Tst, Count, SQL.Length, "Invalid param list for " & Name); end Test_Add_Param_T; -- Test the Bind_Param operation for various types. procedure Test_Bind_Param_T (Tst : in out Test) is Count : constant Positive := 100; SQL : ADO.Parameters.List; S : Util.Measures.Stamp; begin for I in 1 .. Count loop Bind_Param (ADO.Parameters.Abstract_List (SQL), "a_parameter_name", Value); end loop; Util.Measures.Report (S, "Bind_Param " & Name & "(" & Positive'Image (Count) & " calls)"); Util.Tests.Assert_Equals (Tst, 1, SQL.Length, "Invalid param list for " & Name); end Test_Bind_Param_T; procedure Test_Add_Param_Integer is new Test_Add_Param_T (Integer, Add_Param, 10, "Integer"); procedure Test_Add_Param_Long_Long_Integer is new Test_Add_Param_T (Long_Long_Integer, Add_Param, 10_000_000_000_000, "Long_Long_Integer"); procedure Test_Add_Param_Identifier is new Test_Add_Param_T (Identifier, Add_Param, 100, "Identifier"); procedure Test_Add_Param_Boolean is new Test_Add_Param_T (Boolean, Add_Param, False, "Boolean"); procedure Test_Add_Param_String is new Test_Add_Param_T (String, Add_Param, "0123456789ABCDEF", "String"); procedure Test_Add_Param_Calendar is new Test_Add_Param_T (Ada.Calendar.Time, Add_Param, Ada.Calendar.Clock, "Time"); procedure Test_Add_Param_Unbounded_String is new Test_Add_Param_T (Unbounded_String, Add_Param, To_Unbounded_String ("0123456789ABCDEF"), "Unbounded_String"); procedure Test_Bind_Param_Integer is new Test_Bind_Param_T (Integer, Bind_Param, 10, "Integer"); procedure Test_Bind_Param_Long_Long_Integer is new Test_Bind_Param_T (Long_Long_Integer, Bind_Param, 10_000_000_000_000, "Long_Long_Integer"); procedure Test_Bind_Param_Identifier is new Test_Bind_Param_T (Identifier, Bind_Param, 100, "Identifier"); procedure Test_Bind_Param_Entity_Type is new Test_Bind_Param_T (Entity_Type, Bind_Param, 100, "Entity_Type"); procedure Test_Bind_Param_Boolean is new Test_Bind_Param_T (Boolean, Bind_Param, False, "Boolean"); procedure Test_Bind_Param_String is new Test_Bind_Param_T (String, Bind_Param, "0123456789ABCDEF", "String"); procedure Test_Bind_Param_Calendar is new Test_Bind_Param_T (Ada.Calendar.Time, Bind_Param, Ada.Calendar.Clock, "Time"); procedure Test_Bind_Param_Unbounded_String is new Test_Bind_Param_T (Unbounded_String, Bind_Param, To_Unbounded_String ("0123456789ABCDEF"), "Unbounded_String"); package Caller is new Util.Test_Caller (Test, "ADO.Parameters"); procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is begin Caller.Add_Test (Suite, "Test ADO.Parameters.Expand", Test_Expand_Sql'Access); Caller.Add_Test (Suite, "Test ADO.Parameters.Expand (invalid params)", Test_Expand_Error'Access); Caller.Add_Test (Suite, "Test ADO.Parameters.Expand (perf)", Test_Expand_Perf'Access); Caller.Add_Test (Suite, "Test ADO.Parameters.Add_Param (Boolean)", Test_Add_Param_Boolean'Access); Caller.Add_Test (Suite, "Test ADO.Parameters.Add_Param (Integer)", Test_Add_Param_Integer'Access); Caller.Add_Test (Suite, "Test ADO.Parameters.Add_Param (Long_Long_Integer)", Test_Add_Param_Long_Long_Integer'Access); Caller.Add_Test (Suite, "Test ADO.Parameters.Add_Param (Identifier)", Test_Add_Param_Identifier'Access); Caller.Add_Test (Suite, "Test ADO.Parameters.Add_Param (Calendar)", Test_Add_Param_Calendar'Access); Caller.Add_Test (Suite, "Test ADO.Parameters.Add_Param (String)", Test_Add_Param_String'Access); Caller.Add_Test (Suite, "Test ADO.Parameters.Add_Param (Unbounded_String)", Test_Add_Param_Unbounded_String'Access); Caller.Add_Test (Suite, "Test ADO.Parameters.Bind_Param (Boolean)", Test_Bind_Param_Boolean'Access); Caller.Add_Test (Suite, "Test ADO.Parameters.Bind_Param (Integer)", Test_Bind_Param_Integer'Access); Caller.Add_Test (Suite, "Test ADO.Parameters.Bind_Param (Long_Long_Integer)", Test_Bind_Param_Long_Long_Integer'Access); Caller.Add_Test (Suite, "Test ADO.Parameters.Bind_Param (Identifier)", Test_Bind_Param_Identifier'Access); Caller.Add_Test (Suite, "Test ADO.Parameters.Bind_Param (Calendar)", Test_Bind_Param_Calendar'Access); Caller.Add_Test (Suite, "Test ADO.Parameters.Bind_Param (String)", Test_Bind_Param_String'Access); Caller.Add_Test (Suite, "Test ADO.Parameters.Bind_Param (Unbounded_String)", Test_Bind_Param_Unbounded_String'Access); Caller.Add_Test (Suite, "Test ADO.Parameters.Bind_Param (Entity_Type)", Test_Bind_Param_Entity_Type'Access); Caller.Add_Test (Suite, "Test ADO.Parameters.Expand (cache expander)", Test_Expand_With_Expander'Access); end Add_Tests; -- ------------------------------ -- Check if the string is a reserved keyword. -- ------------------------------ overriding function Is_Reserved (D : in Dialect; Name : in String) return Boolean is pragma Unreferenced (D, Name); begin return False; end Is_Reserved; -- ------------------------------ -- Test expand SQL with parameters. -- ------------------------------ procedure Test_Expand_Sql (T : in out Test) is SQL : ADO.Parameters.List; D : aliased Dialect; procedure Check (Pattern : in String; Expect : in String); procedure Check (Pattern : in String; Expect : in String) is Result : constant String := SQL.Expand (Pattern); begin Assert_Equals (T, Expect, Result, "Invalid SQL expansion"); end Check; begin SQL.Set_Dialect (D'Unchecked_Access); SQL.Bind_Param (1, "select '"); SQL.Bind_Param (2, "from"); SQL.Bind_Param ("user_id", String '("23")); SQL.Bind_Param ("object_23_identifier", Integer (44)); SQL.Bind_Param ("bool", True); SQL.Bind_Param (6, False); SQL.Bind_Param ("_date", Ada.Calendar.Clock); SQL.Bind_Null_Param ("_null"); Check ("?", "'select '''"); Check (":2", "'from'"); Check (":6", "0"); Check (":user_id", "'23'"); Check (":bool", "1"); Check (":_null", "NULL"); Check ("select :1 :2 :3 :4 :5 :6", "select 'select ''' 'from' '23' 44 1 0"); Check ("select ? ? ? ? ? ?", "select 'select ''' 'from' '23' 44 1 0"); Check ("select ? :2 :user_id :object_23_identifier :bool :6", "select 'select ''' 'from' '23' 44 1 0"); Check ("select \:1 \:2 \:3 \:4 \:5 \:6", "select :1 :2 :3 :4 :5 :6"); end Test_Expand_Sql; -- ------------------------------ -- Test expand with invalid parameters. -- ------------------------------ procedure Test_Expand_Error (T : in out Test) is SQL : ADO.Parameters.List; procedure Check (Pattern : in String; Expect : in String); procedure Check (Pattern : in String; Expect : in String) is Result : constant String := SQL.Expand (Pattern); begin Assert_Equals (T, Expect, Result, "Invalid SQL expansion"); end Check; begin Check (":<", "<"); Check (":234", ""); Check (":name", ""); Check ("select :", "select :"); end Test_Expand_Error; -- ------------------------------ -- Test expand performance. -- ------------------------------ procedure Test_Expand_Perf (T : in out Test) is pragma Unreferenced (T); SQL : ADO.Parameters.List; D : aliased Dialect; begin SQL.Set_Dialect (D'Unchecked_Access); declare T : Util.Measures.Stamp; begin for I in 1 .. 1_000 loop SQL.Bind_Param (I, I); end loop; Util.Measures.Report (T, "Bind_Param (1000 calls)"); end; declare B : constant Unbounded_String := To_Unbounded_String ("select t.a, t.b, t.c, t.d, t.e, t.f " & "from T where t.b = 23"); T : Util.Measures.Stamp; begin for I in 1 .. 1_000 loop declare S : constant String := To_String (B); pragma Unreferenced (S); begin null; end; end loop; Util.Measures.Report (T, "Expand reference To_String"); end; declare T : Util.Measures.Stamp; begin for I in 1 .. 1_000 loop declare S : constant String := SQL.Expand ("select t.a, t.b, t.c, t.d, t.e, t.f " & "from T where t.b = 23"); pragma Unreferenced (S); begin null; end; end loop; Util.Measures.Report (T, "Expand (1000 calls with 0 parameter)"); end; declare T : Util.Measures.Stamp; begin for I in 1 .. 1_000 loop declare S : constant String := SQL.Expand ("select t.a, t.b, t.c, t.d, t.e, t.f " & "from T where t.b = :10"); pragma Unreferenced (S); begin null; end; end loop; Util.Measures.Report (T, "Expand (1000 calls with 1 parameter)"); end; declare T : Util.Measures.Stamp; begin for I in 1 .. 1_000 loop declare S : constant String := SQL.Expand (":10 :20 :30 :40 :50 :60 :70 :80 :90 :100"); pragma Unreferenced (S); begin null; end; end loop; Util.Measures.Report (T, "Expand (1000 calls with 10 parameters)"); end; end Test_Expand_Perf; -- ------------------------------ -- Test expand with cache expander. -- ------------------------------ procedure Test_Expand_With_Expander (T : in out Test) is procedure Check (Content : in String; Expect : in String); SQL : ADO.Parameters.List; D : aliased Dialect; C : aliased ADO.Caches.Cache_Manager; M : access Int_Cache.Cache_Type := new Int_Cache.Cache_Type; P : access Int_Cache.Cache_Type := new Int_Cache.Cache_Type; procedure Check (Content : in String; Expect : in String) is S : constant String := SQL.Expand (Content); begin Util.Tests.Assert_Equals (T, Expect, S, "Invalid expand for SQL '" & Content & "'"); end Check; begin C.Add_Cache ("test-group", M.all'Access); C.Add_Cache ("G2", P.all'Access); SQL.Expander := C'Unchecked_Access; M.Insert ("value-1", 123); M.Insert ("2", 2); M.Insert ("a name", 10); P.Insert ("1", 10); P.Insert ("a", 0); P.Insert ("c", 1); SQL.Set_Dialect (D'Unchecked_Access); Check ("$test-group[2]", "2"); Check ("$test-group[a name]", "10"); Check ("SELECT * FROM user WHERE id = $test-group[2]+$test-group[value-1]", "SELECT * FROM user WHERE id = 2+123"); Check ("SELECT * FROM user WHERE id = $G2[a]+$test-group[value-1]", "SELECT * FROM user WHERE id = 0+123"); P.Insert ("a", 1, True); Check ("SELECT * FROM user WHERE id = $G2[a]+$test-group[value-1]", "SELECT * FROM user WHERE id = 1+123"); Check ("SELECT * FROM user WHERE id = 2$G2[titi]+$test[value-1]1", "SELECT * FROM user WHERE id = 2+1"); end Test_Expand_With_Expander; end ADO.Parameters.Tests;
----------------------------------------------------------------------- -- ado-parameters-tests -- Test query parameters and SQL expansion -- Copyright (C) 2011, 2015, 2017 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Test_Caller; with Util.Measures; with ADO.Caches.Discrete; with ADO.Caches; package body ADO.Parameters.Tests is use Util.Tests; package Int_Cache is new ADO.Caches.Discrete (Element_Type => Integer); type Dialect is new ADO.Drivers.Dialects.Dialect with null record; -- Check if the string is a reserved keyword. overriding function Is_Reserved (D : in Dialect; Name : in String) return Boolean; -- Test the Add_Param operation for various types. generic type T (<>) is private; with procedure Add_Param (L : in out ADO.Parameters.Abstract_List; V : in T) is <>; Value : T; Name : String; procedure Test_Add_Param_T (Tst : in out Test); -- Test the Bind_Param operation for various types. generic type T (<>) is private; with procedure Bind_Param (L : in out ADO.Parameters.Abstract_List; N : in String; V : in T) is <>; Value : T; Name : String; procedure Test_Bind_Param_T (Tst : in out Test); -- Test the Add_Param operation for various types. procedure Test_Add_Param_T (Tst : in out Test) is Count : constant Positive := 100; SQL : ADO.Parameters.List; S : Util.Measures.Stamp; begin for I in 1 .. Count loop Add_Param (ADO.Parameters.Abstract_List (SQL), Value); end loop; Util.Measures.Report (S, "Add_Param " & Name & "(" & Positive'Image (Count) & " calls)"); Util.Tests.Assert_Equals (Tst, Count, SQL.Length, "Invalid param list for " & Name); end Test_Add_Param_T; -- Test the Bind_Param operation for various types. procedure Test_Bind_Param_T (Tst : in out Test) is Count : constant Positive := 100; SQL : ADO.Parameters.List; S : Util.Measures.Stamp; begin for I in 1 .. Count loop Bind_Param (ADO.Parameters.Abstract_List (SQL), "a_parameter_name", Value); end loop; Util.Measures.Report (S, "Bind_Param " & Name & "(" & Positive'Image (Count) & " calls)"); Util.Tests.Assert_Equals (Tst, 1, SQL.Length, "Invalid param list for " & Name); end Test_Bind_Param_T; procedure Test_Add_Param_Integer is new Test_Add_Param_T (Integer, Add_Param, 10, "Integer"); procedure Test_Add_Param_Long_Long_Integer is new Test_Add_Param_T (Long_Long_Integer, Add_Param, 10_000_000_000_000, "Long_Long_Integer"); procedure Test_Add_Param_Identifier is new Test_Add_Param_T (Identifier, Add_Param, 100, "Identifier"); procedure Test_Add_Param_Boolean is new Test_Add_Param_T (Boolean, Add_Param, False, "Boolean"); procedure Test_Add_Param_String is new Test_Add_Param_T (String, Add_Param, "0123456789ABCDEF", "String"); procedure Test_Add_Param_Calendar is new Test_Add_Param_T (Ada.Calendar.Time, Add_Param, Ada.Calendar.Clock, "Time"); procedure Test_Add_Param_Unbounded_String is new Test_Add_Param_T (Unbounded_String, Add_Param, To_Unbounded_String ("0123456789ABCDEF"), "Unbounded_String"); procedure Test_Bind_Param_Integer is new Test_Bind_Param_T (Integer, Bind_Param, 10, "Integer"); procedure Test_Bind_Param_Long_Long_Integer is new Test_Bind_Param_T (Long_Long_Integer, Bind_Param, 10_000_000_000_000, "Long_Long_Integer"); procedure Test_Bind_Param_Identifier is new Test_Bind_Param_T (Identifier, Bind_Param, 100, "Identifier"); procedure Test_Bind_Param_Entity_Type is new Test_Bind_Param_T (Entity_Type, Bind_Param, 100, "Entity_Type"); procedure Test_Bind_Param_Boolean is new Test_Bind_Param_T (Boolean, Bind_Param, False, "Boolean"); procedure Test_Bind_Param_String is new Test_Bind_Param_T (String, Bind_Param, "0123456789ABCDEF", "String"); procedure Test_Bind_Param_Calendar is new Test_Bind_Param_T (Ada.Calendar.Time, Bind_Param, Ada.Calendar.Clock, "Time"); procedure Test_Bind_Param_Unbounded_String is new Test_Bind_Param_T (Unbounded_String, Bind_Param, To_Unbounded_String ("0123456789ABCDEF"), "Unbounded_String"); package Caller is new Util.Test_Caller (Test, "ADO.Parameters"); procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is begin Caller.Add_Test (Suite, "Test ADO.Parameters.Expand", Test_Expand_Sql'Access); Caller.Add_Test (Suite, "Test ADO.Parameters.Expand (invalid params)", Test_Expand_Error'Access); Caller.Add_Test (Suite, "Test ADO.Parameters.Expand (perf)", Test_Expand_Perf'Access); Caller.Add_Test (Suite, "Test ADO.Parameters.Add_Param (Boolean)", Test_Add_Param_Boolean'Access); Caller.Add_Test (Suite, "Test ADO.Parameters.Add_Param (Integer)", Test_Add_Param_Integer'Access); Caller.Add_Test (Suite, "Test ADO.Parameters.Add_Param (Long_Long_Integer)", Test_Add_Param_Long_Long_Integer'Access); Caller.Add_Test (Suite, "Test ADO.Parameters.Add_Param (Identifier)", Test_Add_Param_Identifier'Access); Caller.Add_Test (Suite, "Test ADO.Parameters.Add_Param (Calendar)", Test_Add_Param_Calendar'Access); Caller.Add_Test (Suite, "Test ADO.Parameters.Add_Param (String)", Test_Add_Param_String'Access); Caller.Add_Test (Suite, "Test ADO.Parameters.Add_Param (Unbounded_String)", Test_Add_Param_Unbounded_String'Access); Caller.Add_Test (Suite, "Test ADO.Parameters.Bind_Param (Boolean)", Test_Bind_Param_Boolean'Access); Caller.Add_Test (Suite, "Test ADO.Parameters.Bind_Param (Integer)", Test_Bind_Param_Integer'Access); Caller.Add_Test (Suite, "Test ADO.Parameters.Bind_Param (Long_Long_Integer)", Test_Bind_Param_Long_Long_Integer'Access); Caller.Add_Test (Suite, "Test ADO.Parameters.Bind_Param (Identifier)", Test_Bind_Param_Identifier'Access); Caller.Add_Test (Suite, "Test ADO.Parameters.Bind_Param (Calendar)", Test_Bind_Param_Calendar'Access); Caller.Add_Test (Suite, "Test ADO.Parameters.Bind_Param (String)", Test_Bind_Param_String'Access); Caller.Add_Test (Suite, "Test ADO.Parameters.Bind_Param (Unbounded_String)", Test_Bind_Param_Unbounded_String'Access); Caller.Add_Test (Suite, "Test ADO.Parameters.Bind_Param (Entity_Type)", Test_Bind_Param_Entity_Type'Access); Caller.Add_Test (Suite, "Test ADO.Parameters.Expand (cache expander)", Test_Expand_With_Expander'Access); end Add_Tests; -- ------------------------------ -- Check if the string is a reserved keyword. -- ------------------------------ overriding function Is_Reserved (D : in Dialect; Name : in String) return Boolean is pragma Unreferenced (D, Name); begin return False; end Is_Reserved; -- ------------------------------ -- Test expand SQL with parameters. -- ------------------------------ procedure Test_Expand_Sql (T : in out Test) is SQL : ADO.Parameters.List; D : aliased Dialect; procedure Check (Pattern : in String; Expect : in String); procedure Check (Pattern : in String; Expect : in String) is Result : constant String := SQL.Expand (Pattern); begin Assert_Equals (T, Expect, Result, "Invalid SQL expansion"); end Check; begin SQL.Set_Dialect (D'Unchecked_Access); SQL.Bind_Param (1, "select '"); SQL.Bind_Param (2, "from"); SQL.Bind_Param ("user_id", String '("23")); SQL.Bind_Param ("object_23_identifier", Integer (44)); SQL.Bind_Param ("bool", True); SQL.Bind_Param (6, False); SQL.Bind_Param ("_date", Ada.Calendar.Clock); SQL.Bind_Null_Param ("_null"); Check ("?", "'select '''"); Check (":2", "'from'"); Check (":6", "0"); Check (":user_id", "'23'"); Check (":bool", "1"); Check (":_null", "NULL"); Check ("select :1 :2 :3 :4 :5 :6", "select 'select ''' 'from' '23' 44 1 0"); Check ("select ? ? ? ? ? ?", "select 'select ''' 'from' '23' 44 1 0"); Check ("select ? :2 :user_id :object_23_identifier :bool :6", "select 'select ''' 'from' '23' 44 1 0"); Check ("select \:1 \:2 \:3 \:4 \:5 \:6", "select :1 :2 :3 :4 :5 :6"); end Test_Expand_Sql; -- ------------------------------ -- Test expand with invalid parameters. -- ------------------------------ procedure Test_Expand_Error (T : in out Test) is SQL : ADO.Parameters.List; procedure Check (Pattern : in String; Expect : in String); procedure Check (Pattern : in String; Expect : in String) is Result : constant String := SQL.Expand (Pattern); begin Assert_Equals (T, Expect, Result, "Invalid SQL expansion"); end Check; begin Check (":<", "<"); Check (":234", ""); Check (":name", ""); Check ("select :", "select :"); end Test_Expand_Error; -- ------------------------------ -- Test expand performance. -- ------------------------------ procedure Test_Expand_Perf (T : in out Test) is pragma Unreferenced (T); SQL : ADO.Parameters.List; D : aliased Dialect; begin SQL.Set_Dialect (D'Unchecked_Access); declare T : Util.Measures.Stamp; begin for I in 1 .. 1_000 loop SQL.Bind_Param (I, I); end loop; Util.Measures.Report (T, "Bind_Param (1000 calls)"); end; declare B : constant Unbounded_String := To_Unbounded_String ("select t.a, t.b, t.c, t.d, t.e, t.f " & "from T where t.b = 23"); T : Util.Measures.Stamp; begin for I in 1 .. 1_000 loop declare S : constant String := To_String (B); pragma Unreferenced (S); begin null; end; end loop; Util.Measures.Report (T, "Expand reference To_String"); end; declare T : Util.Measures.Stamp; begin for I in 1 .. 1_000 loop declare S : constant String := SQL.Expand ("select t.a, t.b, t.c, t.d, t.e, t.f " & "from T where t.b = 23"); pragma Unreferenced (S); begin null; end; end loop; Util.Measures.Report (T, "Expand (1000 calls with 0 parameter)"); end; declare T : Util.Measures.Stamp; begin for I in 1 .. 1_000 loop declare S : constant String := SQL.Expand ("select t.a, t.b, t.c, t.d, t.e, t.f " & "from T where t.b = :10"); pragma Unreferenced (S); begin null; end; end loop; Util.Measures.Report (T, "Expand (1000 calls with 1 parameter)"); end; declare T : Util.Measures.Stamp; begin for I in 1 .. 1_000 loop declare S : constant String := SQL.Expand (":10 :20 :30 :40 :50 :60 :70 :80 :90 :100"); pragma Unreferenced (S); begin null; end; end loop; Util.Measures.Report (T, "Expand (1000 calls with 10 parameters)"); end; end Test_Expand_Perf; -- ------------------------------ -- Test expand with cache expander. -- ------------------------------ procedure Test_Expand_With_Expander (T : in out Test) is procedure Check (Content : in String; Expect : in String); SQL : ADO.Parameters.List; D : aliased Dialect; C : aliased ADO.Caches.Cache_Manager; M : constant access Int_Cache.Cache_Type := new Int_Cache.Cache_Type; P : constant access Int_Cache.Cache_Type := new Int_Cache.Cache_Type; procedure Check (Content : in String; Expect : in String) is S : constant String := SQL.Expand (Content); begin Util.Tests.Assert_Equals (T, Expect, S, "Invalid expand for SQL '" & Content & "'"); end Check; begin C.Add_Cache ("test-group", M.all'Access); C.Add_Cache ("G2", P.all'Access); SQL.Expander := C'Unchecked_Access; M.Insert ("value-1", 123); M.Insert ("2", 2); M.Insert ("a name", 10); P.Insert ("1", 10); P.Insert ("a", 0); P.Insert ("c", 1); SQL.Set_Dialect (D'Unchecked_Access); Check ("$test-group[2]", "2"); Check ("$test-group[a name]", "10"); Check ("SELECT * FROM user WHERE id = $test-group[2]+$test-group[value-1]", "SELECT * FROM user WHERE id = 2+123"); Check ("SELECT * FROM user WHERE id = $G2[a]+$test-group[value-1]", "SELECT * FROM user WHERE id = 0+123"); P.Insert ("a", 1, True); Check ("SELECT * FROM user WHERE id = $G2[a]+$test-group[value-1]", "SELECT * FROM user WHERE id = 1+123"); Check ("SELECT * FROM user WHERE id = 2$G2[titi]+$test[value-1]1", "SELECT * FROM user WHERE id = 2+1"); end Test_Expand_With_Expander; end ADO.Parameters.Tests;
Fix compilation warning detected by GNAT 2017
Fix compilation warning detected by GNAT 2017
Ada
apache-2.0
stcarrez/ada-ado
2ed3937f486c83b3cf19934d9463bd8fc4479468
regtests/util-listeners-tests.adb
regtests/util-listeners-tests.adb
----------------------------------------------------------------------- -- util-listeners-tests -- Unit tests for listeners -- Copyright (C) 2012 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Strings.Unbounded; with Util.Measures; with Util.Test_Caller; with Util.Listeners.Observers; with Util.Listeners.Lifecycles; package body Util.Listeners.Tests is use Util.Tests; Test_Error : exception; Count : Natural := 0; package String_Observers is new Util.Listeners.Observers (String); package Integer_Observers is new Util.Listeners.Observers (Integer); type String_Listener is new String_Observers.Observer with record Expect : Ada.Strings.Unbounded.Unbounded_String; end record; overriding procedure Update (Listener : in String_Listener; Item : in String); type Integer_Listener is new Integer_Observers.Observer with record Expect : Integer; end record; overriding procedure Update (Listener : in Integer_Listener; Item : in Integer); package Caller is new Util.Test_Caller (Test, "Listeners"); procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is begin Caller.Add_Test (Suite, "Test Util.Listeners.Publish", Test_Publish'Access); Caller.Add_Test (Suite, "Test Util.Listeners.Publish_Perf", Test_Publish_Perf'Access); Caller.Add_Test (Suite, "Test Util.Listeners.Lifecycles", Test_Lifecycles'Access); end Add_Tests; overriding procedure Update (Listener : in String_Listener; Item : in String) is use type Ada.Strings.Unbounded.Unbounded_String; begin if Item /= Listener.Expect then raise Test_Error; end if; Count := Count + 1; end Update; overriding procedure Update (Listener : in Integer_Listener; Item : in Integer) is use type Ada.Strings.Unbounded.Unbounded_String; begin if Item /= Listener.Expect then raise Test_Error; end if; Count := Count + 1; end Update; -- ------------------------------ -- Test the listeners and the publish operation. -- ------------------------------ procedure Test_Publish (T : in out Test) is Listeners : Util.Listeners.List; L1 : aliased String_Listener; L2 : aliased Integer_Listener; L3 : aliased Integer_Listener; begin Listeners.Append (L1'Unchecked_Access); Listeners.Append (L2'Unchecked_Access); Listeners.Append (L3'Unchecked_Access); L1.Expect := Ada.Strings.Unbounded.To_Unbounded_String ("Hello"); String_Observers.Notify (Listeners, "Hello"); Util.Tests.Assert_Equals (T, 1, Count, "Invalid number of calls"); L2.Expect := 3; L3.Expect := 3; Integer_Observers.Notify (Listeners, 3); end Test_Publish; -- ------------------------------ -- Performance test for the listeners. -- ------------------------------ procedure Test_Publish_Perf (T : in out Test) is Listeners : Util.Listeners.List; L1 : aliased Integer_Listener; procedure Test_Basic (Item : in Integer) is begin Util.Tests.Assert_Equals (T, 3, Item); end Test_Basic; begin Listeners.Append (L1'Unchecked_Access); L1.Expect := 3; declare S : Util.Measures.Stamp; begin for I in 1 .. 1_000 loop Integer_Observers.Notify (Listeners, 3); end loop; Util.Measures.Report (S, "Published 1000 times"); end; declare S : Util.Measures.Stamp; begin for I in 1 .. 1_000 loop Test_Basic (3); end loop; Util.Measures.Report (S, "Call basic 1000 times"); end; end Test_Publish_Perf; -- ------------------------------ -- Test the lifecycles listener. -- ------------------------------ procedure Test_Lifecycles (T : in out Test) is package TL is new Util.Listeners.Lifecycles (Util.Measures.Stamp); Create_Count : Natural := 0; Update_Count : Natural := 0; Delete_Count : Natural := 0; type Listener is new TL.Listener with null record; -- The `On_Create` procedure is called by `Notify_Create` to notify the creation -- of the item. overriding procedure On_Create (Instance : in Listener; Item : in Util.Measures.Stamp); -- The `On_Update` procedure is called by `Notify_Update` to notify the update of the item. overriding procedure On_Update (Instance : in Listener; Item : in Util.Measures.Stamp); -- The `On_Delete` procedure is called by `Notify_Delete` to notify the deletion -- of the item. overriding procedure On_Delete (Instance : in Listener; Item : in Util.Measures.Stamp); -- ------------------------------ -- The `On_Create` procedure is called by `Notify_Create` to notify the creation -- of the item. -- ------------------------------ overriding procedure On_Create (Instance : in Listener; Item : in Util.Measures.Stamp) is pragma Unreferenced (Instance, Item); begin Create_Count := Create_Count + 1; end On_Create; -- ------------------------------ -- The `On_Update` procedure is called by `Notify_Update` to notify the update of the item. -- ------------------------------ overriding procedure On_Update (Instance : in Listener; Item : in Util.Measures.Stamp) is pragma Unreferenced (Instance, Item); begin Update_Count := Update_Count + 1; end On_Update; -- ------------------------------ -- The `On_Delete` procedure is called by `Notify_Delete` to notify the deletion -- of the item. -- ------------------------------ overriding procedure On_Delete (Instance : in Listener; Item : in Util.Measures.Stamp) is pragma Unreferenced (Instance, Item); begin Delete_Count := Delete_Count + 1; end On_Delete; Listeners : Util.Listeners.List; L1 : aliased Integer_Listener; L2 : aliased Listener; begin Listeners.Append (L1'Unchecked_Access); Listeners.Append (L2'Unchecked_Access); declare S : Util.Measures.Stamp; begin TL.Notify_Create (Listeners, S); TL.Notify_Update (Listeners, S); TL.Notify_Delete (Listeners, S); Util.Measures.Report (S, "Notify Create, Update, Delete"); end; Util.Tests.Assert_Equals (T, 1, Create_Count, "On_Create not called"); Util.Tests.Assert_Equals (T, 1, Update_Count, "On_Update not called"); Util.Tests.Assert_Equals (T, 1, Delete_Count, "On_Delete not called"); end Test_Lifecycles; end Util.Listeners.Tests;
----------------------------------------------------------------------- -- util-listeners-tests -- Unit tests for listeners -- Copyright (C) 2012 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Strings.Unbounded; with Util.Measures; with Util.Test_Caller; with Util.Listeners.Observers; with Util.Listeners.Lifecycles; package body Util.Listeners.Tests is use Util.Tests; Test_Error : exception; Count : Natural := 0; package String_Observers is new Util.Listeners.Observers (String); package Integer_Observers is new Util.Listeners.Observers (Integer); type String_Listener is new String_Observers.Observer with record Expect : Ada.Strings.Unbounded.Unbounded_String; end record; overriding procedure Update (Listener : in String_Listener; Item : in String); type Integer_Listener is new Integer_Observers.Observer with record Expect : Integer; end record; overriding procedure Update (Listener : in Integer_Listener; Item : in Integer); package Caller is new Util.Test_Caller (Test, "Listeners"); procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is begin Caller.Add_Test (Suite, "Test Util.Listeners.Publish", Test_Publish'Access); Caller.Add_Test (Suite, "Test Util.Listeners.Publish_Perf", Test_Publish_Perf'Access); Caller.Add_Test (Suite, "Test Util.Listeners.Lifecycles", Test_Lifecycles'Access); end Add_Tests; overriding procedure Update (Listener : in String_Listener; Item : in String) is use type Ada.Strings.Unbounded.Unbounded_String; begin if Item /= Listener.Expect then raise Test_Error; end if; Count := Count + 1; end Update; overriding procedure Update (Listener : in Integer_Listener; Item : in Integer) is use type Ada.Strings.Unbounded.Unbounded_String; begin if Item /= Listener.Expect then raise Test_Error; end if; Count := Count + 1; end Update; -- ------------------------------ -- Test the listeners and the publish operation. -- ------------------------------ procedure Test_Publish (T : in out Test) is Listeners : Util.Listeners.List; L1 : aliased String_Listener; L2 : aliased Integer_Listener; L3 : aliased Integer_Listener; begin Listeners.Append (L1'Unchecked_Access); Listeners.Append (L2'Unchecked_Access); Listeners.Append (L3'Unchecked_Access); L1.Expect := Ada.Strings.Unbounded.To_Unbounded_String ("Hello"); String_Observers.Notify (Listeners, "Hello"); Util.Tests.Assert_Equals (T, 1, Count, "Invalid number of calls"); L2.Expect := 3; L3.Expect := 3; Integer_Observers.Notify (Listeners, 3); end Test_Publish; -- ------------------------------ -- Performance test for the listeners. -- ------------------------------ procedure Test_Publish_Perf (T : in out Test) is procedure Test_Basic (Item : in Integer); Listeners : Util.Listeners.List; L1 : aliased Integer_Listener; procedure Test_Basic (Item : in Integer) is begin Util.Tests.Assert_Equals (T, 3, Item); end Test_Basic; begin Listeners.Append (L1'Unchecked_Access); L1.Expect := 3; declare S : Util.Measures.Stamp; begin for I in 1 .. 1_000 loop Integer_Observers.Notify (Listeners, 3); end loop; Util.Measures.Report (S, "Published 1000 times"); end; declare S : Util.Measures.Stamp; begin for I in 1 .. 1_000 loop Test_Basic (3); end loop; Util.Measures.Report (S, "Call basic 1000 times"); end; end Test_Publish_Perf; -- ------------------------------ -- Test the lifecycles listener. -- ------------------------------ procedure Test_Lifecycles (T : in out Test) is package TL is new Util.Listeners.Lifecycles (Util.Measures.Stamp); Create_Count : Natural := 0; Update_Count : Natural := 0; Delete_Count : Natural := 0; type Listener is new TL.Listener with null record; -- The `On_Create` procedure is called by `Notify_Create` to notify the creation -- of the item. overriding procedure On_Create (Instance : in Listener; Item : in Util.Measures.Stamp); -- The `On_Update` procedure is called by `Notify_Update` to notify the update of the item. overriding procedure On_Update (Instance : in Listener; Item : in Util.Measures.Stamp); -- The `On_Delete` procedure is called by `Notify_Delete` to notify the deletion -- of the item. overriding procedure On_Delete (Instance : in Listener; Item : in Util.Measures.Stamp); -- ------------------------------ -- The `On_Create` procedure is called by `Notify_Create` to notify the creation -- of the item. -- ------------------------------ overriding procedure On_Create (Instance : in Listener; Item : in Util.Measures.Stamp) is pragma Unreferenced (Instance, Item); begin Create_Count := Create_Count + 1; end On_Create; -- ------------------------------ -- The `On_Update` procedure is called by `Notify_Update` to notify the update of the item. -- ------------------------------ overriding procedure On_Update (Instance : in Listener; Item : in Util.Measures.Stamp) is pragma Unreferenced (Instance, Item); begin Update_Count := Update_Count + 1; end On_Update; -- ------------------------------ -- The `On_Delete` procedure is called by `Notify_Delete` to notify the deletion -- of the item. -- ------------------------------ overriding procedure On_Delete (Instance : in Listener; Item : in Util.Measures.Stamp) is pragma Unreferenced (Instance, Item); begin Delete_Count := Delete_Count + 1; end On_Delete; Listeners : Util.Listeners.List; L1 : aliased Integer_Listener; L2 : aliased Listener; begin Listeners.Append (L1'Unchecked_Access); Listeners.Append (L2'Unchecked_Access); declare S : Util.Measures.Stamp; begin TL.Notify_Create (Listeners, S); TL.Notify_Update (Listeners, S); TL.Notify_Delete (Listeners, S); Util.Measures.Report (S, "Notify Create, Update, Delete"); end; Util.Tests.Assert_Equals (T, 1, Create_Count, "On_Create not called"); Util.Tests.Assert_Equals (T, 1, Update_Count, "On_Update not called"); Util.Tests.Assert_Equals (T, 1, Delete_Count, "On_Delete not called"); end Test_Lifecycles; end Util.Listeners.Tests;
Fix compilation warning
Fix compilation warning
Ada
apache-2.0
stcarrez/ada-util,stcarrez/ada-util
582c1d9486c235e15732f07df3e4aa9df1bcaf19
regtests/security-policies-tests.adb
regtests/security-policies-tests.adb
----------------------------------------------------------------------- -- Security-policies-tests - Unit tests for Security.Permissions -- Copyright (C) 2011, 2012 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Tests; with Util.Files; with Util.Test_Caller; with Util.Measures; with Security.Contexts; with Security.Policies.Roles; with Security.Permissions.Tests; package body Security.Policies.Tests is use Util.Tests; package Caller is new Util.Test_Caller (Test, "Security.Policies"); procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is begin Caller.Add_Test (Suite, "Test Security.Permissions.Create_Role", Test_Create_Role'Access); Caller.Add_Test (Suite, "Test Security.Permissions.Has_Permission", Test_Has_Permission'Access); Caller.Add_Test (Suite, "Test Security.Permissions.Read_Policy (empty)", Test_Read_Empty_Policy'Access); Caller.Add_Test (Suite, "Test Security.Policies.Add_Policy", Test_Get_Role_Policy'Access); Caller.Add_Test (Suite, "Test Security.Policies.Get_Policy", Test_Get_Role_Policy'Access); Caller.Add_Test (Suite, "Test Security.Policies.Roles.Get_Role_Policy", Test_Get_Role_Policy'Access); Caller.Add_Test (Suite, "Test Security.Policies.Read_Policy", Test_Read_Policy'Access); Caller.Add_Test (Suite, "Test Security.Policies.Roles.Set_Roles", Test_Set_Roles'Access); Caller.Add_Test (Suite, "Test Security.Policies.Roles.Set_Roles (invalid)", Test_Set_Invalid_Roles'Access); -- These tests are identical but registered under different names -- for the test documentation. Caller.Add_Test (Suite, "Test Security.Contexts.Has_Permission", Test_Role_Policy'Access); Caller.Add_Test (Suite, "Test Security.Controllers.Roles.Has_Permission", Test_Role_Policy'Access); Caller.Add_Test (Suite, "Test Security.Permissions.Role_Policy", Test_Role_Policy'Access); end Add_Tests; -- ------------------------------ -- Get the roles assigned to the user. -- ------------------------------ function Get_Roles (User : in Test_Principal) return Roles.Role_Map is begin return User.Roles; end Get_Roles; -- ------------------------------ -- Get the principal name. -- ------------------------------ function Get_Name (From : in Test_Principal) return String is begin return Util.Strings.To_String (From.Name); end Get_Name; -- ------------------------------ -- Test Create_Role and Get_Role_Name -- ------------------------------ procedure Test_Create_Role (T : in out Test) is use Security.Policies.Roles; M : Security.Policies.Roles.Role_Policy; Role : Role_Type; begin M.Create_Role (Name => "admin", Role => Role); Assert_Equals (T, "admin", M.Get_Role_Name (Role), "Invalid name"); for I in Role + 1 .. Role_Type'Last loop declare Name : constant String := "admin-" & Role_Type'Image (I); Role2 : Role_Type; begin Role2 := M.Find_Role ("admin"); T.Assert (Role2 = Role, "Find_Role returned an invalid role"); M.Create_Role (Name => Name, Role => Role2); Assert_Equals (T, Name, M.Get_Role_Name (Role2), "Invalid name"); end; end loop; end Test_Create_Role; -- ------------------------------ -- Test Set_Roles -- ------------------------------ procedure Test_Set_Roles (T : in out Test) is use Security.Policies.Roles; M : Security.Policies.Roles.Role_Policy; Admin : Role_Type; Manager : Role_Type; Map : Role_Map := (others => False); begin M.Create_Role (Name => "manager", Role => Manager); M.Create_Role (Name => "admin", Role => Admin); Assert_Equals (T, "admin", M.Get_Role_Name (Admin), "Invalid name"); T.Assert (not Map (Admin), "The admin role must not set in the map"); M.Set_Roles ("admin", Map); T.Assert (Map (Admin), "The admin role is not set in the map"); T.Assert (not Map (Manager), "The manager role must not be set in the map"); Map := (others => False); M.Set_Roles ("manager,admin", Map); T.Assert (Map (Admin), "The admin role is not set in the map"); T.Assert (Map (Manager), "The manager role is not set in the map"); end Test_Set_Roles; -- ------------------------------ -- Test Set_Roles on an invalid role name -- ------------------------------ procedure Test_Set_Invalid_Roles (T : in out Test) is use Security.Policies.Roles; M : Security.Policies.Roles.Role_Policy; Map : Role_Map := (others => False); begin M.Set_Roles ("manager,admin", Map); T.Assert (False, "No exception was raised"); exception when E : Security.Policies.Roles.Invalid_Name => null; end Test_Set_Invalid_Roles; -- ------------------------------ -- Test Has_Permission -- ------------------------------ procedure Test_Has_Permission (T : in out Test) is M : Security.Policies.Policy_Manager (1); -- Perm : Permissions.Permission_Type; User : Test_Principal; begin -- T.Assert (not M.Has_Permission (User, 1), "User has a non-existing permission"); null; end Test_Has_Permission; procedure Configure_Policy (Manager : in out Security.Policies.Policy_Manager; Name : in String) is Dir : constant String := "regtests/files/permissions/"; Path : constant String := Util.Tests.Get_Path (Dir); R : Security.Policies.Roles.Role_Policy_Access := new Roles.Role_Policy; U : Security.Policies.URLs.URL_Policy_Access := new URLs.URL_Policy; begin Manager.Add_Policy (R.all'Access); Manager.Add_Policy (U.all'Access); Manager.Read_Policy (Util.Files.Compose (Path, Name)); end Configure_Policy; -- ------------------------------ -- Test the Get_Policy, Get_Role_Policy and Add_Policy operations. -- ------------------------------ procedure Test_Get_Role_Policy (T : in out Test) is use type Roles.Role_Policy_Access; M : aliased Security.Policies.Policy_Manager (Max_Policies => 2); P : Security.Policies.Policy_Access; R : Security.Policies.Roles.Role_Policy_Access; begin P := M.Get_Policy (Security.Policies.Roles.NAME); T.Assert (P = null, "Get_Policy succeeded"); R := Security.Policies.Roles.Get_Role_Policy (M); T.Assert (R = null, "Get_Role_Policy succeeded"); R := new Roles.Role_Policy; M.Add_Policy (R.all'Access); P := M.Get_Policy (Security.Policies.Roles.NAME); T.Assert (P /= null, "Role policy not found"); T.Assert (P.all in Roles.Role_Policy'Class, "Invalid role policy"); R := Security.Policies.Roles.Get_Role_Policy (M); T.Assert (R /= null, "Get_Role_Policy should not return null"); end Test_Get_Role_Policy; -- ------------------------------ -- Test reading an empty policy file -- ------------------------------ procedure Test_Read_Empty_Policy (T : in out Test) is M : aliased Security.Policies.Policy_Manager (Max_Policies => 2); User : aliased Test_Principal; Context : aliased Security.Contexts.Security_Context; P : Security.Policies.Policy_Access; R : Security.Policies.Roles.Role_Policy_Access; begin Configure_Policy (M, "empty.xml"); Context.Set_Context (Manager => M'Unchecked_Access, Principal => User'Unchecked_Access); R := Security.Policies.Roles.Get_Role_Policy (M); declare Admin : Policies.Roles.Role_Type; begin Admin := R.Find_Role ("admin"); T.Fail ("'admin' role was returned"); exception when Security.Policies.Roles.Invalid_Name => null; end; T.Assert (not Contexts.Has_Permission (Permissions.Tests.P_Admin.Permission), "Has_Permission (admin) failed for empty policy"); T.Assert (not Contexts.Has_Permission (Permissions.Tests.P_Create.Permission), "Has_Permission (create) failed for empty policy"); T.Assert (not Contexts.Has_Permission (Permissions.Tests.P_Update.Permission), "Has_Permission (update) failed for empty policy"); T.Assert (not Contexts.Has_Permission (Permissions.Tests.P_Delete.Permission), "Has_Permission (delete) failed for empty policy"); end Test_Read_Empty_Policy; -- ------------------------------ -- Test reading policy files -- ------------------------------ procedure Test_Read_Policy (T : in out Test) is M : aliased Security.Policies.Policy_Manager (Max_Policies => 2); User : aliased Test_Principal; Admin_Perm : Policies.Roles.Role_Type; Manager_Perm : Policies.Roles.Role_Type; Context : aliased Security.Contexts.Security_Context; R : Security.Policies.Roles.Role_Policy_Access := new Roles.Role_Policy; begin Configure_Policy (M, "simple-policy.xml"); Context.Set_Context (Manager => M'Unchecked_Access, Principal => User'Unchecked_Access); User.Roles (Admin_Perm) := True; declare use Security.Permissions.Tests; S : Util.Measures.Stamp; begin for I in 1 .. 1_000 loop declare URI : constant String := "/admin/home/" & Util.Strings.Image (I) & "/l.html"; P : constant URLs.URI_Permission (URI'Length) := URLs.URI_Permission '(Len => URI'Length, URI => URI); begin T.Assert (Contexts.Has_Permission (Permission => P_Admin.Permission), "Permission not granted"); end; end loop; Util.Measures.Report (S, "Has_Permission (1000 calls, cache miss)"); end; declare use Security.Permissions.Tests; S : Util.Measures.Stamp; begin for I in 1 .. 1_000 loop declare URI : constant String := "/admin/home/list.html"; P : constant URLs.URI_Permission (URI'Length) := URLs.URI_Permission '(Len => URI'Length, URI => URI); begin T.Assert (Contexts.Has_Permission (Permission => P_Admin.Permission), "Permission not granted"); end; end loop; Util.Measures.Report (S, "Has_Permission (1000 calls, cache hit)"); end; end Test_Read_Policy; -- ------------------------------ -- Read the policy file <b>File</b> and perform a test on the given URI -- with a user having the given role. -- ------------------------------ procedure Check_Policy (T : in out Test; File : in String; Role : in String; URI : in String) is M : aliased Security.Policies.Policy_Manager (2); User : aliased Test_Principal; Admin_Perm : Roles.Role_Type; Context : aliased Security.Contexts.Security_Context; P : Security.Policies.Policy_Access; R : Security.Policies.Roles.Role_Policy_Access; U : Security.Policies.URLs.URL_Policy_Access := new URLs.URL_Policy; begin Configure_Policy (M, File); Context.Set_Context (Manager => M'Unchecked_Access, Principal => User'Unchecked_Access); R := Security.Policies.Roles.Get_Role_Policy (M); Admin_Perm := R.Find_Role (Role); declare P : constant URLs.URI_Permission (URI'Length) := URLs.URI_Permission '(Len => URI'Length, URI => URI); begin -- A user without the role should not have the permission. T.Assert (not U.Has_Permission (Context => Context'Unchecked_Access, Permission => P), "Permission was granted for user without role. URI=" & URI); -- Set the role. User.Roles (Admin_Perm) := True; T.Assert (U.Has_Permission (Context => Context'Unchecked_Access, Permission => P), "Permission was not granted for user with role. URI=" & URI); end; end Check_Policy; -- ------------------------------ -- Test reading policy files and using the <role-permission> controller -- ------------------------------ procedure Test_Role_Policy (T : in out Test) is begin T.Check_Policy (File => "policy-with-role.xml", Role => "developer", URI => "/developer/user-should-have-developer-role"); T.Check_Policy (File => "policy-with-role.xml", Role => "manager", URI => "/developer/user-should-have-manager-role"); T.Check_Policy (File => "policy-with-role.xml", Role => "manager", URI => "/manager/user-should-have-manager-role"); T.Check_Policy (File => "policy-with-role.xml", Role => "admin", URI => "/manager/user-should-have-admin-role"); T.Check_Policy (File => "policy-with-role.xml", Role => "admin", URI => "/admin/user-should-have-admin-role"); end Test_Role_Policy; end Security.Policies.Tests;
----------------------------------------------------------------------- -- Security-policies-tests - Unit tests for Security.Permissions -- Copyright (C) 2011, 2012 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Tests; with Util.Files; with Util.Test_Caller; with Util.Measures; with Security.Contexts; with Security.Policies.Roles; with Security.Permissions.Tests; package body Security.Policies.Tests is use Util.Tests; package Caller is new Util.Test_Caller (Test, "Security.Policies"); procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is begin Caller.Add_Test (Suite, "Test Security.Permissions.Create_Role", Test_Create_Role'Access); Caller.Add_Test (Suite, "Test Security.Permissions.Has_Permission", Test_Has_Permission'Access); Caller.Add_Test (Suite, "Test Security.Permissions.Read_Policy (empty)", Test_Read_Empty_Policy'Access); Caller.Add_Test (Suite, "Test Security.Policies.Add_Policy", Test_Get_Role_Policy'Access); Caller.Add_Test (Suite, "Test Security.Policies.Get_Policy", Test_Get_Role_Policy'Access); Caller.Add_Test (Suite, "Test Security.Policies.Roles.Get_Role_Policy", Test_Get_Role_Policy'Access); Caller.Add_Test (Suite, "Test Security.Policies.Read_Policy", Test_Read_Policy'Access); Caller.Add_Test (Suite, "Test Security.Policies.Roles.Set_Roles", Test_Set_Roles'Access); Caller.Add_Test (Suite, "Test Security.Policies.Roles.Set_Roles (invalid)", Test_Set_Invalid_Roles'Access); -- These tests are identical but registered under different names -- for the test documentation. Caller.Add_Test (Suite, "Test Security.Contexts.Has_Permission", Test_Role_Policy'Access); Caller.Add_Test (Suite, "Test Security.Controllers.Roles.Has_Permission", Test_Role_Policy'Access); Caller.Add_Test (Suite, "Test Security.Permissions.Role_Policy", Test_Role_Policy'Access); end Add_Tests; -- ------------------------------ -- Get the roles assigned to the user. -- ------------------------------ function Get_Roles (User : in Test_Principal) return Roles.Role_Map is begin return User.Roles; end Get_Roles; -- ------------------------------ -- Get the principal name. -- ------------------------------ function Get_Name (From : in Test_Principal) return String is begin return Util.Strings.To_String (From.Name); end Get_Name; -- ------------------------------ -- Test Create_Role and Get_Role_Name -- ------------------------------ procedure Test_Create_Role (T : in out Test) is use Security.Policies.Roles; M : Security.Policies.Roles.Role_Policy; Role : Role_Type; begin M.Create_Role (Name => "admin", Role => Role); Assert_Equals (T, "admin", M.Get_Role_Name (Role), "Invalid name"); for I in Role + 1 .. Role_Type'Last loop declare Name : constant String := "admin-" & Role_Type'Image (I); Role2 : Role_Type; begin Role2 := M.Find_Role ("admin"); T.Assert (Role2 = Role, "Find_Role returned an invalid role"); M.Create_Role (Name => Name, Role => Role2); Assert_Equals (T, Name, M.Get_Role_Name (Role2), "Invalid name"); end; end loop; end Test_Create_Role; -- ------------------------------ -- Test Set_Roles -- ------------------------------ procedure Test_Set_Roles (T : in out Test) is use Security.Policies.Roles; M : Security.Policies.Roles.Role_Policy; Admin : Role_Type; Manager : Role_Type; Map : Role_Map := (others => False); begin M.Create_Role (Name => "manager", Role => Manager); M.Create_Role (Name => "admin", Role => Admin); Assert_Equals (T, "admin", M.Get_Role_Name (Admin), "Invalid name"); T.Assert (not Map (Admin), "The admin role must not set in the map"); M.Set_Roles ("admin", Map); T.Assert (Map (Admin), "The admin role is not set in the map"); T.Assert (not Map (Manager), "The manager role must not be set in the map"); Map := (others => False); M.Set_Roles ("manager,admin", Map); T.Assert (Map (Admin), "The admin role is not set in the map"); T.Assert (Map (Manager), "The manager role is not set in the map"); end Test_Set_Roles; -- ------------------------------ -- Test Set_Roles on an invalid role name -- ------------------------------ procedure Test_Set_Invalid_Roles (T : in out Test) is use Security.Policies.Roles; M : Security.Policies.Roles.Role_Policy; Map : Role_Map := (others => False); begin M.Set_Roles ("manager,admin", Map); T.Assert (False, "No exception was raised"); exception when E : Security.Policies.Roles.Invalid_Name => null; end Test_Set_Invalid_Roles; -- ------------------------------ -- Test Has_Permission -- ------------------------------ procedure Test_Has_Permission (T : in out Test) is M : Security.Policies.Policy_Manager (1); -- Perm : Permissions.Permission_Type; User : Test_Principal; begin -- T.Assert (not M.Has_Permission (User, 1), "User has a non-existing permission"); null; end Test_Has_Permission; procedure Configure_Policy (Manager : in out Security.Policies.Policy_Manager; Name : in String) is Dir : constant String := "regtests/files/permissions/"; Path : constant String := Util.Tests.Get_Path (Dir); R : Security.Policies.Roles.Role_Policy_Access := new Roles.Role_Policy; U : Security.Policies.URLs.URL_Policy_Access := new URLs.URL_Policy; begin Manager.Add_Policy (R.all'Access); Manager.Add_Policy (U.all'Access); Manager.Read_Policy (Util.Files.Compose (Path, Name)); end Configure_Policy; -- ------------------------------ -- Test the Get_Policy, Get_Role_Policy and Add_Policy operations. -- ------------------------------ procedure Test_Get_Role_Policy (T : in out Test) is use type Roles.Role_Policy_Access; M : aliased Security.Policies.Policy_Manager (Max_Policies => 2); P : Security.Policies.Policy_Access; R : Security.Policies.Roles.Role_Policy_Access; begin P := M.Get_Policy (Security.Policies.Roles.NAME); T.Assert (P = null, "Get_Policy succeeded"); R := Security.Policies.Roles.Get_Role_Policy (M); T.Assert (R = null, "Get_Role_Policy succeeded"); R := new Roles.Role_Policy; M.Add_Policy (R.all'Access); P := M.Get_Policy (Security.Policies.Roles.NAME); T.Assert (P /= null, "Role policy not found"); T.Assert (P.all in Roles.Role_Policy'Class, "Invalid role policy"); R := Security.Policies.Roles.Get_Role_Policy (M); T.Assert (R /= null, "Get_Role_Policy should not return null"); end Test_Get_Role_Policy; -- ------------------------------ -- Test reading an empty policy file -- ------------------------------ procedure Test_Read_Empty_Policy (T : in out Test) is M : aliased Security.Policies.Policy_Manager (Max_Policies => 2); User : aliased Test_Principal; Context : aliased Security.Contexts.Security_Context; P : Security.Policies.Policy_Access; R : Security.Policies.Roles.Role_Policy_Access; begin Configure_Policy (M, "empty.xml"); Context.Set_Context (Manager => M'Unchecked_Access, Principal => User'Unchecked_Access); R := Security.Policies.Roles.Get_Role_Policy (M); declare Admin : Policies.Roles.Role_Type; begin Admin := R.Find_Role ("admin"); T.Fail ("'admin' role was returned"); exception when Security.Policies.Roles.Invalid_Name => null; end; T.Assert (not Contexts.Has_Permission (Permissions.Tests.P_Admin.Permission), "Has_Permission (admin) failed for empty policy"); T.Assert (not Contexts.Has_Permission (Permissions.Tests.P_Create.Permission), "Has_Permission (create) failed for empty policy"); T.Assert (not Contexts.Has_Permission (Permissions.Tests.P_Update.Permission), "Has_Permission (update) failed for empty policy"); T.Assert (not Contexts.Has_Permission (Permissions.Tests.P_Delete.Permission), "Has_Permission (delete) failed for empty policy"); end Test_Read_Empty_Policy; -- ------------------------------ -- Test reading policy files -- ------------------------------ procedure Test_Read_Policy (T : in out Test) is use Security.Permissions.Tests; M : aliased Security.Policies.Policy_Manager (Max_Policies => 2); User : aliased Test_Principal; Admin : Policies.Roles.Role_Type; Manager_Perm : Policies.Roles.Role_Type; Context : aliased Security.Contexts.Security_Context; R : Security.Policies.Roles.Role_Policy_Access := new Roles.Role_Policy; begin Configure_Policy (M, "simple-policy.xml"); Context.Set_Context (Manager => M'Unchecked_Access, Principal => User'Unchecked_Access); R := Security.Policies.Roles.Get_Role_Policy (M); Admin := R.Find_Role ("admin"); T.Assert (not Contexts.Has_Permission (Permission => P_Admin.Permission), "Permission was granted but user has no role"); User.Roles (Admin) := True; T.Assert (Contexts.Has_Permission (Permission => P_Admin.Permission), "Permission was not granted and user has admin role"); declare S : Util.Measures.Stamp; begin for I in 1 .. 1_000 loop declare URI : constant String := "/admin/home/" & Util.Strings.Image (I) & "/l.html"; P : constant URLs.URI_Permission (URI'Length) := URLs.URI_Permission '(Len => URI'Length, URI => URI); begin T.Assert (Contexts.Has_Permission (Permission => P_Admin.Permission), "Permission not granted"); end; end loop; Util.Measures.Report (S, "Has_Permission (1000 calls, cache miss)"); end; declare use Security.Permissions.Tests; S : Util.Measures.Stamp; begin for I in 1 .. 1_000 loop declare URI : constant String := "/admin/home/list.html"; P : constant URLs.URI_Permission (URI'Length) := URLs.URI_Permission '(Len => URI'Length, URI => URI); begin T.Assert (Contexts.Has_Permission (Permission => P_Admin.Permission), "Permission not granted"); end; end loop; Util.Measures.Report (S, "Has_Permission (1000 calls, cache hit)"); end; end Test_Read_Policy; -- ------------------------------ -- Read the policy file <b>File</b> and perform a test on the given URI -- with a user having the given role. -- ------------------------------ procedure Check_Policy (T : in out Test; File : in String; Role : in String; URI : in String) is M : aliased Security.Policies.Policy_Manager (2); User : aliased Test_Principal; Admin_Perm : Roles.Role_Type; Context : aliased Security.Contexts.Security_Context; P : Security.Policies.Policy_Access; R : Security.Policies.Roles.Role_Policy_Access; U : Security.Policies.URLs.URL_Policy_Access := new URLs.URL_Policy; begin Configure_Policy (M, File); Context.Set_Context (Manager => M'Unchecked_Access, Principal => User'Unchecked_Access); R := Security.Policies.Roles.Get_Role_Policy (M); Admin_Perm := R.Find_Role (Role); declare P : constant URLs.URI_Permission (URI'Length) := URLs.URI_Permission '(Len => URI'Length, URI => URI); begin -- A user without the role should not have the permission. T.Assert (not U.Has_Permission (Context => Context'Unchecked_Access, Permission => P), "Permission was granted for user without role. URI=" & URI); -- Set the role. User.Roles (Admin_Perm) := True; T.Assert (U.Has_Permission (Context => Context'Unchecked_Access, Permission => P), "Permission was not granted for user with role. URI=" & URI); end; end Check_Policy; -- ------------------------------ -- Test reading policy files and using the <role-permission> controller -- ------------------------------ procedure Test_Role_Policy (T : in out Test) is begin T.Check_Policy (File => "policy-with-role.xml", Role => "developer", URI => "/developer/user-should-have-developer-role"); T.Check_Policy (File => "policy-with-role.xml", Role => "manager", URI => "/developer/user-should-have-manager-role"); T.Check_Policy (File => "policy-with-role.xml", Role => "manager", URI => "/manager/user-should-have-manager-role"); T.Check_Policy (File => "policy-with-role.xml", Role => "admin", URI => "/manager/user-should-have-admin-role"); T.Check_Policy (File => "policy-with-role.xml", Role => "admin", URI => "/admin/user-should-have-admin-role"); end Test_Role_Policy; end Security.Policies.Tests;
Fix the unit test for simple-policy
Fix the unit test for simple-policy
Ada
apache-2.0
stcarrez/ada-security
7feeab53957eb0e9a690c945991b94931a79f129
regtests/util-http-clients-tests.ads
regtests/util-http-clients-tests.ads
----------------------------------------------------------------------- -- util-http-clients-tests -- Unit tests for HTTP client -- Copyright (C) 2012, 2020 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Strings.Unbounded; with Util.Tests; with Util.Tests.Servers; with Util.Streams.Texts; with Util.Streams.Sockets; package Util.Http.Clients.Tests is type Method_Type is (OPTIONS, GET, HEAD, POST, PUT, DELETE, TRACE, CONNECT, UNKNOWN); type Test_Server is new Util.Tests.Servers.Server with record Method : Method_Type := UNKNOWN; Result : Ada.Strings.Unbounded.Unbounded_String; Content_Type : Ada.Strings.Unbounded.Unbounded_String; Length : Natural := 0; Test_Timeout : Boolean := False; end record; type Test_Server_Access is access all Test_Server'Class; -- Process the line received by the server. overriding procedure Process_Line (Into : in out Test_Server; Line : in Ada.Strings.Unbounded.Unbounded_String; Stream : in out Util.Streams.Texts.Reader_Stream'Class; Client : in out Util.Streams.Sockets.Socket_Stream'Class); type Test is new Util.Tests.Test with record Server : Test_Server_Access := null; end record; -- Test the http Get operation. procedure Test_Http_Get (T : in out Test); -- Test the http POST operation. procedure Test_Http_Post (T : in out Test); -- Test the http PUT operation. procedure Test_Http_Put (T : in out Test); -- Test the http DELETE operation. procedure Test_Http_Delete (T : in out Test); -- Test the http timeout. procedure Test_Http_Timeout (T : in out Test); overriding procedure Set_Up (T : in out Test); overriding procedure Tear_Down (T : in out Test); -- Get the test server base URI. function Get_Uri (T : in Test) return String; -- The <b>Http_Tests</b> package must be instantiated with one of the HTTP implementation. -- The <b>Register</b> procedure configures the Http.Client to use the given HTTP -- implementation before running the test. generic with procedure Register; NAME : in String; package Http_Tests is procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite); type Http_Test is new Test with null record; overriding procedure Set_Up (T : in out Http_Test); end Http_Tests; end Util.Http.Clients.Tests;
----------------------------------------------------------------------- -- util-http-clients-tests -- Unit tests for HTTP client -- Copyright (C) 2012, 2020 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Strings.Unbounded; with Util.Tests; with Util.Tests.Servers; with Util.Streams.Texts; with Util.Streams.Sockets; package Util.Http.Clients.Tests is type Method_Type is (OPTIONS, GET, HEAD, POST, PUT, DELETE, TRACE, CONNECT, UNKNOWN); type Test_Server is new Util.Tests.Servers.Server with record Method : Method_Type := UNKNOWN; Result : Ada.Strings.Unbounded.Unbounded_String; Content_Type : Ada.Strings.Unbounded.Unbounded_String; Length : Natural := 0; Test_Timeout : Boolean := False; end record; type Test_Server_Access is access all Test_Server'Class; -- Process the line received by the server. overriding procedure Process_Line (Into : in out Test_Server; Line : in Ada.Strings.Unbounded.Unbounded_String; Stream : in out Util.Streams.Texts.Reader_Stream'Class; Client : in out Util.Streams.Sockets.Socket_Stream'Class); type Test is new Util.Tests.Test with record Server : Test_Server_Access := null; end record; -- Test the http Get operation. procedure Test_Http_Get (T : in out Test); -- Test the http POST operation. procedure Test_Http_Post (T : in out Test); -- Test the http PUT operation. procedure Test_Http_Put (T : in out Test); -- Test the http DELETE operation. procedure Test_Http_Delete (T : in out Test); -- Test the http OPTIONS operation. procedure Test_Http_Options (T : in out Test); -- Test the http timeout. procedure Test_Http_Timeout (T : in out Test); overriding procedure Set_Up (T : in out Test); overriding procedure Tear_Down (T : in out Test); -- Get the test server base URI. function Get_Uri (T : in Test) return String; -- The <b>Http_Tests</b> package must be instantiated with one of the HTTP implementation. -- The <b>Register</b> procedure configures the Http.Client to use the given HTTP -- implementation before running the test. generic with procedure Register; NAME : in String; package Http_Tests is procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite); type Http_Test is new Test with null record; overriding procedure Set_Up (T : in out Http_Test); end Http_Tests; end Util.Http.Clients.Tests;
Declare Test_Http_Options procedure
Declare Test_Http_Options procedure
Ada
apache-2.0
stcarrez/ada-util,stcarrez/ada-util
14b82c897ebff6dd46c9adb1b448a12f338b8974
regtests/wiki-filters-html-tests.adb
regtests/wiki-filters-html-tests.adb
----------------------------------------------------------------------- -- wiki-filters-html-tests -- Unit tests for wiki HTML filters -- Copyright (C) 2015 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Test_Caller; with Util.Assertions; with Util.Strings; with Util.Log.Loggers; package body Wiki.Filters.Html.Tests is Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("Wiki.Filters"); package Caller is new Util.Test_Caller (Test, "Wikis.Filters.Html"); procedure Assert_Equals is new Util.Assertions.Assert_Equals_T (Html_Tag); procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is begin Caller.Add_Test (Suite, "Test Wiki.Filters.Html.Find_Tag", Test_Find_Tag'Access); end Add_Tests; -- ------------------------------ -- Test Find_Tag operation. -- ------------------------------ procedure Test_Find_Tag (T : in out Test) is begin for I in Html_Tag'Range loop declare Name : constant String := Html_Tag'Image (I); Wname : constant Wide_Wide_String := Html_Tag'Wide_Wide_Image (I); Pos : constant Natural := Util.Strings.Index (Name, '_'); Tag : constant Html_Tag := Find_Tag (Wname (Wname'First .. Pos - 1)); begin Log.Info ("Checking tag {0}", Name); Assert_Equals (T, I, Tag, "Find_Tag failed"); Assert_Equals (T, UNKNOWN_TAG, Find_Tag (Wname (Wname'First .. Pos - 1) & "x"), "Find_Tag must return UNKNOWN_TAG"); end; end loop; end Test_Find_Tag; end Wiki.Filters.Html.Tests;
----------------------------------------------------------------------- -- wiki-filters-html-tests -- Unit tests for wiki HTML filters -- Copyright (C) 2015 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Test_Caller; with Util.Assertions; with Util.Strings; with Util.Log.Loggers; package body Wiki.Filters.Html.Tests is Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("Wiki.Filters"); package Caller is new Util.Test_Caller (Test, "Wikis.Filters.Html"); procedure Assert_Equals is new Util.Assertions.Assert_Equals_T (Html_Tag); procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is begin Caller.Add_Test (Suite, "Test Wiki.Filters.Html.Find_Tag", Test_Find_Tag'Access); end Add_Tests; -- ------------------------------ -- Test Find_Tag operation. -- ------------------------------ procedure Test_Find_Tag (T : in out Test) is begin for I in Html_Tag'Range loop declare Name : constant String := Html_Tag'Image (I); Wname : constant Wide_Wide_String := Html_Tag'Wide_Wide_Image (I); Pos : constant Natural := Util.Strings.Index (Name, '_'); Tag : constant Html_Tag := Find_Tag (Wname (Wname'First .. Pos - 1)); begin Log.Info ("Checking tag {0}", Name); if I /= ROOT_HTML_TAG then Assert_Equals (T, I, Tag, "Find_Tag failed"); end if; Assert_Equals (T, UNKNOWN_TAG, Find_Tag (Wname (Wname'First .. Pos - 1) & "x"), "Find_Tag must return UNKNOWN_TAG"); end; end loop; end Test_Find_Tag; end Wiki.Filters.Html.Tests;
Fix unit test
Fix unit test
Ada
apache-2.0
stcarrez/ada-wiki,stcarrez/ada-wiki
68373f27a5d35a51fb73e35ec3fee9af2114d6ce
resources/scripts/api/threatbook.ads
resources/scripts/api/threatbook.ads
-- Copyright 2021 Jeff Foley. All rights reserved. -- Use of this source code is governed by Apache 2 LICENSE that can be found in the LICENSE file. local json = require("json") name = "ThreatBook" type = "api" function start() setratelimit(5) end function check() local c local cfg = datasrc_config() if cfg ~= nil then c = cfg.credentials end if (c ~= nil and c.key ~= nil and c.key ~= "") then return true end return false end function vertical(ctx, domain) local c local cfg = datasrc_config() if cfg ~= nil then c = cfg.credentials end if (c == nil or c.key == nil or c.key == "") then return end local resp, err = request(ctx, { url=verturl(domain, key), headers={['Content-Type']="application/json"}, }) if (err ~= nil and err ~= "") then return end local d = json.decode(resp) if (d == nil or d.response_code ~= 0 or #(d.sub_domains.data) == 0) then return end for i, sub in pairs(d.sub_domains.data) do newname(ctx, sub) end end function verturl(domain, key) return "https://api.threatbook.cn/v3/domain/sub_domains?apikey=" .. key .. "&resource=" .. domain end
-- Copyright 2021 Jeff Foley. All rights reserved. -- Use of this source code is governed by Apache 2 LICENSE that can be found in the LICENSE file. local json = require("json") name = "ThreatBook" type = "api" function start() setratelimit(5) end function check() local c local cfg = datasrc_config() if cfg ~= nil then c = cfg.credentials end if (c ~= nil and c.key ~= nil and c.key ~= "") then return true end return false end function vertical(ctx, domain) local c local cfg = datasrc_config() if cfg ~= nil then c = cfg.credentials end if (c == nil or c.key == nil or c.key == "") then return end local resp, err = request(ctx, { url=verturl(domain, c.key), headers={['Content-Type']="application/json"}, }) if (err ~= nil and err ~= "") then return end local d = json.decode(resp) if (d == nil or d.response_code ~= 0 or #(d.sub_domains.data) == 0) then return end for i, sub in pairs(d.sub_domains.data) do newname(ctx, sub) end end function verturl(domain, key) return "https://api.threatbook.cn/v3/domain/sub_domains?apikey=" .. key .. "&resource=" .. domain end
Fix #647
Fix #647
Ada
apache-2.0
caffix/amass,caffix/amass
b26d2c0d53ce297efcd4a4e5b1dc72d8655417c2
regtests/util-encoders-tests.ads
regtests/util-encoders-tests.ads
----------------------------------------------------------------------- -- util-encodes-tests - Test for encoding -- Copyright (C) 2009, 2010, 2011, 2012, 2016, 2017 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Tests; package Util.Encoders.Tests is procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite); type Test is new Util.Tests.Test with null record; procedure Test_Hex (T : in out Test); procedure Test_Base64_Encode (T : in out Test); procedure Test_Base64_Decode (T : in out Test); procedure Test_Base64_URL_Encode (T : in out Test); procedure Test_Base64_URL_Decode (T : in out Test); procedure Test_Encoder (T : in out Test; C : in out Util.Encoders.Encoder); procedure Test_Base64_Benchmark (T : in out Test); procedure Test_SHA1_Encode (T : in out Test); procedure Test_SHA256_Encode (T : in out Test); -- Benchmark test for SHA1 procedure Test_SHA1_Benchmark (T : in out Test); -- Test HMAC-SHA1 procedure Test_HMAC_SHA1_RFC2202_T1 (T : in out Test); procedure Test_HMAC_SHA1_RFC2202_T2 (T : in out Test); procedure Test_HMAC_SHA1_RFC2202_T3 (T : in out Test); procedure Test_HMAC_SHA1_RFC2202_T4 (T : in out Test); procedure Test_HMAC_SHA1_RFC2202_T5 (T : in out Test); procedure Test_HMAC_SHA1_RFC2202_T6 (T : in out Test); procedure Test_HMAC_SHA1_RFC2202_T7 (T : in out Test); -- Test HMAC-SHA256 procedure Test_HMAC_SHA256_RFC4231_T1 (T : in out Test); procedure Test_HMAC_SHA256_RFC4231_T2 (T : in out Test); procedure Test_HMAC_SHA256_RFC4231_T3 (T : in out Test); procedure Test_HMAC_SHA256_RFC4231_T4 (T : in out Test); procedure Test_HMAC_SHA256_RFC4231_T5 (T : in out Test); procedure Test_HMAC_SHA256_RFC4231_T6 (T : in out Test); procedure Test_HMAC_SHA256_RFC4231_T7 (T : in out Test); -- Test encoding leb128. procedure Test_LEB128 (T : in out Test); -- Test encoding leb128 + base64url. procedure Test_Base64_LEB128 (T : in out Test); end Util.Encoders.Tests;
----------------------------------------------------------------------- -- util-encodes-tests - Test for encoding -- Copyright (C) 2009, 2010, 2011, 2012, 2016, 2017 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Tests; package Util.Encoders.Tests is procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite); type Test is new Util.Tests.Test with null record; procedure Test_Hex (T : in out Test); procedure Test_Base64_Encode (T : in out Test); procedure Test_Base64_Decode (T : in out Test); procedure Test_Base64_URL_Encode (T : in out Test); procedure Test_Base64_URL_Decode (T : in out Test); procedure Test_Encoder (T : in out Test; C : in out Util.Encoders.Encoder); procedure Test_Base64_Benchmark (T : in out Test); procedure Test_SHA1_Encode (T : in out Test); procedure Test_SHA256_Encode (T : in out Test); -- Benchmark test for SHA1 procedure Test_SHA1_Benchmark (T : in out Test); -- Test HMAC-SHA1 procedure Test_HMAC_SHA1_RFC2202_T1 (T : in out Test); procedure Test_HMAC_SHA1_RFC2202_T2 (T : in out Test); procedure Test_HMAC_SHA1_RFC2202_T3 (T : in out Test); procedure Test_HMAC_SHA1_RFC2202_T4 (T : in out Test); procedure Test_HMAC_SHA1_RFC2202_T5 (T : in out Test); procedure Test_HMAC_SHA1_RFC2202_T6 (T : in out Test); procedure Test_HMAC_SHA1_RFC2202_T7 (T : in out Test); -- Test HMAC-SHA256 procedure Test_HMAC_SHA256_RFC4231_T1 (T : in out Test); procedure Test_HMAC_SHA256_RFC4231_T2 (T : in out Test); procedure Test_HMAC_SHA256_RFC4231_T3 (T : in out Test); procedure Test_HMAC_SHA256_RFC4231_T4 (T : in out Test); procedure Test_HMAC_SHA256_RFC4231_T5 (T : in out Test); procedure Test_HMAC_SHA256_RFC4231_T6 (T : in out Test); procedure Test_HMAC_SHA256_RFC4231_T7 (T : in out Test); -- Test encoding leb128. procedure Test_LEB128 (T : in out Test); -- Test encoding leb128 + base64url. procedure Test_Base64_LEB128 (T : in out Test); -- Test encrypt and decrypt operations. procedure Test_AES (T : in out Test); end Util.Encoders.Tests;
Declare the Test_AES procedure
Declare the Test_AES procedure
Ada
apache-2.0
stcarrez/ada-util,stcarrez/ada-util
17f7234a51c09b729f0e72b600c40977cbf1bfe2
regtests/util-encoders-tests.ads
regtests/util-encoders-tests.ads
----------------------------------------------------------------------- -- util-encodes-tests - Test for encoding -- Copyright (C) 2009, 2010, 2011, 2012, 2016, 2017, 2020 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Tests; package Util.Encoders.Tests is procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite); type Test is new Util.Tests.Test with null record; procedure Test_Hex (T : in out Test); procedure Test_Base64_Encode (T : in out Test); procedure Test_Base64_Decode (T : in out Test); procedure Test_Base64_URL_Encode (T : in out Test); procedure Test_Base64_URL_Decode (T : in out Test); procedure Test_Encoder (T : in out Test; C : in Util.Encoders.Encoder; D : in Util.Encoders.Decoder); procedure Test_Base64_Benchmark (T : in out Test); procedure Test_SHA1_Encode (T : in out Test); procedure Test_SHA256_Encode (T : in out Test); -- Benchmark test for SHA1 procedure Test_SHA1_Benchmark (T : in out Test); -- Test HMAC-SHA1 procedure Test_HMAC_SHA1_RFC2202_T1 (T : in out Test); procedure Test_HMAC_SHA1_RFC2202_T2 (T : in out Test); procedure Test_HMAC_SHA1_RFC2202_T3 (T : in out Test); procedure Test_HMAC_SHA1_RFC2202_T4 (T : in out Test); procedure Test_HMAC_SHA1_RFC2202_T5 (T : in out Test); procedure Test_HMAC_SHA1_RFC2202_T6 (T : in out Test); procedure Test_HMAC_SHA1_RFC2202_T7 (T : in out Test); -- Test HMAC-SHA256 procedure Test_HMAC_SHA256_RFC4231_T1 (T : in out Test); procedure Test_HMAC_SHA256_RFC4231_T2 (T : in out Test); procedure Test_HMAC_SHA256_RFC4231_T3 (T : in out Test); procedure Test_HMAC_SHA256_RFC4231_T4 (T : in out Test); procedure Test_HMAC_SHA256_RFC4231_T5 (T : in out Test); procedure Test_HMAC_SHA256_RFC4231_T6 (T : in out Test); procedure Test_HMAC_SHA256_RFC4231_T7 (T : in out Test); -- Test encoding leb128. procedure Test_LEB128 (T : in out Test); -- Test encoding leb128 + base64url. procedure Test_Base64_LEB128 (T : in out Test); -- Test encrypt and decrypt operations. procedure Test_AES (T : in out Test); -- Test encrypt and decrypt operations. procedure Test_Encrypt_Decrypt_Secret (T : in out Test); procedure Test_Encrypt_Decrypt_Secret_OFB (T : in out Test); procedure Test_Encrypt_Decrypt_Secret_CFB (T : in out Test); procedure Test_Encrypt_Decrypt_Secret_CTR (T : in out Test); -- Test Decode Quoted-Printable encoding. procedure Test_Decode_Quoted_Printable (T : in out Test); end Util.Encoders.Tests;
----------------------------------------------------------------------- -- util-encodes-tests - Test for encoding -- Copyright (C) 2009 - 2022 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Tests; package Util.Encoders.Tests is procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite); type Test is new Util.Tests.Test with null record; procedure Test_Hex (T : in out Test); procedure Test_Base64_Encode (T : in out Test); procedure Test_Base64_Decode (T : in out Test); procedure Test_Base64_URL_Encode (T : in out Test); procedure Test_Base64_URL_Decode (T : in out Test); procedure Test_Encoder (T : in out Test; C : in Util.Encoders.Encoder; D : in Util.Encoders.Decoder); procedure Test_Base64_Benchmark (T : in out Test); procedure Test_SHA1_Encode (T : in out Test); procedure Test_SHA256_Encode (T : in out Test); -- Benchmark test for SHA1 procedure Test_SHA1_Benchmark (T : in out Test); -- Test HMAC-SHA1 procedure Test_HMAC_SHA1_RFC2202_T1 (T : in out Test); procedure Test_HMAC_SHA1_RFC2202_T2 (T : in out Test); procedure Test_HMAC_SHA1_RFC2202_T3 (T : in out Test); procedure Test_HMAC_SHA1_RFC2202_T4 (T : in out Test); procedure Test_HMAC_SHA1_RFC2202_T5 (T : in out Test); procedure Test_HMAC_SHA1_RFC2202_T6 (T : in out Test); procedure Test_HMAC_SHA1_RFC2202_T7 (T : in out Test); -- Test HMAC-SHA256 procedure Test_HMAC_SHA256_RFC4231_T1 (T : in out Test); procedure Test_HMAC_SHA256_RFC4231_T2 (T : in out Test); procedure Test_HMAC_SHA256_RFC4231_T3 (T : in out Test); procedure Test_HMAC_SHA256_RFC4231_T4 (T : in out Test); procedure Test_HMAC_SHA256_RFC4231_T5 (T : in out Test); procedure Test_HMAC_SHA256_RFC4231_T6 (T : in out Test); procedure Test_HMAC_SHA256_RFC4231_T7 (T : in out Test); -- Test encoding leb128. procedure Test_LEB128 (T : in out Test); -- Test encoding leb128 + base64url. procedure Test_Base64_LEB128 (T : in out Test); -- Test encrypt and decrypt operations. procedure Test_AES (T : in out Test); -- Test encrypt and decrypt operations. procedure Test_Encrypt_Decrypt_Secret (T : in out Test); procedure Test_Encrypt_Decrypt_Secret_OFB (T : in out Test); procedure Test_Encrypt_Decrypt_Secret_CFB (T : in out Test); procedure Test_Encrypt_Decrypt_Secret_CTR (T : in out Test); -- Test Decode Quoted-Printable encoding. procedure Test_Decode_Quoted_Printable (T : in out Test); -- Test the percent URI encoding. procedure Test_Encode_URI (T : in out Test); end Util.Encoders.Tests;
Declare the Test_Encode_URI procedure
Declare the Test_Encode_URI procedure
Ada
apache-2.0
stcarrez/ada-util,stcarrez/ada-util
9a7ec9ce9daba8db7d08f08b34d01320d1a522b6
src/asf-components-widgets-likes.adb
src/asf-components-widgets-likes.adb
----------------------------------------------------------------------- -- components-widgets-likes -- Social Likes Components -- Copyright (C) 2013 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Locales; with Util.Beans.Objects; with Util.Strings.Tokenizers; with ASF.Requests; with ASF.Contexts.Writer; package body ASF.Components.Widgets.Likes is FB_LAYOUT_ATTR : aliased constant String := "data-layout"; FB_SHOW_FACES_ATTR : aliased constant String := "data-show-faces"; FB_WIDTH_ATTR : aliased constant String := "data-width"; FB_ACTION_ATTR : aliased constant String := "data-action"; FB_FONT_ATTR : aliased constant String := "data-font"; FB_COlORSCHEME_ATTR : aliased constant String := "data-colorscheme"; FB_REF_ATTR : aliased constant String := "data-ref"; FB_KIDS_ATTR : aliased constant String := "data-kid_directed_site"; FACEBOOK_ATTRIBUTE_NAMES : Util.Strings.String_Set.Set; FACEBOOK_SCRIPT_ATTRIBUTE : constant String := "asf.widgets.facebook.script"; type Like_Generator_Binding is record Name : Util.Strings.Name_Access; Generator : Like_Generator_Access; end record; type Like_Generator_Array is array (1 .. MAX_LIKE_GENERATOR) of Like_Generator_Binding; FB_NAME : aliased constant String := "facebook"; FB_GENERATOR : aliased Facebook_Like_Generator; Generators : Like_Generator_Array := (1 => (FB_NAME'Access, FB_GENERATOR'Access), others => (null, null)); -- ------------------------------ -- Render the facebook like button according to the component attributes. -- ------------------------------ overriding procedure Render_Like (Generator : in Facebook_Like_Generator; UI : in UILike'Class; Href : in String; Context : in out ASF.Contexts.Faces.Faces_Context'Class) is Writer : constant Contexts.Writer.Response_Writer_Access := Context.Get_Response_Writer; Request : constant ASF.Requests.Request_Access := Context.Get_Request; begin if not Context.Is_Ajax_Request and then Util.Beans.Objects.Is_Null (Request.Get_Attribute (FACEBOOK_SCRIPT_ATTRIBUTE)) then Request.Set_Attribute (FACEBOOK_SCRIPT_ATTRIBUTE, Util.Beans.Objects.To_Object (True)); Writer.Queue_Script ("(function(d, s, id) { var js, fjs = d.getElementsByTagName(s)[0];" & "if (d.getElementById(id)) return;" & "js = d.createElement(s); js.id = id;" & "js.src = ""//connect.facebook.net/"); Writer.Queue_Script (Util.Locales.To_String (Context.Get_Locale)); Writer.Queue_Script ("/all.js#xfbml=1&;appId=116337738505130"); Writer.Queue_Script (Generator.App_Id); Writer.Queue_Script (""";fjs.parentNode.insertBefore(js, fjs);" & "}(document, 'script', 'facebook-jssdk'));"); Writer.Start_Element ("div"); Writer.Write_Attribute ("id", "fb-root"); Writer.End_Element ("div"); end if; Writer.Start_Element ("div"); Writer.Write_Attribute ("class", "fb-like"); Writer.Write_Attribute ("data-href", Href); Writer.Write_Attribute ("data-send", "true"); UI.Render_Attributes (Context, FACEBOOK_ATTRIBUTE_NAMES, Writer); Writer.End_Element ("div"); end Render_Like; -- ------------------------------ -- Get the link to submit in the like action. -- ------------------------------ function Get_Link (UI : in UILike; Context : in ASF.Contexts.Faces.Faces_Context'Class) return String is Href : constant String := UI.Get_Attribute ("href", Context, ""); begin if Href'Length > 0 then return Href; else return Context.Get_Request.Get_Request_URI; end if; end Get_Link; -- ------------------------------ -- Render an image with the source link created from an email address to the Gravatars service. -- ------------------------------ overriding procedure Encode_Begin (UI : in UILike; Context : in out ASF.Contexts.Faces.Faces_Context'Class) is begin if UI.Is_Rendered (Context) then declare Kind : constant String := UI.Get_Attribute ("type", Context, ""); Href : constant String := UILike'Class (UI).Get_Link (Context); procedure Render (Name : in String; Done : out Boolean); procedure Render (Name : in String; Done : out Boolean) is use type Util.Strings.Name_Access; begin Done := False; for I in Generators'Range loop exit when Generators (I).Name = null; if Generators (I).Name.all = Name then Generators (I).Generator.Render_Like (UI, Href, Context); return; end if; end loop; UI.Log_Error ("Like type {0} is not recognized", Name); end Render; begin if Kind'Length = 0 then UI.Log_Error ("The like type is empty."); else Util.Strings.Tokenizers.Iterate_Tokens (Content => Kind, Pattern => ",", Process => Render'Access); end if; end; end if; end Encode_Begin; -- ------------------------------ -- Register the like generator under the given name. -- ------------------------------ procedure Register_Like (Name : in Util.Strings.Name_Access; Generator : in Like_Generator_Access) is use type Util.Strings.Name_Access; begin for I in Generators'Range loop if Generators (I).Name = null then Generators (I).Name := Name; Generators (I).Generator := Generator; return; end if; end loop; end Register_Like; begin FACEBOOK_ATTRIBUTE_NAMES.Insert (FB_LAYOUT_ATTR'Access); FACEBOOK_ATTRIBUTE_NAMES.Insert (FB_SHOW_FACES_ATTR'Access); FACEBOOK_ATTRIBUTE_NAMES.Insert (FB_WIDTH_ATTR'Access); FACEBOOK_ATTRIBUTE_NAMES.Insert (FB_ACTION_ATTR'Access); FACEBOOK_ATTRIBUTE_NAMES.Insert (FB_FONT_ATTR'Access); FACEBOOK_ATTRIBUTE_NAMES.Insert (FB_COlORSCHEME_ATTR'Access); FACEBOOK_ATTRIBUTE_NAMES.Insert (FB_REF_ATTR'Access); FACEBOOK_ATTRIBUTE_NAMES.Insert (FB_KIDS_ATTR'Access); end ASF.Components.Widgets.Likes;
----------------------------------------------------------------------- -- components-widgets-likes -- Social Likes Components -- Copyright (C) 2013 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Locales; with Util.Beans.Objects; with Util.Strings.Tokenizers; with ASF.Requests; with ASF.Contexts.Writer; package body ASF.Components.Widgets.Likes is FB_LAYOUT_ATTR : aliased constant String := "data-layout"; FB_SHOW_FACES_ATTR : aliased constant String := "data-show-faces"; FB_WIDTH_ATTR : aliased constant String := "data-width"; FB_ACTION_ATTR : aliased constant String := "data-action"; FB_FONT_ATTR : aliased constant String := "data-font"; FB_COlORSCHEME_ATTR : aliased constant String := "data-colorscheme"; FB_REF_ATTR : aliased constant String := "data-ref"; FB_KIDS_ATTR : aliased constant String := "data-kid_directed_site"; FACEBOOK_ATTRIBUTE_NAMES : Util.Strings.String_Set.Set; FACEBOOK_SCRIPT_ATTRIBUTE : constant String := "asf.widgets.facebook.script"; GOOGLE_ATTRIBUTE_NAMES : Util.Strings.String_Set.Set; GOOGLE_SCRIPT_ATTRIBUTE : constant String := "asf.widgets.google.script"; type Like_Generator_Binding is record Name : Util.Strings.Name_Access; Generator : Like_Generator_Access; end record; type Like_Generator_Array is array (1 .. MAX_LIKE_GENERATOR) of Like_Generator_Binding; FB_NAME : aliased constant String := "facebook"; FB_GENERATOR : aliased Facebook_Like_Generator; G_NAME : aliased constant String := "google+"; G_GENERATOR : aliased Google_Like_Generator; Generators : Like_Generator_Array := (1 => (FB_NAME'Access, FB_GENERATOR'Access), 2 => (G_NAME'Access, G_GENERATOR'Access), others => (null, null)); -- ------------------------------ -- Render the facebook like button according to the component attributes. -- ------------------------------ overriding procedure Render_Like (Generator : in Facebook_Like_Generator; UI : in UILike'Class; Href : in String; Context : in out ASF.Contexts.Faces.Faces_Context'Class) is Writer : constant Contexts.Writer.Response_Writer_Access := Context.Get_Response_Writer; Request : constant ASF.Requests.Request_Access := Context.Get_Request; begin if not Context.Is_Ajax_Request and then Util.Beans.Objects.Is_Null (Request.Get_Attribute (FACEBOOK_SCRIPT_ATTRIBUTE)) then Request.Set_Attribute (FACEBOOK_SCRIPT_ATTRIBUTE, Util.Beans.Objects.To_Object (True)); Writer.Queue_Script ("(function(d, s, id) { var js, fjs = d.getElementsByTagName(s)[0];" & "if (d.getElementById(id)) return;" & "js = d.createElement(s); js.id = id;" & "js.src = ""//connect.facebook.net/"); Writer.Queue_Script (Util.Locales.To_String (Context.Get_Locale)); Writer.Queue_Script ("/all.js#xfbml=1&;appId=116337738505130"); Writer.Queue_Script (Generator.App_Id); Writer.Queue_Script (""";fjs.parentNode.insertBefore(js, fjs);" & "}(document, 'script', 'facebook-jssdk'));"); Writer.Start_Element ("div"); Writer.Write_Attribute ("id", "fb-root"); Writer.End_Element ("div"); end if; Writer.Start_Element ("div"); Writer.Write_Attribute ("class", "fb-like"); Writer.Write_Attribute ("data-href", Href); Writer.Write_Attribute ("data-send", "true"); UI.Render_Attributes (Context, FACEBOOK_ATTRIBUTE_NAMES, Writer); Writer.End_Element ("div"); end Render_Like; -- ------------------------------ -- Google like generator -- ------------------------------ overriding procedure Render_Like (Generator : in Google_Like_Generator; UI : in UILike'Class; Href : in String; Context : in out ASF.Contexts.Faces.Faces_Context'Class) is pragma Unreferenced (Generator); Writer : constant Contexts.Writer.Response_Writer_Access := Context.Get_Response_Writer; Request : constant ASF.Requests.Request_Access := Context.Get_Request; begin if not Context.Is_Ajax_Request and then Util.Beans.Objects.Is_Null (Request.Get_Attribute (GOOGLE_SCRIPT_ATTRIBUTE)) then Request.Set_Attribute (GOOGLE_SCRIPT_ATTRIBUTE, Util.Beans.Objects.To_Object (True)); Writer.Queue_Include_Script ("https://apis.google.com/js/plusone.js"); end if; Writer.Start_Element ("div"); Writer.Write_Attribute ("class", "g-plusone"); Writer.Write_Attribute ("data-href", Href); Writer.Write_Attribute ("data-send", "true"); UI.Render_Attributes (Context, GOOGLE_ATTRIBUTE_NAMES, Writer); Writer.End_Element ("div"); end Render_Like; -- ------------------------------ -- Get the link to submit in the like action. -- ------------------------------ function Get_Link (UI : in UILike; Context : in ASF.Contexts.Faces.Faces_Context'Class) return String is Href : constant String := UI.Get_Attribute ("href", Context, ""); begin if Href'Length > 0 then return Href; else return Context.Get_Request.Get_Request_URI; end if; end Get_Link; -- ------------------------------ -- Render an image with the source link created from an email address to the Gravatars service. -- ------------------------------ overriding procedure Encode_Begin (UI : in UILike; Context : in out ASF.Contexts.Faces.Faces_Context'Class) is begin if UI.Is_Rendered (Context) then declare Kind : constant String := UI.Get_Attribute ("type", Context, ""); Href : constant String := UILike'Class (UI).Get_Link (Context); procedure Render (Name : in String; Done : out Boolean); procedure Render (Name : in String; Done : out Boolean) is use type Util.Strings.Name_Access; begin Done := False; for I in Generators'Range loop exit when Generators (I).Name = null; if Generators (I).Name.all = Name then Generators (I).Generator.Render_Like (UI, Href, Context); return; end if; end loop; UI.Log_Error ("Like type {0} is not recognized", Name); end Render; begin if Kind'Length = 0 then UI.Log_Error ("The like type is empty."); else Util.Strings.Tokenizers.Iterate_Tokens (Content => Kind, Pattern => ",", Process => Render'Access); end if; end; end if; end Encode_Begin; -- ------------------------------ -- Register the like generator under the given name. -- ------------------------------ procedure Register_Like (Name : in Util.Strings.Name_Access; Generator : in Like_Generator_Access) is use type Util.Strings.Name_Access; begin for I in Generators'Range loop if Generators (I).Name = null then Generators (I).Name := Name; Generators (I).Generator := Generator; return; end if; end loop; end Register_Like; begin FACEBOOK_ATTRIBUTE_NAMES.Insert (FB_LAYOUT_ATTR'Access); FACEBOOK_ATTRIBUTE_NAMES.Insert (FB_SHOW_FACES_ATTR'Access); FACEBOOK_ATTRIBUTE_NAMES.Insert (FB_WIDTH_ATTR'Access); FACEBOOK_ATTRIBUTE_NAMES.Insert (FB_ACTION_ATTR'Access); FACEBOOK_ATTRIBUTE_NAMES.Insert (FB_FONT_ATTR'Access); FACEBOOK_ATTRIBUTE_NAMES.Insert (FB_COlORSCHEME_ATTR'Access); FACEBOOK_ATTRIBUTE_NAMES.Insert (FB_REF_ATTR'Access); FACEBOOK_ATTRIBUTE_NAMES.Insert (FB_KIDS_ATTR'Access); end ASF.Components.Widgets.Likes;
Implement the Google like generator
Implement the Google like generator
Ada
apache-2.0
Letractively/ada-asf,Letractively/ada-asf,Letractively/ada-asf
471582a6a0fddb29d6b289d1c01e07110eb41f93
src/asf-applications-messages.ads
src/asf-applications-messages.ads
----------------------------------------------------------------------- -- applications.messages -- Application Messages -- Copyright (C) 2010 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Strings.Unbounded; package ASF.Applications.Messages is type Severity is (NONE, INFO, WARN, ERROR, FATAL); -- ------------------------------ -- Application message -- ------------------------------ type Message is private; -- Return the message severity level. function Get_Severity (Msg : in Message) return Severity; -- Sets the message severity level. procedure Set_Severity (Msg : in out Message; Kind : in Severity); -- Return the localized message summary. function Get_Summary (Msg : in Message) return String; -- Sets the localized message summary. procedure Set_Summary (Msg : in out Message; Summary : in String); -- Return the localized message detail. If the message detail was -- not provided, returns the message summary. function Get_Detail (Msg : in Message) return String; -- Sets the localized message detail. procedure Set_Detail (Msg : in out Message; Detail : in String); -- Returns true if both messages are identical (same severity, same messages) function "=" (Left, Right : in Message) return Boolean; private type Message is record Kind : Severity := ERROR; Summary : Ada.Strings.Unbounded.Unbounded_String; Detail : Ada.Strings.Unbounded.Unbounded_String; end record; end ASF.Applications.Messages;
----------------------------------------------------------------------- -- applications.messages -- Application Messages -- Copyright (C) 2010, 2018 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Strings.Unbounded; with ASF.Utils; package ASF.Applications.Messages is type Severity is (NONE, INFO, WARN, ERROR, FATAL); -- ------------------------------ -- Application message -- ------------------------------ type Message is private; -- Return the message severity level. function Get_Severity (Msg : in Message) return Severity; -- Sets the message severity level. procedure Set_Severity (Msg : in out Message; Kind : in Severity); -- Return the localized message summary. function Get_Summary (Msg : in Message) return String; -- Sets the localized message summary. procedure Set_Summary (Msg : in out Message; Summary : in String); -- Format the localized message with the arguments and set the message summary. procedure Format_Summary (Msg : in out Message; Summary : in String; Args : in ASF.Utils.Object_Array); -- Return the localized message detail. If the message detail was -- not provided, returns the message summary. function Get_Detail (Msg : in Message) return String; -- Sets the localized message detail. procedure Set_Detail (Msg : in out Message; Detail : in String); -- Returns true if both messages are identical (same severity, same messages) function "=" (Left, Right : in Message) return Boolean; private type Message is record Kind : Severity := ERROR; Summary : Ada.Strings.Unbounded.Unbounded_String; Detail : Ada.Strings.Unbounded.Unbounded_String; end record; end ASF.Applications.Messages;
Declare the Format_Summary procedure to format and set the message summary
Declare the Format_Summary procedure to format and set the message summary
Ada
apache-2.0
stcarrez/ada-asf,stcarrez/ada-asf,stcarrez/ada-asf
cd2eaa331e31f921aeacdb04cdfd23e879174cb1
mat/src/frames/mat-frames-print.adb
mat/src/frames/mat-frames-print.adb
----------------------------------------------------------------------- -- Frames - Representation of stack frames -- Copyright (C) 2014 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Text_IO; use Ada.Text_IO; with MAT.Types; with Interfaces; procedure MAT.Frames.Print (File : in File_Type; F : in Frame_Type) is use MAT.Types; use Interfaces; Depth : Natural := F.Depth - F.Local_Depth + 1; Child : Frame_Ptr; procedure Print_Address (File : in File_Type; Addr : in Target_Addr); function Hex_Image (Val : Target_Addr; Len : Positive) return String; function Hex_Image (Val : Target_Addr; Len : Positive) return String is Conversion : constant String (1 .. 16) := "0123456789ABCDEF"; S : String (1 .. Len) := (others => '0'); P : Target_Addr := Val; N : Target_Addr; I : Positive := Len; begin while P /= 0 loop N := P mod 16; P := P / 16; S (I) := Conversion (Natural (N + 1)); exit when I = 1; I := I - 1; end loop; return S; end Hex_Image; procedure Print_Address (File : in File_Type; Addr : in Target_Addr) is begin Put (File, Hex_Image (Addr, 20)); end Print_Address; begin for I in 1 .. F.Local_Depth loop Set_Col (File, Positive_Count (Depth)); Print_Address (File, F.Calls (I)); Put_Line (" D " & Natural'Image (Depth)); Depth := Depth + 1; end loop; Child := F.Children; while Child /= null loop Print (File, Child); Child := Child.Next; end loop; end MAT.Frames.Print;
----------------------------------------------------------------------- -- Frames - Representation of stack frames -- Copyright (C) 2014 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Text_IO; use Ada.Text_IO; with MAT.Types; with Interfaces; procedure MAT.Frames.Print (File : in File_Type; F : in Frame_Type) is use MAT.Types; use Interfaces; Depth : Natural := F.Depth - F.Local_Depth + 1; Child : Frame_Type; procedure Print_Address (File : in File_Type; Addr : in Target_Addr); function Hex_Image (Val : Target_Addr; Len : Positive) return String; function Hex_Image (Val : Target_Addr; Len : Positive) return String is Conversion : constant String (1 .. 16) := "0123456789ABCDEF"; S : String (1 .. Len) := (others => '0'); P : Target_Addr := Val; N : Target_Addr; I : Positive := Len; begin while P /= 0 loop N := P mod 16; P := P / 16; S (I) := Conversion (Natural (N + 1)); exit when I = 1; I := I - 1; end loop; return S; end Hex_Image; procedure Print_Address (File : in File_Type; Addr : in Target_Addr) is begin Put (File, Hex_Image (Addr, 20)); end Print_Address; begin for I in 1 .. F.Local_Depth loop Set_Col (File, Positive_Count (Depth)); Print_Address (File, F.Calls (I)); Put_Line (" D " & Natural'Image (Depth)); Depth := Depth + 1; end loop; Child := F.Children; while Child /= null loop Print (File, Child); Child := Child.Next; end loop; end MAT.Frames.Print;
Fix compilation
Fix compilation
Ada
apache-2.0
stcarrez/mat,stcarrez/mat,stcarrez/mat
e85dc40927341e87d49e46293f208dc4419c0680
src/os-linux/util-streams-raw.adb
src/os-linux/util-streams-raw.adb
----------------------------------------------------------------------- -- util-streams-raw -- Raw streams (OS specific) -- Copyright (C) 2011, 2016, 2018 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.IO_Exceptions; package body Util.Streams.Raw is use Util.Systems.Os; use type Util.Systems.Types.File_Type; -- ----------------------- -- Initialize the raw stream to read and write on the given file descriptor. -- ----------------------- procedure Initialize (Stream : in out Raw_Stream; File : in File_Type) is begin if Stream.File /= NO_FILE then raise Ada.IO_Exceptions.Status_Error; end if; Stream.File := File; end Initialize; -- ----------------------- -- Close the stream. -- ----------------------- overriding procedure Close (Stream : in out Raw_Stream) is begin if Stream.File /= NO_FILE then if Close (Stream.File) /= 0 then raise Ada.IO_Exceptions.Device_Error; end if; Stream.File := NO_FILE; end if; end Close; -- ----------------------- -- Write the buffer array to the output stream. -- ----------------------- procedure Write (Stream : in out Raw_Stream; Buffer : in Ada.Streams.Stream_Element_Array) is begin if Write (Stream.File, Buffer'Address, Buffer'Length) < 0 then raise Ada.IO_Exceptions.Device_Error; end if; end Write; -- ----------------------- -- Read into the buffer as many bytes as possible and return in -- <b>last</b> the position of the last byte read. -- ----------------------- procedure Read (Stream : in out Raw_Stream; Into : out Ada.Streams.Stream_Element_Array; Last : out Ada.Streams.Stream_Element_Offset) is Res : Ssize_T; begin Res := Read (Stream.File, Into'Address, Into'Length); if Res < 0 then raise Ada.IO_Exceptions.Device_Error; end if; Last := Into'First + Ada.Streams.Stream_Element_Offset (Res) - 1; end Read; -- ----------------------- -- Reposition the read/write file offset. -- ----------------------- procedure Seek (Stream : in out Raw_Stream; Pos : in Util.Systems.Types.off_t; Mode : in Util.Systems.Types.Seek_Mode) is -- use type Util.Systems.Types.off_t; Res : Util.Systems.Types.off_t; begin Res := Sys_Lseek (Stream.File, Pos, Mode); if Res < 0 then raise Ada.IO_Exceptions.Device_Error; end if; end Seek; -- ----------------------- -- Flush the stream and release the buffer. -- ----------------------- procedure Finalize (Object : in out Raw_Stream) is begin Close (Object); end Finalize; end Util.Streams.Raw;
----------------------------------------------------------------------- -- util-streams-raw -- Raw streams (OS specific) -- Copyright (C) 2011, 2016, 2018 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.IO_Exceptions; with Interfaces.C; package body Util.Streams.Raw is use Util.Systems.Os; use type Util.Systems.Types.File_Type; -- GNAT 2018 issues a warning due to the use type Interfaces.C.int clause. -- But gcc 7.3 and older fails to compile and requires this use clause. pragma Warnings (Off); use type Interfaces.C.int; pragma Warnings (On); -- ----------------------- -- Initialize the raw stream to read and write on the given file descriptor. -- ----------------------- procedure Initialize (Stream : in out Raw_Stream; File : in File_Type) is begin if Stream.File /= NO_FILE then raise Ada.IO_Exceptions.Status_Error; end if; Stream.File := File; end Initialize; -- ----------------------- -- Close the stream. -- ----------------------- overriding procedure Close (Stream : in out Raw_Stream) is begin if Stream.File /= NO_FILE then if Close (Stream.File) /= 0 then raise Ada.IO_Exceptions.Device_Error; end if; Stream.File := NO_FILE; end if; end Close; -- ----------------------- -- Write the buffer array to the output stream. -- ----------------------- procedure Write (Stream : in out Raw_Stream; Buffer : in Ada.Streams.Stream_Element_Array) is begin if Write (Stream.File, Buffer'Address, Buffer'Length) < 0 then raise Ada.IO_Exceptions.Device_Error; end if; end Write; -- ----------------------- -- Read into the buffer as many bytes as possible and return in -- <b>last</b> the position of the last byte read. -- ----------------------- procedure Read (Stream : in out Raw_Stream; Into : out Ada.Streams.Stream_Element_Array; Last : out Ada.Streams.Stream_Element_Offset) is Res : Ssize_T; begin Res := Read (Stream.File, Into'Address, Into'Length); if Res < 0 then raise Ada.IO_Exceptions.Device_Error; end if; Last := Into'First + Ada.Streams.Stream_Element_Offset (Res) - 1; end Read; -- ----------------------- -- Reposition the read/write file offset. -- ----------------------- procedure Seek (Stream : in out Raw_Stream; Pos : in Util.Systems.Types.off_t; Mode : in Util.Systems.Types.Seek_Mode) is -- use type Util.Systems.Types.off_t; Res : Util.Systems.Types.off_t; begin Res := Sys_Lseek (Stream.File, Pos, Mode); if Res < 0 then raise Ada.IO_Exceptions.Device_Error; end if; end Seek; -- ----------------------- -- Flush the stream and release the buffer. -- ----------------------- procedure Finalize (Object : in out Raw_Stream) is begin Close (Object); end Finalize; end Util.Streams.Raw;
Fix compilation with FSF gcc 7.3: a use type Interfaces.C.int clause is required but it generates a warning with GNAT 2018
Fix compilation with FSF gcc 7.3: a use type Interfaces.C.int clause is required but it generates a warning with GNAT 2018
Ada
apache-2.0
stcarrez/ada-util,stcarrez/ada-util
47c89fbe21e0ec2c3f5fde99f27083839c2ca779
src/security-auth-oauth-facebook.adb
src/security-auth-oauth-facebook.adb
----------------------------------------------------------------------- -- security-auth-oauth-facebook -- Facebook OAuth based authentication -- Copyright (C) 2013 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Beans.Objects; with Util.Beans.Objects.Time; with Util.Serialize.Mappers.Record_Mapper; with Util.Http.Rest; package body Security.Auth.OAuth.Facebook is -- TIME_SHIFT : constant Duration := 12 * 3600.0; type Token_Info_Field_Type is (FIELD_APP_ID, FIELD_IS_VALID, FIELD_EXPIRES, FIELD_ISSUED_AT, FIELD_USER_ID, FIELD_EMAIL, FIELD_FIRST_NAME, FIELD_LAST_NAME, FIELD_NAME, FIELD_LOCALE, FIELD_GENDER); type Token_Info is record App_Id : Ada.Strings.Unbounded.Unbounded_String; Is_Valid : Boolean := False; Expires : Ada.Calendar.Time; Issued : Ada.Calendar.Time; User_Id : Ada.Strings.Unbounded.Unbounded_String; Email : Ada.Strings.Unbounded.Unbounded_String; Name : Ada.Strings.Unbounded.Unbounded_String; First_Name : Ada.Strings.Unbounded.Unbounded_String; Last_Name : Ada.Strings.Unbounded.Unbounded_String; Locale : Ada.Strings.Unbounded.Unbounded_String; Gender : Ada.Strings.Unbounded.Unbounded_String; end record; type Token_Info_Access is access all Token_Info; procedure Set_Member (Into : in out Token_Info; Field : in Token_Info_Field_Type; Value : in Util.Beans.Objects.Object); procedure Set_Member (Into : in out Token_Info; Field : in Token_Info_Field_Type; Value : in Util.Beans.Objects.Object) is begin case Field is when FIELD_APP_ID => Into.App_Id := Util.Beans.Objects.To_Unbounded_String (Value); when FIELD_IS_VALID => Into.Is_Valid := Util.Beans.Objects.To_Boolean (Value); when FIELD_EXPIRES => Into.Expires := Util.Beans.Objects.Time.To_Time (Value); when FIELD_ISSUED_AT => Into.Issued := Util.Beans.Objects.Time.To_Time (Value); when FIELD_USER_ID => Into.User_Id := Util.Beans.Objects.To_Unbounded_String (Value); when FIELD_EMAIL => Into.Email := Util.Beans.Objects.To_Unbounded_String (Value); when FIELD_NAME => Into.Name := Util.Beans.Objects.To_Unbounded_String (Value); when FIELD_FIRST_NAME => Into.First_Name := Util.Beans.Objects.To_Unbounded_String (Value); when FIELD_LAST_NAME => Into.Last_Name := Util.Beans.Objects.To_Unbounded_String (Value); when FIELD_LOCALE => Into.Locale := Util.Beans.Objects.To_Unbounded_String (Value); when FIELD_GENDER => Into.Gender := Util.Beans.Objects.To_Unbounded_String (Value); end case; end Set_Member; package Token_Info_Mapper is new Util.Serialize.Mappers.Record_Mapper (Element_Type => Token_Info, Element_Type_Access => Token_Info_Access, Fields => Token_Info_Field_Type, Set_Member => Set_Member); procedure Get_Token_Info is new Util.Http.Rest.Rest_Get (Element_Mapper => Token_Info_Mapper); Token_Info_Map : aliased Token_Info_Mapper.Mapper; -- ------------------------------ -- Verify the OAuth access token and retrieve information about the user. -- ------------------------------ overriding procedure Verify_Access_Token (Realm : in Manager; Assoc : in Association; Request : in Parameters'Class; Token : in Security.OAuth.Clients.Access_Token_Access; Result : in out Authentication) is use type Ada.Calendar.Time; T : constant String := Token.Get_Name; Info : aliased Token_Info; Now : constant Ada.Calendar.Time := Ada.Calendar.Clock; begin Get_Token_Info ("https://graph.facebook.com/debug_token?access_token=" & T & "&input_token=" & T, Token_Info_Map'Access, "/data", Info'Unchecked_Access); if not Info.Is_Valid then Set_Result (Result, INVALID_SIGNATURE, "invalid access token returned"); elsif Info.Issued + TIME_SHIFT < Now then Set_Result (Result, INVALID_SIGNATURE, "the access token issued more than 1 hour ago"); elsif Info.Expires + TIME_SHIFT < Now then Set_Result (Result, INVALID_SIGNATURE, "the access token has expored"); elsif Length (Info.User_Id) = 0 then Set_Result (Result, INVALID_SIGNATURE, "the access token refers to an empty user_id"); elsif Info.App_Id /= Realm.App.Get_Application_Identifier then Set_Result (Result, INVALID_SIGNATURE, "the access token was granted for another application"); else Result.Identity := To_Unbounded_String ("https://graph.facebook.com/"); Append (Result.Identity, Info.User_Id); Result.Claimed_Id := Result.Identity; Get_Token_Info ("https://graph.facebook.com/" & To_String (Info.User_Id) & "?access_token=" & T, Token_Info_Map'Access, "", Info'Unchecked_Access); Result.Email := Info.Email; Result.Full_Name := Info.Name; Result.First_Name := Info.First_Name; Result.Last_Name := Info.Last_Name; Result.Language := Info.Locale; Result.Gender := Info.Gender; Set_Result (Result, AUTHENTICATED, "authenticated"); end if; end Verify_Access_Token; begin Token_Info_Map.Add_Mapping ("app_id", FIELD_APP_ID); Token_Info_Map.Add_Mapping ("expires_at", FIELD_EXPIRES); Token_Info_Map.Add_Mapping ("issued_at", FIELD_ISSUED_AT); Token_Info_Map.Add_Mapping ("is_valid", FIELD_IS_VALID); Token_Info_Map.Add_Mapping ("user_id", FIELD_USER_ID); Token_Info_Map.Add_Mapping ("email", FIELD_EMAIL); Token_Info_Map.Add_Mapping ("name", FIELD_NAME); Token_Info_Map.Add_Mapping ("first_name", FIELD_FIRST_NAME); Token_Info_Map.Add_Mapping ("last_name", FIELD_LAST_NAME); Token_Info_Map.Add_Mapping ("locale", FIELD_LOCALE); Token_Info_Map.Add_Mapping ("gender", FIELD_GENDER); end Security.Auth.OAuth.Facebook;
----------------------------------------------------------------------- -- security-auth-oauth-facebook -- Facebook OAuth based authentication -- Copyright (C) 2013 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Beans.Objects; with Util.Beans.Objects.Time; with Util.Serialize.Mappers.Record_Mapper; with Util.Http.Rest; package body Security.Auth.OAuth.Facebook is -- TIME_SHIFT : constant Duration := 12 * 3600.0; type Token_Info_Field_Type is (FIELD_APP_ID, FIELD_IS_VALID, FIELD_EXPIRES, FIELD_ISSUED_AT, FIELD_USER_ID, FIELD_EMAIL, FIELD_FIRST_NAME, FIELD_LAST_NAME, FIELD_NAME, FIELD_LOCALE, FIELD_GENDER); type Token_Info is record App_Id : Ada.Strings.Unbounded.Unbounded_String; Is_Valid : Boolean := False; Expires : Ada.Calendar.Time; Issued : Ada.Calendar.Time; User_Id : Ada.Strings.Unbounded.Unbounded_String; Email : Ada.Strings.Unbounded.Unbounded_String; Name : Ada.Strings.Unbounded.Unbounded_String; First_Name : Ada.Strings.Unbounded.Unbounded_String; Last_Name : Ada.Strings.Unbounded.Unbounded_String; Locale : Ada.Strings.Unbounded.Unbounded_String; Gender : Ada.Strings.Unbounded.Unbounded_String; end record; type Token_Info_Access is access all Token_Info; procedure Set_Member (Into : in out Token_Info; Field : in Token_Info_Field_Type; Value : in Util.Beans.Objects.Object); procedure Set_Member (Into : in out Token_Info; Field : in Token_Info_Field_Type; Value : in Util.Beans.Objects.Object) is begin case Field is when FIELD_APP_ID => Into.App_Id := Util.Beans.Objects.To_Unbounded_String (Value); when FIELD_IS_VALID => Into.Is_Valid := Util.Beans.Objects.To_Boolean (Value); when FIELD_EXPIRES => Into.Expires := Util.Beans.Objects.Time.To_Time (Value); when FIELD_ISSUED_AT => Into.Issued := Util.Beans.Objects.Time.To_Time (Value); when FIELD_USER_ID => Into.User_Id := Util.Beans.Objects.To_Unbounded_String (Value); when FIELD_EMAIL => Into.Email := Util.Beans.Objects.To_Unbounded_String (Value); when FIELD_NAME => Into.Name := Util.Beans.Objects.To_Unbounded_String (Value); when FIELD_FIRST_NAME => Into.First_Name := Util.Beans.Objects.To_Unbounded_String (Value); when FIELD_LAST_NAME => Into.Last_Name := Util.Beans.Objects.To_Unbounded_String (Value); when FIELD_LOCALE => Into.Locale := Util.Beans.Objects.To_Unbounded_String (Value); when FIELD_GENDER => Into.Gender := Util.Beans.Objects.To_Unbounded_String (Value); end case; end Set_Member; package Token_Info_Mapper is new Util.Serialize.Mappers.Record_Mapper (Element_Type => Token_Info, Element_Type_Access => Token_Info_Access, Fields => Token_Info_Field_Type, Set_Member => Set_Member); procedure Get_Token_Info is new Util.Http.Rest.Rest_Get (Element_Mapper => Token_Info_Mapper); Token_Info_Map : aliased Token_Info_Mapper.Mapper; -- ------------------------------ -- Verify the OAuth access token and retrieve information about the user. -- ------------------------------ overriding procedure Verify_Access_Token (Realm : in Manager; Assoc : in Association; Request : in Parameters'Class; Token : in Security.OAuth.Clients.Access_Token_Access; Result : in out Authentication) is pragma Unreferenced (Assoc, Request); use type Ada.Calendar.Time; T : constant String := Token.Get_Name; Info : aliased Token_Info; Now : constant Ada.Calendar.Time := Ada.Calendar.Clock; begin Get_Token_Info ("https://graph.facebook.com/debug_token?access_token=" & T & "&input_token=" & T, Token_Info_Map'Access, "/data", Info'Unchecked_Access); if not Info.Is_Valid then Set_Result (Result, INVALID_SIGNATURE, "invalid access token returned"); elsif Info.Issued + TIME_SHIFT < Now then Set_Result (Result, INVALID_SIGNATURE, "the access token issued more than 1 hour ago"); elsif Info.Expires + TIME_SHIFT < Now then Set_Result (Result, INVALID_SIGNATURE, "the access token has expored"); elsif Length (Info.User_Id) = 0 then Set_Result (Result, INVALID_SIGNATURE, "the access token refers to an empty user_id"); elsif Info.App_Id /= Realm.App.Get_Application_Identifier then Set_Result (Result, INVALID_SIGNATURE, "the access token was granted for another application"); else Result.Identity := To_Unbounded_String ("https://graph.facebook.com/"); Append (Result.Identity, Info.User_Id); Result.Claimed_Id := Result.Identity; Get_Token_Info ("https://graph.facebook.com/" & To_String (Info.User_Id) & "?access_token=" & T, Token_Info_Map'Access, "", Info'Unchecked_Access); Result.Email := Info.Email; Result.Full_Name := Info.Name; Result.First_Name := Info.First_Name; Result.Last_Name := Info.Last_Name; Result.Language := Info.Locale; Result.Gender := Info.Gender; Set_Result (Result, AUTHENTICATED, "authenticated"); end if; end Verify_Access_Token; begin Token_Info_Map.Add_Mapping ("app_id", FIELD_APP_ID); Token_Info_Map.Add_Mapping ("expires_at", FIELD_EXPIRES); Token_Info_Map.Add_Mapping ("issued_at", FIELD_ISSUED_AT); Token_Info_Map.Add_Mapping ("is_valid", FIELD_IS_VALID); Token_Info_Map.Add_Mapping ("user_id", FIELD_USER_ID); Token_Info_Map.Add_Mapping ("email", FIELD_EMAIL); Token_Info_Map.Add_Mapping ("name", FIELD_NAME); Token_Info_Map.Add_Mapping ("first_name", FIELD_FIRST_NAME); Token_Info_Map.Add_Mapping ("last_name", FIELD_LAST_NAME); Token_Info_Map.Add_Mapping ("locale", FIELD_LOCALE); Token_Info_Map.Add_Mapping ("gender", FIELD_GENDER); end Security.Auth.OAuth.Facebook;
Fix compilation warning
Fix compilation warning
Ada
apache-2.0
stcarrez/ada-security
4a68a2f1019489f6a935b10f558653e0db2dabdf
src/wiki-streams-html-builders.ads
src/wiki-streams-html-builders.ads
----------------------------------------------------------------------- -- wiki-streams-html-builders -- Wiki writer to a string builder -- Copyright (C) 2011, 2012, 2013, 2015, 2016 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Wiki.Streams.Builders; -- == Writer interfaces == -- The <tt>Wiki.Writers</tt> package defines the interfaces used by the renderer to write -- their outputs. -- package Wiki.Streams.Html.Builders is type Html_Output_Builder_Stream is limited new Wiki.Streams.Builders.Output_Builder_Stream and Wiki.Streams.Html.Html_Output_Stream with private; type Html_Output_Builder_Stream_Access is access all Html_Output_Builder_Stream'Class; overriding procedure Write_Wide_Element (Stream : in out Html_Output_Builder_Stream; Name : in String; Content : in Wiki.Strings.WString); overriding procedure Write_Wide_Attribute (Stream : in out Html_Output_Builder_Stream; Name : in String; Content : in Unbounded_Wide_Wide_String); -- Write an XML attribute within an XML element. -- The attribute value is escaped according to the XML escape rules. overriding procedure Write_Wide_Attribute (Stream : in out Html_Output_Builder_Stream; Name : in String; Content : in Wiki.Strings.WString); overriding procedure Start_Element (Stream : in out Html_Output_Builder_Stream; Name : in String); overriding procedure End_Element (Stream : in out Html_Output_Builder_Stream; Name : in String); overriding procedure Write_Wide_Text (Stream : in out Html_Output_Builder_Stream; Content : in Wiki.Strings.WString); private type Html_Output_Builder_Stream is limited new Wiki.Streams.Builders.Output_Builder_Stream and Wiki.Streams.Html.Html_Output_Stream with record -- Whether an XML element must be closed (that is a '>' is necessary) Close_Start : Boolean := False; end record; end Wiki.Streams.Html.Builders;
----------------------------------------------------------------------- -- wiki-streams-html-builders -- Wiki writer to a string builder -- Copyright (C) 2011, 2012, 2013, 2015, 2016 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Wiki.Streams.Builders; -- == Writer interfaces == -- The <tt>Wiki.Writers</tt> package defines the interfaces used by the renderer to write -- their outputs. -- package Wiki.Streams.Html.Builders is type Html_Output_Builder_Stream is limited new Wiki.Streams.Builders.Output_Builder_Stream and Wiki.Streams.Html.Html_Output_Stream with private; type Html_Output_Builder_Stream_Access is access all Html_Output_Builder_Stream'Class; overriding procedure Write_Wide_Element (Stream : in out Html_Output_Builder_Stream; Name : in String; Content : in Wiki.Strings.WString); overriding procedure Write_Wide_Attribute (Stream : in out Html_Output_Builder_Stream; Name : in String; Content : in Wiki.Strings.UString); -- Write an XML attribute within an XML element. -- The attribute value is escaped according to the XML escape rules. overriding procedure Write_Wide_Attribute (Stream : in out Html_Output_Builder_Stream; Name : in String; Content : in Wiki.Strings.WString); overriding procedure Start_Element (Stream : in out Html_Output_Builder_Stream; Name : in String); overriding procedure End_Element (Stream : in out Html_Output_Builder_Stream; Name : in String); overriding procedure Write_Wide_Text (Stream : in out Html_Output_Builder_Stream; Content : in Wiki.Strings.WString); private type Html_Output_Builder_Stream is limited new Wiki.Streams.Builders.Output_Builder_Stream and Wiki.Streams.Html.Html_Output_Stream with record -- Whether an XML element must be closed (that is a '>' is necessary) Close_Start : Boolean := False; end record; end Wiki.Streams.Html.Builders;
Use the Wiki.Strings.UString type
Use the Wiki.Strings.UString type
Ada
apache-2.0
stcarrez/ada-wiki,stcarrez/ada-wiki
f116c99712efc776625e0e980925814676f93afc
awa/regtests/awa_command.adb
awa/regtests/awa_command.adb
----------------------------------------------------------------------- -- awa_command - Tests for AWA command -- Copyright (C) 2020 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Commands; with Util.Tests; with AWA.Tests; with AWA.Commands.Drivers; with AWA.Commands.List; with AWA.Commands.Start; with AWA.Commands.Stop; with Servlet.Server; with AWA.Tests; with ADO.Drivers; with AWA.Testsuite; procedure AWA_Command is package Server_Commands is new AWA.Commands.Drivers (Driver_Name => "awa", Container_Type => Servlet.Server.Container); package List_Command is new AWA.Commands.List (Server_Commands); package Start_Command is new AWA.Commands.Start (Server_Commands); package Stop_Command is new AWA.Commands.Stop (Server_Commands); App : aliased AWA.Tests.Test_Application; Context : AWA.Commands.Context_Type; Arguments : Util.Commands.Dynamic_Argument_List; Suite : Util.Tests.Access_Test_Suite := AWA.Testsuite.Suite; begin ADO.Drivers.Initialize; Server_Commands.WS.Register_Application ("/test", App'Unchecked_Access); Server_Commands.Run (Context, Arguments); end AWA_Command;
----------------------------------------------------------------------- -- awa_command - Tests for AWA command -- Copyright (C) 2020 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Commands; with Util.Tests; with AWA.Tests; with AWA.Commands.Drivers; with AWA.Commands.List; with AWA.Commands.Start; with AWA.Commands.Stop; with Servlet.Server; with ADO.Drivers; with AWA.Testsuite; procedure AWA_Command is package Server_Commands is new AWA.Commands.Drivers (Driver_Name => "awa", Container_Type => Servlet.Server.Container); package List_Command is new AWA.Commands.List (Server_Commands); package Start_Command is new AWA.Commands.Start (Server_Commands); package Stop_Command is new AWA.Commands.Stop (Server_Commands); App : aliased AWA.Tests.Test_Application; Context : AWA.Commands.Context_Type; Arguments : Util.Commands.Dynamic_Argument_List; Suite : Util.Tests.Access_Test_Suite := AWA.Testsuite.Suite; pragma Unreferenced (Suite); begin ADO.Drivers.Initialize; Server_Commands.WS.Register_Application ("/test", App'Unchecked_Access); Server_Commands.Run (Context, Arguments); exception when E : others => AWA.Commands.Print (Context, E); end AWA_Command;
Handle exceptions and report them by using the Print procedure
Handle exceptions and report them by using the Print procedure
Ada
apache-2.0
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
ccabc96e88c53b258d238635130b2e5421e60a9b
src/util-listeners-lifecycles.ads
src/util-listeners-lifecycles.ads
----------------------------------------------------------------------- -- util-listeners-lifecycles -- Listeners -- Copyright (C) 2012 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- -- The `Lifecycles` package provides a listener interface dedicated to -- track lifecycle managements on objects. It defines a set of procedures to be -- notified when an object is created, updated or deleted. generic type Element_Type (<>) is limited private; package Util.Listeners.Lifecycles is -- ------------------------------ -- Lifecycle listener -- ------------------------------ type Listener is limited interface and Util.Listeners.Listener; -- The `On_Create` procedure is called by `Notify_Create` to notify the creation of the item. procedure On_Create (Instance : in Listener; Item : in Element_Type) is abstract; -- The `On_Update` procedure is called by `Notify_Update` to notify the update of the item. procedure On_Update (Instance : in Listener; Item : in Element_Type) is abstract; -- The `On_Delete` procedure is called by `Notify_Delete` to notify the deletion of the item. procedure On_Delete (Instance : in Listener; Item : in Element_Type) is abstract; -- Inform the the lifecycle listeners registered in `List` that the item passed in `Item` -- has been created (calls `On_Create`). procedure Notify_Create (List : in Util.Listeners.List; Item : in Element_Type); -- Inform the the lifecycle listeners registered in `List` that the item passed in `Item` -- has been updated (calls `On_Update`). procedure Notify_Update (List : in Util.Listeners.List; Item : in Element_Type); -- Inform the the lifecycle listeners registered in `List` that the item passed in `Item` -- has been deleted (calls `On_Delete`). procedure Notify_Delete (List : in Util.Listeners.List; Item : in Element_Type); end Util.Listeners.Lifecycles;
----------------------------------------------------------------------- -- util-listeners-lifecycles -- Listeners -- Copyright (C) 2012 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- -- The `Lifecycles` package provides a listener interface dedicated to -- track lifecycle managements on objects. It defines a set of procedures to be -- notified when an object is created, updated or deleted. -- -- Notes: another implementation can be made by using three different listener lists -- that use the simple observer pattern. generic type Element_Type (<>) is limited private; package Util.Listeners.Lifecycles is -- ------------------------------ -- Lifecycle listener -- ------------------------------ type Listener is limited interface and Util.Listeners.Listener; -- The `On_Create` procedure is called by `Notify_Create` to notify the creation of the item. procedure On_Create (Instance : in Listener; Item : in Element_Type) is abstract; -- The `On_Update` procedure is called by `Notify_Update` to notify the update of the item. procedure On_Update (Instance : in Listener; Item : in Element_Type) is abstract; -- The `On_Delete` procedure is called by `Notify_Delete` to notify the deletion of the item. procedure On_Delete (Instance : in Listener; Item : in Element_Type) is abstract; -- Inform the the lifecycle listeners registered in `List` that the item passed in `Item` -- has been created (calls `On_Create`). procedure Notify_Create (List : in Util.Listeners.List; Item : in Element_Type); -- Inform the the lifecycle listeners registered in `List` that the item passed in `Item` -- has been updated (calls `On_Update`). procedure Notify_Update (List : in Util.Listeners.List; Item : in Element_Type); -- Inform the the lifecycle listeners registered in `List` that the item passed in `Item` -- has been deleted (calls `On_Delete`). procedure Notify_Delete (List : in Util.Listeners.List; Item : in Element_Type); end Util.Listeners.Lifecycles;
Update the documentation
Update the documentation
Ada
apache-2.0
flottokarotto/ada-util,Letractively/ada-util,flottokarotto/ada-util,Letractively/ada-util
aaa80d65c65e7c0ee6b16612df136fdc403366ae
src/xml/util-serialize-io-xml.ads
src/xml/util-serialize-io-xml.ads
----------------------------------------------------------------------- -- util-serialize-io-xml -- XML Serialization Driver -- Copyright (C) 2011, 2012, 2016, 2017 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Sax.Exceptions; with Sax.Locators; with Sax.Readers; with Sax.Attributes; with Unicode.CES; with Input_Sources; with Ada.Streams; with Ada.Strings.Unbounded; with Util.Streams.Buffered; with Util.Streams.Texts; package Util.Serialize.IO.XML is Parse_Error : exception; type Parser is new Serialize.IO.Parser with private; -- Parse the stream using the JSON parser. procedure Parse (Handler : in out Parser; Stream : in out Util.Streams.Buffered.Buffered_Stream'Class); -- Set the XHTML reader to ignore or not the white spaces. -- When set to True, the ignorable white spaces will not be kept. procedure Set_Ignore_White_Spaces (Reader : in out Parser; Value : in Boolean); -- Set the XHTML reader to ignore empty lines. procedure Set_Ignore_Empty_Lines (Reader : in out Parser; Value : in Boolean); -- Get the current location (file and line) to report an error message. function Get_Location (Handler : in Parser) return String; type Xhtml_Reader is new Sax.Readers.Reader with private; -- ------------------------------ -- XML Output Stream -- ------------------------------ -- The <b>Output_Stream</b> provides methods for creating an XML output stream. -- The stream object takes care of the XML escape rules. type Output_Stream is limited new Util.Serialize.IO.Output_Stream with private; -- Set the target output stream. procedure Initialize (Stream : in out Output_Stream; Output : in Util.Streams.Texts.Print_Stream_Access); -- Flush the buffer (if any) to the sink. overriding procedure Flush (Stream : in out Output_Stream); -- Close the sink. overriding procedure Close (Stream : in out Output_Stream); -- Write the buffer array to the output stream. overriding procedure Write (Stream : in out Output_Stream; Buffer : in Ada.Streams.Stream_Element_Array); -- Write a raw character on the stream. procedure Write (Stream : in out Output_Stream; Char : in Character); -- Write a wide character on the stream doing some conversion if necessary. -- The default implementation translates the wide character to a UTF-8 sequence. procedure Write_Wide (Stream : in out Output_Stream; Item : in Wide_Wide_Character); -- Write a raw string on the stream. procedure Write (Stream : in out Output_Stream; Item : in String); -- Write a character on the response stream and escape that character as necessary. procedure Write_Escape (Stream : in out Output_Stream'Class; Char : in Wide_Wide_Character); -- Write the value as a XML string. Special characters are escaped using the XML -- escape rules. procedure Write_String (Stream : in out Output_Stream; Value : in String); -- Write the value as a XML string. Special characters are escaped using the XML -- escape rules. procedure Write_Wide_String (Stream : in out Output_Stream; Value : in Wide_Wide_String); -- Write the value as a XML string. Special characters are escaped using the XML -- escape rules. procedure Write_String (Stream : in out Output_Stream; Value : in Util.Beans.Objects.Object); -- Start a new XML object. procedure Start_Entity (Stream : in out Output_Stream; Name : in String); -- Terminates the current XML object. procedure End_Entity (Stream : in out Output_Stream; Name : in String); -- Write the attribute name/value pair. overriding procedure Write_Attribute (Stream : in out Output_Stream; Name : in String; Value : in String); overriding procedure Write_Wide_Attribute (Stream : in out Output_Stream; Name : in String; Value : in Wide_Wide_String); overriding procedure Write_Attribute (Stream : in out Output_Stream; Name : in String; Value : in Integer); overriding procedure Write_Attribute (Stream : in out Output_Stream; Name : in String; Value : in Boolean); -- Write a XML name/value attribute. procedure Write_Attribute (Stream : in out Output_Stream; Name : in String; Value : in Util.Beans.Objects.Object); -- Write the entity value. overriding procedure Write_Entity (Stream : in out Output_Stream; Name : in String; Value : in String); overriding procedure Write_Wide_Entity (Stream : in out Output_Stream; Name : in String; Value : in Wide_Wide_String); overriding procedure Write_Entity (Stream : in out Output_Stream; Name : in String; Value : in Boolean); overriding procedure Write_Entity (Stream : in out Output_Stream; Name : in String; Value : in Integer); overriding procedure Write_Entity (Stream : in out Output_Stream; Name : in String; Value : in Ada.Calendar.Time); overriding procedure Write_Long_Entity (Stream : in out Output_Stream; Name : in String; Value : in Long_Long_Integer); overriding procedure Write_Enum_Entity (Stream : in out Output_Stream; Name : in String; Value : in String); -- Write a XML name/value entity (see Write_Attribute). overriding procedure Write_Entity (Stream : in out Output_Stream; Name : in String; Value : in Util.Beans.Objects.Object); -- Starts a XML array. overriding procedure Start_Array (Stream : in out Output_Stream; Name : in String); -- Terminates a XML array. overriding procedure End_Array (Stream : in out Output_Stream; Name : in String); -- Return the location where the exception was raised. function Get_Location (Except : Sax.Exceptions.Sax_Parse_Exception'Class) return String; private overriding procedure Warning (Handler : in out Xhtml_Reader; Except : in Sax.Exceptions.Sax_Parse_Exception'Class); overriding procedure Error (Handler : in out Xhtml_Reader; Except : in Sax.Exceptions.Sax_Parse_Exception'Class); overriding procedure Fatal_Error (Handler : in out Xhtml_Reader; Except : in Sax.Exceptions.Sax_Parse_Exception'Class); overriding procedure Set_Document_Locator (Handler : in out Xhtml_Reader; Loc : in out Sax.Locators.Locator); overriding procedure Start_Document (Handler : in out Xhtml_Reader); overriding procedure End_Document (Handler : in out Xhtml_Reader); overriding procedure Start_Prefix_Mapping (Handler : in out Xhtml_Reader; Prefix : in Unicode.CES.Byte_Sequence; URI : in Unicode.CES.Byte_Sequence); overriding procedure End_Prefix_Mapping (Handler : in out Xhtml_Reader; Prefix : in Unicode.CES.Byte_Sequence); overriding procedure Start_Element (Handler : in out Xhtml_Reader; Namespace_URI : in Unicode.CES.Byte_Sequence := ""; Local_Name : in Unicode.CES.Byte_Sequence := ""; Qname : in Unicode.CES.Byte_Sequence := ""; Atts : in Sax.Attributes.Attributes'Class); overriding procedure End_Element (Handler : in out Xhtml_Reader; Namespace_URI : in Unicode.CES.Byte_Sequence := ""; Local_Name : in Unicode.CES.Byte_Sequence := ""; Qname : in Unicode.CES.Byte_Sequence := ""); overriding procedure Characters (Handler : in out Xhtml_Reader; Ch : in Unicode.CES.Byte_Sequence); overriding procedure Ignorable_Whitespace (Handler : in out Xhtml_Reader; Ch : in Unicode.CES.Byte_Sequence); overriding procedure Processing_Instruction (Handler : in out Xhtml_Reader; Target : in Unicode.CES.Byte_Sequence; Data : in Unicode.CES.Byte_Sequence); overriding procedure Skipped_Entity (Handler : in out Xhtml_Reader; Name : in Unicode.CES.Byte_Sequence); overriding procedure Start_Cdata (Handler : in out Xhtml_Reader); overriding procedure End_Cdata (Handler : in out Xhtml_Reader); overriding function Resolve_Entity (Handler : Xhtml_Reader; Public_Id : Unicode.CES.Byte_Sequence; System_Id : Unicode.CES.Byte_Sequence) return Input_Sources.Input_Source_Access; overriding procedure Start_DTD (Handler : in out Xhtml_Reader; Name : Unicode.CES.Byte_Sequence; Public_Id : Unicode.CES.Byte_Sequence := ""; System_Id : Unicode.CES.Byte_Sequence := ""); procedure Collect_Text (Handler : in out Xhtml_Reader; Content : Unicode.CES.Byte_Sequence); type Xhtml_Reader is new Sax.Readers.Reader with record Stack_Pos : Natural := 0; Handler : access Parser'Class; Text : Ada.Strings.Unbounded.Unbounded_String; -- Whether white spaces can be ignored. Ignore_White_Spaces : Boolean := True; -- Whether empty lines should be ignored (when white spaces are kept). Ignore_Empty_Lines : Boolean := True; end record; type Parser is new Util.Serialize.IO.Parser with record -- The SAX locator to find the current file and line number. Locator : Sax.Locators.Locator; Has_Pending_Char : Boolean := False; Pending_Char : Character; -- Whether white spaces can be ignored. Ignore_White_Spaces : Boolean := True; -- Whether empty lines should be ignored (when white spaces are kept). Ignore_Empty_Lines : Boolean := True; end record; type Output_Stream is limited new Util.Serialize.IO.Output_Stream with record Close_Start : Boolean := False; Stream : Util.Streams.Texts.Print_Stream_Access; end record; end Util.Serialize.IO.XML;
----------------------------------------------------------------------- -- util-serialize-io-xml -- XML Serialization Driver -- Copyright (C) 2011, 2012, 2016, 2017 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Sax.Exceptions; with Sax.Locators; with Sax.Readers; with Sax.Attributes; with Unicode.CES; with Input_Sources; with Ada.Streams; with Ada.Strings.Unbounded; with Util.Streams.Buffered; with Util.Streams.Texts; package Util.Serialize.IO.XML is Parse_Error : exception; type Parser is new Serialize.IO.Parser with private; -- Parse the stream using the JSON parser. procedure Parse (Handler : in out Parser; Stream : in out Util.Streams.Buffered.Buffered_Stream'Class; Sink : in out Reader'Class); -- Set the XHTML reader to ignore or not the white spaces. -- When set to True, the ignorable white spaces will not be kept. procedure Set_Ignore_White_Spaces (Reader : in out Parser; Value : in Boolean); -- Set the XHTML reader to ignore empty lines. procedure Set_Ignore_Empty_Lines (Reader : in out Parser; Value : in Boolean); -- Get the current location (file and line) to report an error message. function Get_Location (Handler : in Parser) return String; type Xhtml_Reader is new Sax.Readers.Reader with private; -- ------------------------------ -- XML Output Stream -- ------------------------------ -- The <b>Output_Stream</b> provides methods for creating an XML output stream. -- The stream object takes care of the XML escape rules. type Output_Stream is limited new Util.Serialize.IO.Output_Stream with private; -- Set the target output stream. procedure Initialize (Stream : in out Output_Stream; Output : in Util.Streams.Texts.Print_Stream_Access); -- Flush the buffer (if any) to the sink. overriding procedure Flush (Stream : in out Output_Stream); -- Close the sink. overriding procedure Close (Stream : in out Output_Stream); -- Write the buffer array to the output stream. overriding procedure Write (Stream : in out Output_Stream; Buffer : in Ada.Streams.Stream_Element_Array); -- Write a raw character on the stream. procedure Write (Stream : in out Output_Stream; Char : in Character); -- Write a wide character on the stream doing some conversion if necessary. -- The default implementation translates the wide character to a UTF-8 sequence. procedure Write_Wide (Stream : in out Output_Stream; Item : in Wide_Wide_Character); -- Write a raw string on the stream. procedure Write (Stream : in out Output_Stream; Item : in String); -- Write a character on the response stream and escape that character as necessary. procedure Write_Escape (Stream : in out Output_Stream'Class; Char : in Wide_Wide_Character); -- Write the value as a XML string. Special characters are escaped using the XML -- escape rules. procedure Write_String (Stream : in out Output_Stream; Value : in String); -- Write the value as a XML string. Special characters are escaped using the XML -- escape rules. procedure Write_Wide_String (Stream : in out Output_Stream; Value : in Wide_Wide_String); -- Write the value as a XML string. Special characters are escaped using the XML -- escape rules. procedure Write_String (Stream : in out Output_Stream; Value : in Util.Beans.Objects.Object); -- Start a new XML object. procedure Start_Entity (Stream : in out Output_Stream; Name : in String); -- Terminates the current XML object. procedure End_Entity (Stream : in out Output_Stream; Name : in String); -- Write the attribute name/value pair. overriding procedure Write_Attribute (Stream : in out Output_Stream; Name : in String; Value : in String); overriding procedure Write_Wide_Attribute (Stream : in out Output_Stream; Name : in String; Value : in Wide_Wide_String); overriding procedure Write_Attribute (Stream : in out Output_Stream; Name : in String; Value : in Integer); overriding procedure Write_Attribute (Stream : in out Output_Stream; Name : in String; Value : in Boolean); -- Write a XML name/value attribute. procedure Write_Attribute (Stream : in out Output_Stream; Name : in String; Value : in Util.Beans.Objects.Object); -- Write the entity value. overriding procedure Write_Entity (Stream : in out Output_Stream; Name : in String; Value : in String); overriding procedure Write_Wide_Entity (Stream : in out Output_Stream; Name : in String; Value : in Wide_Wide_String); overriding procedure Write_Entity (Stream : in out Output_Stream; Name : in String; Value : in Boolean); overriding procedure Write_Entity (Stream : in out Output_Stream; Name : in String; Value : in Integer); overriding procedure Write_Entity (Stream : in out Output_Stream; Name : in String; Value : in Ada.Calendar.Time); overriding procedure Write_Long_Entity (Stream : in out Output_Stream; Name : in String; Value : in Long_Long_Integer); overriding procedure Write_Enum_Entity (Stream : in out Output_Stream; Name : in String; Value : in String); -- Write a XML name/value entity (see Write_Attribute). overriding procedure Write_Entity (Stream : in out Output_Stream; Name : in String; Value : in Util.Beans.Objects.Object); -- Starts a XML array. overriding procedure Start_Array (Stream : in out Output_Stream; Name : in String); -- Terminates a XML array. overriding procedure End_Array (Stream : in out Output_Stream; Name : in String); -- Return the location where the exception was raised. function Get_Location (Except : Sax.Exceptions.Sax_Parse_Exception'Class) return String; private overriding procedure Warning (Handler : in out Xhtml_Reader; Except : in Sax.Exceptions.Sax_Parse_Exception'Class); overriding procedure Error (Handler : in out Xhtml_Reader; Except : in Sax.Exceptions.Sax_Parse_Exception'Class); overriding procedure Fatal_Error (Handler : in out Xhtml_Reader; Except : in Sax.Exceptions.Sax_Parse_Exception'Class); overriding procedure Set_Document_Locator (Handler : in out Xhtml_Reader; Loc : in out Sax.Locators.Locator); overriding procedure Start_Document (Handler : in out Xhtml_Reader); overriding procedure End_Document (Handler : in out Xhtml_Reader); overriding procedure Start_Prefix_Mapping (Handler : in out Xhtml_Reader; Prefix : in Unicode.CES.Byte_Sequence; URI : in Unicode.CES.Byte_Sequence); overriding procedure End_Prefix_Mapping (Handler : in out Xhtml_Reader; Prefix : in Unicode.CES.Byte_Sequence); overriding procedure Start_Element (Handler : in out Xhtml_Reader; Namespace_URI : in Unicode.CES.Byte_Sequence := ""; Local_Name : in Unicode.CES.Byte_Sequence := ""; Qname : in Unicode.CES.Byte_Sequence := ""; Atts : in Sax.Attributes.Attributes'Class); overriding procedure End_Element (Handler : in out Xhtml_Reader; Namespace_URI : in Unicode.CES.Byte_Sequence := ""; Local_Name : in Unicode.CES.Byte_Sequence := ""; Qname : in Unicode.CES.Byte_Sequence := ""); overriding procedure Characters (Handler : in out Xhtml_Reader; Ch : in Unicode.CES.Byte_Sequence); overriding procedure Ignorable_Whitespace (Handler : in out Xhtml_Reader; Ch : in Unicode.CES.Byte_Sequence); overriding procedure Processing_Instruction (Handler : in out Xhtml_Reader; Target : in Unicode.CES.Byte_Sequence; Data : in Unicode.CES.Byte_Sequence); overriding procedure Skipped_Entity (Handler : in out Xhtml_Reader; Name : in Unicode.CES.Byte_Sequence); overriding procedure Start_Cdata (Handler : in out Xhtml_Reader); overriding procedure End_Cdata (Handler : in out Xhtml_Reader); overriding function Resolve_Entity (Handler : Xhtml_Reader; Public_Id : Unicode.CES.Byte_Sequence; System_Id : Unicode.CES.Byte_Sequence) return Input_Sources.Input_Source_Access; overriding procedure Start_DTD (Handler : in out Xhtml_Reader; Name : Unicode.CES.Byte_Sequence; Public_Id : Unicode.CES.Byte_Sequence := ""; System_Id : Unicode.CES.Byte_Sequence := ""); procedure Collect_Text (Handler : in out Xhtml_Reader; Content : Unicode.CES.Byte_Sequence); type Xhtml_Reader is new Sax.Readers.Reader with record Stack_Pos : Natural := 0; Handler : access Parser'Class; Text : Ada.Strings.Unbounded.Unbounded_String; -- Whether white spaces can be ignored. Ignore_White_Spaces : Boolean := True; -- Whether empty lines should be ignored (when white spaces are kept). Ignore_Empty_Lines : Boolean := True; Sink : access Reader'Class; end record; type Parser is new Util.Serialize.IO.Parser with record -- The SAX locator to find the current file and line number. Locator : Sax.Locators.Locator; Has_Pending_Char : Boolean := False; Pending_Char : Character; -- Whether white spaces can be ignored. Ignore_White_Spaces : Boolean := True; -- Whether empty lines should be ignored (when white spaces are kept). Ignore_Empty_Lines : Boolean := True; end record; type Output_Stream is limited new Util.Serialize.IO.Output_Stream with record Close_Start : Boolean := False; Stream : Util.Streams.Texts.Print_Stream_Access; end record; end Util.Serialize.IO.XML;
Add a Sink parameter to the Parse procedure
Add a Sink parameter to the Parse procedure
Ada
apache-2.0
stcarrez/ada-util,stcarrez/ada-util
6e15775d0e6f6b8fc7dcbe414b2a01707c0508a1
src/asf-factory.ads
src/asf-factory.ads
----------------------------------------------------------------------- -- asf-factory -- Component and tag factory -- Copyright (C) 2009, 2010, 2011, 2012, 2013 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with ASF.Views.Nodes; with ASF.Converters; with ASF.Validators; with EL.Objects; private with Util.Beans.Objects.Hash; private with Ada.Containers; private with Ada.Containers.Hashed_Maps; -- The <b>ASF.Factory</b> is the main factory for building the facelet -- node tree and defining associated component factory. A binding library -- must be registered before the application starts. The binding library -- must not be changed (this is a read-only static definition of names -- associated with create functions). package ASF.Factory is use ASF; -- ------------------------------ -- List of bindings -- ------------------------------ -- The binding array defines a set of XML entity names that represent -- a library accessible through a XML name-space. The binding array -- must be sorted on the binding name. The <b>Check</b> procedure will -- verify this assumption when the bindings are registered in the factory. type Binding_Array is array (Natural range <>) of aliased ASF.Views.Nodes.Binding; type Binding_Array_Access is access constant Binding_Array; type Factory_Bindings is limited record URI : ASF.Views.Nodes.Name_Access; Bindings : Binding_Array_Access; end record; type Factory_Bindings_Access is access constant Factory_Bindings; -- ------------------------------ -- Component Factory -- ------------------------------ -- The <b>Component_Factory</b> is the main entry point to register bindings -- and resolve them when an XML file is read. type Component_Factory is limited private; -- Register a binding library in the factory. procedure Register (Factory : in out Component_Factory; Bindings : in Factory_Bindings_Access); -- Find the create function in bound to the name in the given URI name-space. -- Returns null if no such binding exist. function Find (Factory : in Component_Factory; URI : in String; Name : in String) return ASF.Views.Nodes.Binding_Access; -- ------------------------------ -- Converter Factory -- ------------------------------ -- The <b>Converter_Factory</b> registers the converters which can be used -- to convert a value into a string or the opposite. -- Register the converter instance under the given name. procedure Register (Factory : in out Component_Factory; Name : in String; Converter : in ASF.Converters.Converter_Access); -- Find the converter instance that was registered under the given name. -- Returns null if no such converter exist. function Find (Factory : in Component_Factory; Name : in EL.Objects.Object) return ASF.Converters.Converter_Access; -- ------------------------------ -- Validator Factory -- ------------------------------ -- Register the validator instance under the given name. procedure Register (Factory : in out Component_Factory; Name : in String; Validator : in ASF.Validators.Validator_Access); -- Find the validator instance that was registered under the given name. -- Returns null if no such validator exist. function Find (Factory : in Component_Factory; Name : in EL.Objects.Object) return ASF.Validators.Validator_Access; private use ASF.Converters; use ASF.Validators; use ASF.Views.Nodes; -- The tag name defines a URI with the name. type Tag_Name is record URI : ASF.Views.Nodes.Name_Access; Name : ASF.Views.Nodes.Name_Access; end record; -- Compute a hash for the tag name. function Hash (Key : in Tag_Name) return Ada.Containers.Hash_Type; -- Returns true if both tag names are identical. function "=" (Left, Right : in Tag_Name) return Boolean; -- Tag library map indexed on the library namespace. package Factory_Maps is new Ada.Containers.Hashed_Maps (Key_Type => Tag_Name, Element_Type => Binding_Access, Hash => Hash, Equivalent_Keys => "="); -- Converter map indexed on the converter name. -- The key is an EL.Objects.Object to minimize the conversions when searching -- for a converter. package Converter_Maps is new Ada.Containers.Hashed_Maps (Key_Type => EL.Objects.Object, Element_Type => Converter_Access, Hash => EL.Objects.Hash, Equivalent_Keys => EL.Objects."="); -- Validator map indexed on the validator name. -- The key is an EL.Objects.Object to minimize the conversions when searching -- for a validator. package Validator_Maps is new Ada.Containers.Hashed_Maps (Key_Type => EL.Objects.Object, Element_Type => Validator_Access, Hash => EL.Objects.Hash, Equivalent_Keys => EL.Objects."="); type Component_Factory is limited record Map : Factory_Maps.Map; Converters : Converter_Maps.Map; Validators : Validator_Maps.Map; end record; end ASF.Factory;
----------------------------------------------------------------------- -- asf-factory -- Component and tag factory -- Copyright (C) 2009, 2010, 2011, 2012, 2013, 2018 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with ASF.Views.Nodes; with ASF.Converters; with ASF.Validators; with EL.Objects; private with Util.Beans.Objects.Hash; private with Ada.Containers; private with Ada.Containers.Hashed_Maps; -- The <b>ASF.Factory</b> is the main factory for building the facelet -- node tree and defining associated component factory. A binding library -- must be registered before the application starts. The binding library -- must not be changed (this is a read-only static definition of names -- associated with create functions). package ASF.Factory is -- ------------------------------ -- List of bindings -- ------------------------------ -- The binding array defines a set of XML entity names that represent -- a library accessible through a XML name-space. The binding array -- must be sorted on the binding name. The <b>Check</b> procedure will -- verify this assumption when the bindings are registered in the factory. type Binding_Array is array (Natural range <>) of aliased ASF.Views.Nodes.Binding_Type; type Binding_Array_Access is access constant Binding_Array; type Factory_Bindings is limited record URI : ASF.Views.Nodes.Name_Access; Bindings : Binding_Array_Access; end record; type Factory_Bindings_Access is access constant Factory_Bindings; -- ------------------------------ -- Component Factory -- ------------------------------ -- The <b>Component_Factory</b> is the main entry point to register bindings -- and resolve them when an XML file is read. type Component_Factory is limited private; -- Register a binding library in the factory. procedure Register (Factory : in out Component_Factory; Bindings : in Factory_Bindings_Access); procedure Register (Factory : in out Component_Factory; URI : in ASF.Views.Nodes.Name_Access; Name : in ASF.Views.Nodes.Name_Access; Tag : in ASF.Views.Nodes.Tag_Node_Create_Access; Create : in ASF.Views.Nodes.Create_Access); -- Find the create function in bound to the name in the given URI name-space. -- Returns null if no such binding exist. function Find (Factory : in Component_Factory; URI : in String; Name : in String) return ASF.Views.Nodes.Binding_Type; -- ------------------------------ -- Converter Factory -- ------------------------------ -- The <b>Converter_Factory</b> registers the converters which can be used -- to convert a value into a string or the opposite. -- Register the converter instance under the given name. procedure Register (Factory : in out Component_Factory; Name : in String; Converter : in ASF.Converters.Converter_Access); -- Find the converter instance that was registered under the given name. -- Returns null if no such converter exist. function Find (Factory : in Component_Factory; Name : in EL.Objects.Object) return ASF.Converters.Converter_Access; -- ------------------------------ -- Validator Factory -- ------------------------------ -- Register the validator instance under the given name. procedure Register (Factory : in out Component_Factory; Name : in String; Validator : in ASF.Validators.Validator_Access); -- Find the validator instance that was registered under the given name. -- Returns null if no such validator exist. function Find (Factory : in Component_Factory; Name : in EL.Objects.Object) return ASF.Validators.Validator_Access; private use ASF.Converters; use ASF.Validators; use ASF.Views.Nodes; -- The tag name defines a URI with the name. type Tag_Name is record URI : ASF.Views.Nodes.Name_Access; Name : ASF.Views.Nodes.Name_Access; end record; -- Compute a hash for the tag name. function Hash (Key : in Tag_Name) return Ada.Containers.Hash_Type; -- Returns true if both tag names are identical. function "=" (Left, Right : in Tag_Name) return Boolean; -- Tag library map indexed on the library namespace. package Factory_Maps is new Ada.Containers.Hashed_Maps (Key_Type => Tag_Name, Element_Type => Binding_Type, Hash => Hash, Equivalent_Keys => "="); -- Converter map indexed on the converter name. -- The key is an EL.Objects.Object to minimize the conversions when searching -- for a converter. package Converter_Maps is new Ada.Containers.Hashed_Maps (Key_Type => EL.Objects.Object, Element_Type => Converter_Access, Hash => EL.Objects.Hash, Equivalent_Keys => EL.Objects."="); -- Validator map indexed on the validator name. -- The key is an EL.Objects.Object to minimize the conversions when searching -- for a validator. package Validator_Maps is new Ada.Containers.Hashed_Maps (Key_Type => EL.Objects.Object, Element_Type => Validator_Access, Hash => EL.Objects.Hash, Equivalent_Keys => EL.Objects."="); type Component_Factory is limited record Map : Factory_Maps.Map; Converters : Converter_Maps.Map; Validators : Validator_Maps.Map; end record; end ASF.Factory;
Update the factory to use the Binding_Type instead of the Binding_Access Declare a Register procedure to register a single binding instance
Update the factory to use the Binding_Type instead of the Binding_Access Declare a Register procedure to register a single binding instance
Ada
apache-2.0
stcarrez/ada-asf,stcarrez/ada-asf,stcarrez/ada-asf
699f8ec28fa40cb7286d387f9ece159f173f8b5e
src/asf-components-html-factory.adb
src/asf-components-html-factory.adb
----------------------------------------------------------------------- -- html-factory -- Factory for HTML UI Components -- Copyright (C) 2009, 2010, 2011, 2012, 2014, 2018 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with ASF.Components.Base; with ASF.Components.Html.Text; with ASF.Components.Html.Lists; with ASF.Components.Html.Links; with ASF.Components.Html.Panels; with ASF.Components.Html.Forms; with ASF.Components.Html.Pages; with ASF.Components.Html.Selects; with ASF.Components.Html.Messages; with ASF.Views.Nodes; package body ASF.Components.Html.Factory is use ASF.Components.Base; function Create_Body return UIComponent_Access; function Create_Doctype return UIComponent_Access; function Create_Head return UIComponent_Access; function Create_Output return UIComponent_Access; function Create_Output_Label return UIComponent_Access; function Create_Output_Link return UIComponent_Access; function Create_Output_Format return UIComponent_Access; function Create_List return UIComponent_Access; function Create_PanelGroup return UIComponent_Access; function Create_Form return UIComponent_Access; function Create_Input_File return UIComponent_Access; function Create_Input_Hidden return UIComponent_Access; function Create_Input_Text return UIComponent_Access; function Create_Input_Textarea return UIComponent_Access; function Create_Command return UIComponent_Access; function Create_Message return UIComponent_Access; function Create_Messages return UIComponent_Access; function Create_SelectOne return UIComponent_Access; function Create_SelectOneRadio return UIComponent_Access; function Create_SelectBooleanCheckbox return UIComponent_Access; -- Create an UIInput secret component function Create_Input_Secret return ASF.Components.Base.UIComponent_Access; -- ------------------------------ -- Create an UIBody component -- ------------------------------ function Create_Body return UIComponent_Access is begin return new ASF.Components.Html.Pages.UIBody; end Create_Body; -- ------------------------------ -- Create an UIDoctype component -- ------------------------------ function Create_Doctype return UIComponent_Access is begin return new ASF.Components.Html.Pages.UIDoctype; end Create_Doctype; -- ------------------------------ -- Create an UIHead component -- ------------------------------ function Create_Head return UIComponent_Access is begin return new ASF.Components.Html.Pages.UIHead; end Create_Head; -- ------------------------------ -- Create an UIOutput component -- ------------------------------ function Create_Output return UIComponent_Access is begin return new ASF.Components.Html.Text.UIOutput; end Create_Output; -- ------------------------------ -- Create an UIOutputLabel component -- ------------------------------ function Create_Output_Label return UIComponent_Access is begin return new ASF.Components.Html.Text.UIOutputLabel; end Create_Output_Label; -- ------------------------------ -- Create an UIOutputLink component -- ------------------------------ function Create_Output_Link return UIComponent_Access is begin return new ASF.Components.Html.Links.UIOutputLink; end Create_Output_Link; -- ------------------------------ -- Create an UIOutput component -- ------------------------------ function Create_Output_Format return UIComponent_Access is begin return new ASF.Components.Html.Text.UIOutputFormat; end Create_Output_Format; -- ------------------------------ -- Create an UIList component -- ------------------------------ function Create_List return UIComponent_Access is begin return new ASF.Components.Html.Lists.UIList; end Create_List; -- ------------------------------ -- Create an UIPanelGroup component -- ------------------------------ function Create_PanelGroup return UIComponent_Access is begin return new ASF.Components.Html.Panels.UIPanelGroup; end Create_PanelGroup; -- ------------------------------ -- Create an UIForm component -- ------------------------------ function Create_Form return UIComponent_Access is begin return new ASF.Components.Html.Forms.UIForm; end Create_Form; -- ------------------------------ -- Create an UIInput_Hidden component -- ------------------------------ function Create_Input_Hidden return UIComponent_Access is begin return new ASF.Components.Html.Forms.UIInput_Hidden; end Create_Input_Hidden; -- ------------------------------ -- Create an UIInput component -- ------------------------------ function Create_Input_Text return UIComponent_Access is begin return new ASF.Components.Html.Forms.UIInput; end Create_Input_Text; -- ------------------------------ -- Create an UIInput secret component -- ------------------------------ function Create_Input_Secret return ASF.Components.Base.UIComponent_Access is Result : constant Html.Forms.UIInput_Access := new ASF.Components.Html.Forms.UIInput; begin Result.Set_Secret (True); return Result.all'Access; end Create_Input_Secret; -- ------------------------------ -- Create an UIInputTextarea component -- ------------------------------ function Create_Input_Textarea return UIComponent_Access is begin return new ASF.Components.Html.Forms.UIInputTextarea; end Create_Input_Textarea; -- ------------------------------ -- Create an UIInput_File component -- ------------------------------ function Create_Input_File return UIComponent_Access is begin return new ASF.Components.Html.Forms.UIInput_File; end Create_Input_File; -- ------------------------------ -- Create an UICommand component -- ------------------------------ function Create_Command return UIComponent_Access is begin return new ASF.Components.Html.Forms.UICommand; end Create_Command; -- ------------------------------ -- Create an UIMessage component -- ------------------------------ function Create_Message return UIComponent_Access is begin return new ASF.Components.Html.Messages.UIMessage; end Create_Message; -- ------------------------------ -- Create an UIMessages component -- ------------------------------ function Create_Messages return UIComponent_Access is begin return new ASF.Components.Html.Messages.UIMessages; end Create_Messages; -- ------------------------------ -- Create an UISelectOne component -- ------------------------------ function Create_SelectOne return UIComponent_Access is begin return new ASF.Components.Html.Selects.UISelectOne; end Create_SelectOne; -- ------------------------------ -- Create an UISelectOneRadio component -- ------------------------------ function Create_SelectOneRadio return UIComponent_Access is begin return new ASF.Components.Html.Selects.UISelectOneRadio; end Create_SelectOneRadio; -- ------------------------------ -- Create an UISelectBoolean component -- ------------------------------ function Create_SelectBooleanCheckbox return UIComponent_Access is begin return new ASF.Components.Html.Selects.UISelectBoolean; end Create_SelectBooleanCheckbox; use ASF.Views.Nodes; URI : aliased constant String := "http://java.sun.com/jsf/html"; BODY_TAG : aliased constant String := "body"; COMMAND_BUTTON_TAG : aliased constant String := "commandButton"; DOCTYPE_TAG : aliased constant String := "doctype"; FORM_TAG : aliased constant String := "form"; HEAD_TAG : aliased constant String := "head"; INPUT_FILE_TAG : aliased constant String := "inputFile"; INPUT_HIDDEN_TAG : aliased constant String := "inputHidden"; INPUT_SECRET_TAG : aliased constant String := "inputSecret"; INPUT_TEXT_TAG : aliased constant String := "inputText"; INPUT_TEXTAREA_TAG : aliased constant String := "inputTextarea"; LIST_TAG : aliased constant String := "list"; MESSAGE_TAG : aliased constant String := "message"; MESSAGES_TAG : aliased constant String := "messages"; OUTPUT_FORMAT_TAG : aliased constant String := "outputFormat"; OUTPUT_LABEL_TAG : aliased constant String := "outputLabel"; OUTPUT_LINK_TAG : aliased constant String := "outputLink"; OUTPUT_TEXT_TAG : aliased constant String := "outputText"; PANEL_GROUP_TAG : aliased constant String := "panelGroup"; SELECT_BOOLEAN_TAG : aliased constant String := "selectBooleanCheckbox"; SELECT_ONE_MENU_TAG : aliased constant String := "selectOneMenu"; SELECT_ONE_RADIO_TAG : aliased constant String := "selectOneRadio"; -- ------------------------------ -- Get the HTML component factory. -- ------------------------------ procedure Register (Factory : in out ASF.Factory.Component_Factory) is begin ASF.Factory.Register (Factory, URI => URI'Access, Name => BODY_TAG'Access, Tag => Create_Component_Node'Access, Create => Create_Body'Access); ASF.Factory.Register (Factory, URI => URI'Access, Name => COMMAND_BUTTON_TAG'Access, Tag => Create_Component_Node'Access, Create => Create_Command'Access); ASF.Factory.Register (Factory, URI => URI'Access, Name => DOCTYPE_TAG'Access, Tag => Create_Component_Node'Access, Create => Create_Doctype'Access); ASF.Factory.Register (Factory, URI => URI'Access, Name => FORM_TAG'Access, Tag => Create_Component_Node'Access, Create => Create_Form'Access); ASF.Factory.Register (Factory, URI => URI'Access, Name => HEAD_TAG'Access, Tag => Create_Component_Node'Access, Create => Create_Head'Access); ASF.Factory.Register (Factory, URI => URI'Access, Name => INPUT_FILE_TAG'Access, Tag => Create_Component_Node'Access, Create => Create_Input_File'Access); ASF.Factory.Register (Factory, URI => URI'Access, Name => INPUT_HIDDEN_TAG'Access, Tag => Create_Component_Node'Access, Create => Create_Input_Hidden'Access); ASF.Factory.Register (Factory, URI => URI'Access, Name => INPUT_SECRET_TAG'Access, Tag => Create_Component_Node'Access, Create => Create_Input_Secret'Access); ASF.Factory.Register (Factory, URI => URI'Access, Name => INPUT_TEXT_TAG'Access, Tag => Create_Component_Node'Access, Create => Create_Input_Text'Access); ASF.Factory.Register (Factory, URI => URI'Access, Name => INPUT_TEXTAREA_TAG'Access, Tag => Create_Component_Node'Access, Create => Create_Input_Textarea'Access); ASF.Factory.Register (Factory, URI => URI'Access, Name => LIST_TAG'Access, Tag => Create_Component_Node'Access, Create => Create_List'Access); ASF.Factory.Register (Factory, URI => URI'Access, Name => MESSAGE_TAG'Access, Tag => Create_Component_Node'Access, Create => Create_Message'Access); ASF.Factory.Register (Factory, URI => URI'Access, Name => MESSAGES_TAG'Access, Tag => Create_Component_Node'Access, Create => Create_Messages'Access); ASF.Factory.Register (Factory, URI => URI'Access, Name => OUTPUT_FORMAT_TAG'Access, Tag => Create_Component_Node'Access, Create => Create_Output_Format'Access); ASF.Factory.Register (Factory, URI => URI'Access, Name => OUTPUT_LABEL_TAG'Access, Tag => Create_Component_Node'Access, Create => Create_Output_Label'Access); ASF.Factory.Register (Factory, URI => URI'Access, Name => OUTPUT_LINK_TAG'Access, Tag => Create_Component_Node'Access, Create => Create_Output_Link'Access); ASF.Factory.Register (Factory, URI => URI'Access, Name => OUTPUT_TEXT_TAG'Access, Tag => Create_Component_Node'Access, Create => Create_Output'Access); ASF.Factory.Register (Factory, URI => URI'Access, Name => PANEL_GROUP_TAG'Access, Tag => Create_Component_Node'Access, Create => Create_PanelGroup'Access); ASF.Factory.Register (Factory, URI => URI'Access, Name => SELECT_BOOLEAN_TAG'Access, Tag => Create_Component_Node'Access, Create => Create_SelectBooleanCheckbox'Access); ASF.Factory.Register (Factory, URI => URI'Access, Name => SELECT_ONE_MENU_TAG'Access, Tag => Create_Component_Node'Access, Create => Create_SelectOne'Access); ASF.Factory.Register (Factory, URI => URI'Access, Name => SELECT_ONE_RADIO_TAG'Access, Tag => Create_Component_Node'Access, Create => Create_SelectOneRadio'Access); end Register; end ASF.Components.Html.Factory;
----------------------------------------------------------------------- -- html-factory -- Factory for HTML UI Components -- Copyright (C) 2009, 2010, 2011, 2012, 2014, 2018, 2019 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with ASF.Components.Base; with ASF.Components.Html.Text; with ASF.Components.Html.Lists; with ASF.Components.Html.Links; with ASF.Components.Html.Panels; with ASF.Components.Html.Forms; with ASF.Components.Html.Pages; with ASF.Components.Html.Selects; with ASF.Components.Html.Messages; with ASF.Views.Nodes; package body ASF.Components.Html.Factory is use ASF.Components.Base; function Create_Body return UIComponent_Access; function Create_Doctype return UIComponent_Access; function Create_Head return UIComponent_Access; function Create_Output_Stylesheet return UIComponent_Access; function Create_Output return UIComponent_Access; function Create_Output_Label return UIComponent_Access; function Create_Output_Link return UIComponent_Access; function Create_Output_Format return UIComponent_Access; function Create_List return UIComponent_Access; function Create_PanelGroup return UIComponent_Access; function Create_Form return UIComponent_Access; function Create_Input_File return UIComponent_Access; function Create_Input_Hidden return UIComponent_Access; function Create_Input_Text return UIComponent_Access; function Create_Input_Textarea return UIComponent_Access; function Create_Command return UIComponent_Access; function Create_Message return UIComponent_Access; function Create_Messages return UIComponent_Access; function Create_SelectOne return UIComponent_Access; function Create_SelectOneRadio return UIComponent_Access; function Create_SelectBooleanCheckbox return UIComponent_Access; -- Create an UIInput secret component function Create_Input_Secret return ASF.Components.Base.UIComponent_Access; -- ------------------------------ -- Create an UIBody component -- ------------------------------ function Create_Body return UIComponent_Access is begin return new ASF.Components.Html.Pages.UIBody; end Create_Body; -- ------------------------------ -- Create an UIDoctype component -- ------------------------------ function Create_Doctype return UIComponent_Access is begin return new ASF.Components.Html.Pages.UIDoctype; end Create_Doctype; -- ------------------------------ -- Create an UIHead component -- ------------------------------ function Create_Head return UIComponent_Access is begin return new ASF.Components.Html.Pages.UIHead; end Create_Head; -- ------------------------------ -- Create an UIOutputStylesheet component -- ------------------------------ function Create_Output_Stylesheet return UIComponent_Access is begin return new ASF.Components.Html.Pages.UIOutputStylesheet; end Create_Output_Stylesheet; -- ------------------------------ -- Create an UIOutput component -- ------------------------------ function Create_Output return UIComponent_Access is begin return new ASF.Components.Html.Text.UIOutput; end Create_Output; -- ------------------------------ -- Create an UIOutputLabel component -- ------------------------------ function Create_Output_Label return UIComponent_Access is begin return new ASF.Components.Html.Text.UIOutputLabel; end Create_Output_Label; -- ------------------------------ -- Create an UIOutputLink component -- ------------------------------ function Create_Output_Link return UIComponent_Access is begin return new ASF.Components.Html.Links.UIOutputLink; end Create_Output_Link; -- ------------------------------ -- Create an UIOutput component -- ------------------------------ function Create_Output_Format return UIComponent_Access is begin return new ASF.Components.Html.Text.UIOutputFormat; end Create_Output_Format; -- ------------------------------ -- Create an UIList component -- ------------------------------ function Create_List return UIComponent_Access is begin return new ASF.Components.Html.Lists.UIList; end Create_List; -- ------------------------------ -- Create an UIPanelGroup component -- ------------------------------ function Create_PanelGroup return UIComponent_Access is begin return new ASF.Components.Html.Panels.UIPanelGroup; end Create_PanelGroup; -- ------------------------------ -- Create an UIForm component -- ------------------------------ function Create_Form return UIComponent_Access is begin return new ASF.Components.Html.Forms.UIForm; end Create_Form; -- ------------------------------ -- Create an UIInput_Hidden component -- ------------------------------ function Create_Input_Hidden return UIComponent_Access is begin return new ASF.Components.Html.Forms.UIInput_Hidden; end Create_Input_Hidden; -- ------------------------------ -- Create an UIInput component -- ------------------------------ function Create_Input_Text return UIComponent_Access is begin return new ASF.Components.Html.Forms.UIInput; end Create_Input_Text; -- ------------------------------ -- Create an UIInput secret component -- ------------------------------ function Create_Input_Secret return ASF.Components.Base.UIComponent_Access is Result : constant Html.Forms.UIInput_Access := new ASF.Components.Html.Forms.UIInput; begin Result.Set_Secret (True); return Result.all'Access; end Create_Input_Secret; -- ------------------------------ -- Create an UIInputTextarea component -- ------------------------------ function Create_Input_Textarea return UIComponent_Access is begin return new ASF.Components.Html.Forms.UIInputTextarea; end Create_Input_Textarea; -- ------------------------------ -- Create an UIInput_File component -- ------------------------------ function Create_Input_File return UIComponent_Access is begin return new ASF.Components.Html.Forms.UIInput_File; end Create_Input_File; -- ------------------------------ -- Create an UICommand component -- ------------------------------ function Create_Command return UIComponent_Access is begin return new ASF.Components.Html.Forms.UICommand; end Create_Command; -- ------------------------------ -- Create an UIMessage component -- ------------------------------ function Create_Message return UIComponent_Access is begin return new ASF.Components.Html.Messages.UIMessage; end Create_Message; -- ------------------------------ -- Create an UIMessages component -- ------------------------------ function Create_Messages return UIComponent_Access is begin return new ASF.Components.Html.Messages.UIMessages; end Create_Messages; -- ------------------------------ -- Create an UISelectOne component -- ------------------------------ function Create_SelectOne return UIComponent_Access is begin return new ASF.Components.Html.Selects.UISelectOne; end Create_SelectOne; -- ------------------------------ -- Create an UISelectOneRadio component -- ------------------------------ function Create_SelectOneRadio return UIComponent_Access is begin return new ASF.Components.Html.Selects.UISelectOneRadio; end Create_SelectOneRadio; -- ------------------------------ -- Create an UISelectBoolean component -- ------------------------------ function Create_SelectBooleanCheckbox return UIComponent_Access is begin return new ASF.Components.Html.Selects.UISelectBoolean; end Create_SelectBooleanCheckbox; use ASF.Views.Nodes; URI : aliased constant String := "http://java.sun.com/jsf/html"; BODY_TAG : aliased constant String := "body"; COMMAND_BUTTON_TAG : aliased constant String := "commandButton"; DOCTYPE_TAG : aliased constant String := "doctype"; FORM_TAG : aliased constant String := "form"; HEAD_TAG : aliased constant String := "head"; INPUT_FILE_TAG : aliased constant String := "inputFile"; INPUT_HIDDEN_TAG : aliased constant String := "inputHidden"; INPUT_SECRET_TAG : aliased constant String := "inputSecret"; INPUT_TEXT_TAG : aliased constant String := "inputText"; INPUT_TEXTAREA_TAG : aliased constant String := "inputTextarea"; LIST_TAG : aliased constant String := "list"; MESSAGE_TAG : aliased constant String := "message"; MESSAGES_TAG : aliased constant String := "messages"; OUTPUT_FORMAT_TAG : aliased constant String := "outputFormat"; OUTPUT_LABEL_TAG : aliased constant String := "outputLabel"; OUTPUT_LINK_TAG : aliased constant String := "outputLink"; OUTPUT_STYLESHEET_TAG : aliased constant String := "outputStylesheet"; OUTPUT_TEXT_TAG : aliased constant String := "outputText"; PANEL_GROUP_TAG : aliased constant String := "panelGroup"; SELECT_BOOLEAN_TAG : aliased constant String := "selectBooleanCheckbox"; SELECT_ONE_MENU_TAG : aliased constant String := "selectOneMenu"; SELECT_ONE_RADIO_TAG : aliased constant String := "selectOneRadio"; -- ------------------------------ -- Get the HTML component factory. -- ------------------------------ procedure Register (Factory : in out ASF.Factory.Component_Factory) is begin ASF.Factory.Register (Factory, URI => URI'Access, Name => BODY_TAG'Access, Tag => Create_Component_Node'Access, Create => Create_Body'Access); ASF.Factory.Register (Factory, URI => URI'Access, Name => COMMAND_BUTTON_TAG'Access, Tag => Create_Component_Node'Access, Create => Create_Command'Access); ASF.Factory.Register (Factory, URI => URI'Access, Name => DOCTYPE_TAG'Access, Tag => Create_Component_Node'Access, Create => Create_Doctype'Access); ASF.Factory.Register (Factory, URI => URI'Access, Name => FORM_TAG'Access, Tag => Create_Component_Node'Access, Create => Create_Form'Access); ASF.Factory.Register (Factory, URI => URI'Access, Name => HEAD_TAG'Access, Tag => Create_Component_Node'Access, Create => Create_Head'Access); ASF.Factory.Register (Factory, URI => URI'Access, Name => INPUT_FILE_TAG'Access, Tag => Create_Component_Node'Access, Create => Create_Input_File'Access); ASF.Factory.Register (Factory, URI => URI'Access, Name => INPUT_HIDDEN_TAG'Access, Tag => Create_Component_Node'Access, Create => Create_Input_Hidden'Access); ASF.Factory.Register (Factory, URI => URI'Access, Name => INPUT_SECRET_TAG'Access, Tag => Create_Component_Node'Access, Create => Create_Input_Secret'Access); ASF.Factory.Register (Factory, URI => URI'Access, Name => INPUT_TEXT_TAG'Access, Tag => Create_Component_Node'Access, Create => Create_Input_Text'Access); ASF.Factory.Register (Factory, URI => URI'Access, Name => INPUT_TEXTAREA_TAG'Access, Tag => Create_Component_Node'Access, Create => Create_Input_Textarea'Access); ASF.Factory.Register (Factory, URI => URI'Access, Name => LIST_TAG'Access, Tag => Create_Component_Node'Access, Create => Create_List'Access); ASF.Factory.Register (Factory, URI => URI'Access, Name => MESSAGE_TAG'Access, Tag => Create_Component_Node'Access, Create => Create_Message'Access); ASF.Factory.Register (Factory, URI => URI'Access, Name => MESSAGES_TAG'Access, Tag => Create_Component_Node'Access, Create => Create_Messages'Access); ASF.Factory.Register (Factory, URI => URI'Access, Name => OUTPUT_FORMAT_TAG'Access, Tag => Create_Component_Node'Access, Create => Create_Output_Format'Access); ASF.Factory.Register (Factory, URI => URI'Access, Name => OUTPUT_LABEL_TAG'Access, Tag => Create_Component_Node'Access, Create => Create_Output_Label'Access); ASF.Factory.Register (Factory, URI => URI'Access, Name => OUTPUT_LINK_TAG'Access, Tag => Create_Component_Node'Access, Create => Create_Output_Link'Access); ASF.Factory.Register (Factory, URI => URI'Access, Name => OUTPUT_STYLESHEET_TAG'Access, Tag => Create_Component_Node'Access, Create => Create_Output_Stylesheet'Access); ASF.Factory.Register (Factory, URI => URI'Access, Name => OUTPUT_TEXT_TAG'Access, Tag => Create_Component_Node'Access, Create => Create_Output'Access); ASF.Factory.Register (Factory, URI => URI'Access, Name => PANEL_GROUP_TAG'Access, Tag => Create_Component_Node'Access, Create => Create_PanelGroup'Access); ASF.Factory.Register (Factory, URI => URI'Access, Name => SELECT_BOOLEAN_TAG'Access, Tag => Create_Component_Node'Access, Create => Create_SelectBooleanCheckbox'Access); ASF.Factory.Register (Factory, URI => URI'Access, Name => SELECT_ONE_MENU_TAG'Access, Tag => Create_Component_Node'Access, Create => Create_SelectOne'Access); ASF.Factory.Register (Factory, URI => URI'Access, Name => SELECT_ONE_RADIO_TAG'Access, Tag => Create_Component_Node'Access, Create => Create_SelectOneRadio'Access); end Register; end ASF.Components.Html.Factory;
Declare and register the <h:outputStylesheet> component
Declare and register the <h:outputStylesheet> component
Ada
apache-2.0
stcarrez/ada-asf,stcarrez/ada-asf,stcarrez/ada-asf
95e25ce267db5db113f5812c2c8eae6a94b3577b
awa/plugins/awa-comments/regtests/awa-comments-modules-tests.adb
awa/plugins/awa-comments/regtests/awa-comments-modules-tests.adb
----------------------------------------------------------------------- -- awa-comments-modules-tests -- Unit tests for comments module -- Copyright (C) 2014 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Strings.Unbounded; with Util.Test_Caller; with Util.Beans.Basic; with Util.Beans.Objects; with Security.Contexts; with ADO.Utils; with AWA.Users.Models; with AWA.Services.Contexts; with AWA.Tests.Helpers.Users; with AWA.Comments.Beans; package body AWA.Comments.Modules.Tests is use Util.Tests; use ADO; package Caller is new Util.Test_Caller (Test, "Comments.Modules"); -- -- function Create_Tag_List_Bean (Module : in Tag_Module_Access) -- return AWA.Tags.Beans.Tag_List_Bean_Access; procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is begin Caller.Add_Test (Suite, "Test AWA.Comments.Modules.Create_Comment (PUBLISHED)", Test_Create_Published_Comment'Access); Caller.Add_Test (Suite, "Test AWA.Comments.Modules.Create_Comment (WAITING)", Test_Create_Waiting_Comment'Access); Caller.Add_Test (Suite, "Test AWA.Comments.Modules.Delete_Comment", Test_Remove_Comment'Access); Caller.Add_Test (Suite, "Test AWA.Comments.Modules.Update_Comment (publish)", Test_Publish_Comment'Access); end Add_Tests; function Get_Count (Bean : in Util.Beans.Objects.Object) return Natural is Value : constant Util.Beans.Objects.Object := Util.Beans.Objects.Get_Value (Bean, "count"); begin return Util.Beans.Objects.To_Integer (Value); end Get_Count; procedure List_Comments (T : in out Test; User : in ADO.Identifier; Into : out Util.Beans.Objects.Object) is Comment_Manager : constant Comment_Module_Access := Get_Comment_Module; Bean : Util.Beans.Basic.Readonly_Bean_Access; List : AWA.Comments.Beans.Comment_List_Bean_Access; begin Bean := Beans.Create_Comment_List_Bean (Comment_Manager); Into := Util.Beans.Objects.To_Object (Bean.all'Access); List := AWA.Comments.Beans.Comment_List_Bean'Class (Bean.all)'Access; List.Set_Value ("entity_type", Util.Beans.Objects.To_Object (String '("awa_user"))); Util.Tests.Assert_Equals (T, 0, Integer (List.Get_Count), "Invalid number of comments"); -- Load the existing comments. List.Load_Comments (User); end List_Comments; -- ------------------------------ -- Create a comment and return the list of comments before and after the creation. -- ------------------------------ procedure Create_Comment (T : in out Test; Status : in AWA.Comments.Models.Status_Type; Before : out Util.Beans.Objects.Object; After : out Util.Beans.Objects.Object; Id : out ADO.Identifier) is Sec_Ctx : Security.Contexts.Security_Context; Context : AWA.Services.Contexts.Service_Context; begin AWA.Tests.Helpers.Users.Login (Context, Sec_Ctx, "[email protected]"); declare Comment_Manager : constant Comment_Module_Access := Get_Comment_Module; User : constant AWA.Users.Models.User_Ref := Context.Get_User; Bean : Util.Beans.Basic.Readonly_Bean_Access; Comment : AWA.Comments.Beans.Comment_Bean_Access; Cleanup : Util.Beans.Objects.Object; Outcome : Ada.Strings.Unbounded.Unbounded_String; begin T.Assert (Comment_Manager /= null, "There is no comment module"); T.List_Comments (User.Get_Id, Before); -- Create a new comment associated with the current user. Bean := Beans.Create_Comment_Bean (Comment_Manager); Cleanup := Util.Beans.Objects.To_Object (Bean.all'Access); Comment := AWA.Comments.Beans.Comment_Bean'Class (Bean.all)'Access; Comment.Set_Value ("entity_type", Util.Beans.Objects.To_Object (String '("awa_user"))); Comment.Set_Value ("permission", Util.Beans.Objects.To_Object (String '("logged-user"))); Comment.Set_Status (Status); Comment.Set_Entity_Id (User.Get_Id); -- Create the comment. Comment.Set_Message ("the comment message for the current user " & AWA.Comments.Models.Status_Type'Image (Status)); Comment.Create (Outcome); Id := Comment.Get_Id; T.Assert (Id /= ADO.NO_IDENTIFIER, "Invalid new comment identifier"); -- Load again the comments. T.List_Comments (User.Get_Id, After); T.Assert (not Util.Beans.Objects.Is_Null (Cleanup), "Comment bean is null"); end; T.Assert (not Util.Beans.Objects.Is_Null (Before), "Before list instance is null"); T.Assert (not Util.Beans.Objects.Is_Null (After), "After list instance is null"); end Create_Comment; -- ------------------------------ -- Test comment creation (PUBLISHED). -- ------------------------------ procedure Test_Create_Published_Comment (T : in out Test) is Before : Util.Beans.Objects.Object; After : Util.Beans.Objects.Object; Id : ADO.Identifier; begin T.Create_Comment (AWA.Comments.Models.COMMENT_PUBLISHED, Before, After, Id); declare Before_Count : constant Natural := Get_Count (Before); After_Count : constant Natural := Get_Count (After); begin Util.Tests.Assert_Equals (T, Before_Count + 1, After_Count, "The new comment does not appear in the list"); end; end Test_Create_Published_Comment; -- ------------------------------ -- Test comment creation (WAITING). -- ------------------------------ procedure Test_Create_Waiting_Comment (T : in out Test) is Before : Util.Beans.Objects.Object; After : Util.Beans.Objects.Object; Id : ADO.Identifier; begin T.Create_Comment (AWA.Comments.Models.COMMENT_WAITING, Before, After, Id); declare Before_Count : constant Natural := Get_Count (Before); After_Count : constant Natural := Get_Count (After); begin Util.Tests.Assert_Equals (T, Before_Count, After_Count, "The new comment MUST not appear in the list"); end; end Test_Create_Waiting_Comment; -- ------------------------------ -- Test comment removal. -- ------------------------------ procedure Test_Remove_Comment (T : in out Test) is Sec_Ctx : Security.Contexts.Security_Context; Context : AWA.Services.Contexts.Service_Context; Before : Util.Beans.Objects.Object; After : Util.Beans.Objects.Object; Id : ADO.Identifier; begin T.Create_Comment (AWA.Comments.Models.COMMENT_PUBLISHED, Before, After, Id); Util.Tests.Assert_Equals (T, Get_Count (Before) + 1, Get_Count (After), "The new comment MUST have been added in the list"); -- Now, simulate a user that logs in and deletes the comment. AWA.Tests.Helpers.Users.Login (Context, Sec_Ctx, "[email protected]"); declare Comment_Manager : constant Comment_Module_Access := Get_Comment_Module; User : constant AWA.Users.Models.User_Ref := Context.Get_User; Comment : AWA.Comments.Beans.Comment_Bean_Access; Bean : Util.Beans.Basic.Readonly_Bean_Access; Outcome : Ada.Strings.Unbounded.Unbounded_String; Cleanup : Util.Beans.Objects.Object; begin T.Assert (Comment_Manager /= null, "There is no comment module"); -- Create the comment bean for the deletion. Bean := Beans.Create_Comment_Bean (Comment_Manager); Cleanup := Util.Beans.Objects.To_Object (Bean.all'Access); Comment := AWA.Comments.Beans.Comment_Bean'Class (Bean.all)'Access; Comment.Set_Value ("entity_type", Util.Beans.Objects.To_Object (String '("awa_user"))); Comment.Set_Value ("permission", Util.Beans.Objects.To_Object (String '("logged-user"))); Comment.Set_Value ("id", ADO.Utils.To_Object (Id)); Comment.Delete (Outcome); T.List_Comments (User.Get_Id, After); T.Assert (not Util.Beans.Objects.Is_Null (Cleanup), "Comment bean is null"); end; Util.Tests.Assert_Equals (T, Get_Count (Before), Get_Count (After), "The new comment MUST have been removed from the list"); end Test_Remove_Comment; -- ------------------------------ -- Test comment publication. -- ------------------------------ procedure Test_Publish_Comment (T : in out Test) is Before : Util.Beans.Objects.Object; After : Util.Beans.Objects.Object; Sec_Ctx : Security.Contexts.Security_Context; Context : AWA.Services.Contexts.Service_Context; Id : ADO.Identifier; begin T.Create_Comment (AWA.Comments.Models.COMMENT_WAITING, Before, After, Id); Util.Tests.Assert_Equals (T, Get_Count (Before), Get_Count (After), "The new comment MUST not be in the list"); -- Now, simulate a user that logs in and publishes the comment. AWA.Tests.Helpers.Users.Login (Context, Sec_Ctx, "[email protected]"); declare Comment_Manager : constant Comment_Module_Access := Get_Comment_Module; User : constant AWA.Users.Models.User_Ref := Context.Get_User; Comment : AWA.Comments.Beans.Comment_Bean_Access; Bean : Util.Beans.Basic.Readonly_Bean_Access; Outcome : Ada.Strings.Unbounded.Unbounded_String; Cleanup : Util.Beans.Objects.Object; begin T.Assert (Comment_Manager /= null, "There is no comment module"); -- Create the comment bean for the deletion. Bean := Beans.Create_Comment_Bean (Comment_Manager); Cleanup := Util.Beans.Objects.To_Object (Bean.all'Access); Comment := AWA.Comments.Beans.Comment_Bean'Class (Bean.all)'Access; Comment.Set_Value ("entity_type", Util.Beans.Objects.To_Object (String '("awa_user"))); Comment.Set_Value ("permission", Util.Beans.Objects.To_Object (String '("logged-user"))); Comment.Set_Value ("id", ADO.Utils.To_Object (Id)); Comment.Set_Status (AWA.Comments.Models.COMMENT_PUBLISHED); Comment.Save (Outcome); T.List_Comments (User.Get_Id, After); T.Assert (not Util.Beans.Objects.Is_Null (Cleanup), "Comment bean is null"); end; Util.Tests.Assert_Equals (T, Get_Count (Before) + 1, Get_Count (After), "The new comment MUST be present in the list after publication"); end Test_Publish_Comment; end AWA.Comments.Modules.Tests;
----------------------------------------------------------------------- -- awa-comments-modules-tests -- Unit tests for comments module -- Copyright (C) 2014 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Strings.Unbounded; with Util.Test_Caller; with Util.Beans.Basic; with Security.Contexts; with ADO.Utils; with AWA.Users.Models; with AWA.Services.Contexts; with AWA.Tests.Helpers.Users; with AWA.Comments.Beans; package body AWA.Comments.Modules.Tests is use Util.Tests; use ADO; package Caller is new Util.Test_Caller (Test, "Comments.Modules"); function Get_Count (Bean : in Util.Beans.Objects.Object) return Natural; procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is begin Caller.Add_Test (Suite, "Test AWA.Comments.Modules.Create_Comment (PUBLISHED)", Test_Create_Published_Comment'Access); Caller.Add_Test (Suite, "Test AWA.Comments.Modules.Create_Comment (WAITING)", Test_Create_Waiting_Comment'Access); Caller.Add_Test (Suite, "Test AWA.Comments.Modules.Delete_Comment", Test_Remove_Comment'Access); Caller.Add_Test (Suite, "Test AWA.Comments.Modules.Update_Comment (publish)", Test_Update_Comment'Access); Caller.Add_Test (Suite, "Test AWA.Comments.Modules.Publish_Comment (publish)", Test_Publish_Comment'Access); end Add_Tests; function Get_Count (Bean : in Util.Beans.Objects.Object) return Natural is Value : constant Util.Beans.Objects.Object := Util.Beans.Objects.Get_Value (Bean, "count"); begin return Util.Beans.Objects.To_Integer (Value); end Get_Count; procedure List_Comments (T : in out Test; User : in ADO.Identifier; Into : out Util.Beans.Objects.Object) is Comment_Manager : constant Comment_Module_Access := Get_Comment_Module; Bean : Util.Beans.Basic.Readonly_Bean_Access; List : AWA.Comments.Beans.Comment_List_Bean_Access; begin Bean := Beans.Create_Comment_List_Bean (Comment_Manager); Into := Util.Beans.Objects.To_Object (Bean.all'Access); List := AWA.Comments.Beans.Comment_List_Bean'Class (Bean.all)'Access; List.Set_Value ("entity_type", Util.Beans.Objects.To_Object (String '("awa_user"))); Util.Tests.Assert_Equals (T, 0, Integer (List.Get_Count), "Invalid number of comments"); -- Load the existing comments. List.Load_Comments (User); end List_Comments; -- ------------------------------ -- Create a comment and return the list of comments before and after the creation. -- ------------------------------ procedure Create_Comment (T : in out Test; Status : in AWA.Comments.Models.Status_Type; Before : out Util.Beans.Objects.Object; After : out Util.Beans.Objects.Object; Id : out ADO.Identifier) is Sec_Ctx : Security.Contexts.Security_Context; Context : AWA.Services.Contexts.Service_Context; begin AWA.Tests.Helpers.Users.Login (Context, Sec_Ctx, "[email protected]"); declare Comment_Manager : constant Comment_Module_Access := Get_Comment_Module; User : constant AWA.Users.Models.User_Ref := Context.Get_User; Bean : Util.Beans.Basic.Readonly_Bean_Access; Comment : AWA.Comments.Beans.Comment_Bean_Access; Cleanup : Util.Beans.Objects.Object; Outcome : Ada.Strings.Unbounded.Unbounded_String; begin T.Assert (Comment_Manager /= null, "There is no comment module"); T.List_Comments (User.Get_Id, Before); -- Create a new comment associated with the current user. Bean := Beans.Create_Comment_Bean (Comment_Manager); Cleanup := Util.Beans.Objects.To_Object (Bean.all'Access); Comment := AWA.Comments.Beans.Comment_Bean'Class (Bean.all)'Access; Comment.Set_Value ("entity_type", Util.Beans.Objects.To_Object (String '("awa_user"))); Comment.Set_Value ("permission", Util.Beans.Objects.To_Object (String '("logged-user"))); Comment.Set_Status (Status); Comment.Set_Entity_Id (User.Get_Id); -- Create the comment. Comment.Set_Message ("the comment message for the current user " & AWA.Comments.Models.Status_Type'Image (Status)); Comment.Create (Outcome); Id := Comment.Get_Id; T.Assert (Id /= ADO.NO_IDENTIFIER, "Invalid new comment identifier"); -- Load again the comments. T.List_Comments (User.Get_Id, After); T.Assert (not Util.Beans.Objects.Is_Null (Cleanup), "Comment bean is null"); end; T.Assert (not Util.Beans.Objects.Is_Null (Before), "Before list instance is null"); T.Assert (not Util.Beans.Objects.Is_Null (After), "After list instance is null"); end Create_Comment; -- ------------------------------ -- Test comment creation (PUBLISHED). -- ------------------------------ procedure Test_Create_Published_Comment (T : in out Test) is Before : Util.Beans.Objects.Object; After : Util.Beans.Objects.Object; Id : ADO.Identifier; begin T.Create_Comment (AWA.Comments.Models.COMMENT_PUBLISHED, Before, After, Id); declare Before_Count : constant Natural := Get_Count (Before); After_Count : constant Natural := Get_Count (After); begin Util.Tests.Assert_Equals (T, Before_Count + 1, After_Count, "The new comment does not appear in the list"); end; end Test_Create_Published_Comment; -- ------------------------------ -- Test comment creation (WAITING). -- ------------------------------ procedure Test_Create_Waiting_Comment (T : in out Test) is Before : Util.Beans.Objects.Object; After : Util.Beans.Objects.Object; Id : ADO.Identifier; begin T.Create_Comment (AWA.Comments.Models.COMMENT_WAITING, Before, After, Id); declare Before_Count : constant Natural := Get_Count (Before); After_Count : constant Natural := Get_Count (After); begin Util.Tests.Assert_Equals (T, Before_Count, After_Count, "The new comment MUST not appear in the list"); end; end Test_Create_Waiting_Comment; -- ------------------------------ -- Test comment removal. -- ------------------------------ procedure Test_Remove_Comment (T : in out Test) is Sec_Ctx : Security.Contexts.Security_Context; Context : AWA.Services.Contexts.Service_Context; Before : Util.Beans.Objects.Object; After : Util.Beans.Objects.Object; Id : ADO.Identifier; begin T.Create_Comment (AWA.Comments.Models.COMMENT_PUBLISHED, Before, After, Id); Util.Tests.Assert_Equals (T, Get_Count (Before) + 1, Get_Count (After), "The new comment MUST have been added in the list"); -- Now, simulate a user that logs in and deletes the comment. AWA.Tests.Helpers.Users.Login (Context, Sec_Ctx, "[email protected]"); declare Comment_Manager : constant Comment_Module_Access := Get_Comment_Module; User : constant AWA.Users.Models.User_Ref := Context.Get_User; Comment : AWA.Comments.Beans.Comment_Bean_Access; Bean : Util.Beans.Basic.Readonly_Bean_Access; Outcome : Ada.Strings.Unbounded.Unbounded_String; Cleanup : Util.Beans.Objects.Object; begin T.Assert (Comment_Manager /= null, "There is no comment module"); -- Create the comment bean for the deletion. Bean := Beans.Create_Comment_Bean (Comment_Manager); Cleanup := Util.Beans.Objects.To_Object (Bean.all'Access); Comment := AWA.Comments.Beans.Comment_Bean'Class (Bean.all)'Access; Comment.Set_Value ("entity_type", Util.Beans.Objects.To_Object (String '("awa_user"))); Comment.Set_Value ("permission", Util.Beans.Objects.To_Object (String '("logged-user"))); Comment.Set_Value ("id", ADO.Utils.To_Object (Id)); Comment.Delete (Outcome); T.List_Comments (User.Get_Id, After); T.Assert (not Util.Beans.Objects.Is_Null (Cleanup), "Comment bean is null"); end; Util.Tests.Assert_Equals (T, Get_Count (Before), Get_Count (After), "The new comment MUST have been removed from the list"); end Test_Remove_Comment; -- ------------------------------ -- Test comment publication. -- ------------------------------ procedure Test_Update_Comment (T : in out Test) is Before : Util.Beans.Objects.Object; After : Util.Beans.Objects.Object; Sec_Ctx : Security.Contexts.Security_Context; Context : AWA.Services.Contexts.Service_Context; Id : ADO.Identifier; begin T.Create_Comment (AWA.Comments.Models.COMMENT_WAITING, Before, After, Id); Util.Tests.Assert_Equals (T, Get_Count (Before), Get_Count (After), "The new comment MUST not be in the list"); -- Now, simulate a user that logs in and publishes the comment. AWA.Tests.Helpers.Users.Login (Context, Sec_Ctx, "[email protected]"); declare Comment_Manager : constant Comment_Module_Access := Get_Comment_Module; User : constant AWA.Users.Models.User_Ref := Context.Get_User; Comment : AWA.Comments.Beans.Comment_Bean_Access; Bean : Util.Beans.Basic.Readonly_Bean_Access; Outcome : Ada.Strings.Unbounded.Unbounded_String; Cleanup : Util.Beans.Objects.Object; begin T.Assert (Comment_Manager /= null, "There is no comment module"); -- Create the comment bean for the deletion. Bean := Beans.Create_Comment_Bean (Comment_Manager); Cleanup := Util.Beans.Objects.To_Object (Bean.all'Access); Comment := AWA.Comments.Beans.Comment_Bean'Class (Bean.all)'Access; Comment.Set_Value ("entity_type", Util.Beans.Objects.To_Object (String '("awa_user"))); Comment.Set_Value ("permission", Util.Beans.Objects.To_Object (String '("logged-user"))); Comment.Set_Value ("id", ADO.Utils.To_Object (Id)); Comment.Set_Status (AWA.Comments.Models.COMMENT_PUBLISHED); Comment.Save (Outcome); T.List_Comments (User.Get_Id, After); T.Assert (not Util.Beans.Objects.Is_Null (Cleanup), "Comment bean is null"); end; Util.Tests.Assert_Equals (T, Get_Count (Before) + 1, Get_Count (After), "The new comment MUST be present in the list after publication"); end Test_Update_Comment; -- ------------------------------ -- Test comment publication through the publish operation bean. -- ------------------------------ procedure Test_Publish_Comment (T : in out Test) is Before : Util.Beans.Objects.Object; After : Util.Beans.Objects.Object; Sec_Ctx : Security.Contexts.Security_Context; Context : AWA.Services.Contexts.Service_Context; Id : ADO.Identifier; begin T.Create_Comment (AWA.Comments.Models.COMMENT_WAITING, Before, After, Id); Util.Tests.Assert_Equals (T, Get_Count (Before), Get_Count (After), "The new comment MUST not be in the list"); -- Now, simulate a user that logs in and publishes the comment. AWA.Tests.Helpers.Users.Login (Context, Sec_Ctx, "[email protected]"); declare Comment_Manager : constant Comment_Module_Access := Get_Comment_Module; User : constant AWA.Users.Models.User_Ref := Context.Get_User; Comment : AWA.Comments.Beans.Comment_Bean; begin T.Assert (Comment_Manager /= null, "There is no comment module"); Comment_Manager.Publish_Comment ("logged-user", Id, AWA.Comments.Models.COMMENT_PUBLISHED, Comment); T.Assert (not Comment.Is_Null, "Comment bean is null"); T.List_Comments (User.Get_Id, After); end; Util.Tests.Assert_Equals (T, Get_Count (Before) + 1, Get_Count (After), "The new comment MUST be present in the list after publication"); end Test_Publish_Comment; end AWA.Comments.Modules.Tests;
Add the new unit test for the publis_comment operation
Add the new unit test for the publis_comment operation
Ada
apache-2.0
tectronics/ada-awa,Letractively/ada-awa,tectronics/ada-awa,tectronics/ada-awa,Letractively/ada-awa,Letractively/ada-awa
3bc650fd2fbd4f12acaef76fbc00b4bd94f0dc9a
regtests/util-serialize-io-xml-tests.ads
regtests/util-serialize-io-xml-tests.ads
----------------------------------------------------------------------- -- serialize-io-xml-tests -- Unit tests for XML serialization -- Copyright (C) 2011, 2012 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Tests; package Util.Serialize.IO.XML.Tests is procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite); type Test is new Util.Tests.Test with null record; -- Test XML de-serialization procedure Test_Parser (T : in out Test); procedure Test_Parser2 (T : in out Test); -- Test (*) wildcard mapping for serialization. procedure Test_Parser_Wildcard_Mapping (T : in out Test); -- Test (**) wildcard mapping for serialization. procedure Test_Parser_Deep_Wildcard_Mapping (T : in out Test); -- Test XML de-serialization with some errors. procedure Test_Parser_Error (T : in out Test); -- Test XML serialization procedure Test_Writer (T : in out Test); end Util.Serialize.IO.XML.Tests;
----------------------------------------------------------------------- -- serialize-io-xml-tests -- Unit tests for XML serialization -- Copyright (C) 2011, 2012, 2016 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Tests; package Util.Serialize.IO.XML.Tests is procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite); type Test is new Util.Tests.Test with null record; -- Test XML de-serialization procedure Test_Parser (T : in out Test); procedure Test_Parser2 (T : in out Test); -- Test (*) wildcard mapping for serialization. procedure Test_Parser_Wildcard_Mapping (T : in out Test); -- Test (**) wildcard mapping for serialization. procedure Test_Parser_Deep_Wildcard_Mapping (T : in out Test); -- Test XML de-serialization with some errors. procedure Test_Parser_Error (T : in out Test); -- Test XML serialization procedure Test_Writer (T : in out Test); -- Test the XML output stream generation. procedure Test_Output (T : in out Test); end Util.Serialize.IO.XML.Tests;
Declare the Test_Output procedure
Declare the Test_Output procedure
Ada
apache-2.0
stcarrez/ada-util,stcarrez/ada-util
301088f762c3bd120778d9e614284d90271478c8
src/sys/lzma/util-streams-buffered-lzma.adb
src/sys/lzma/util-streams-buffered-lzma.adb
----------------------------------------------------------------------- -- util-streams-buffered-lzma -- LZMA streams -- Copyright (C) 2018 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Encoders.Lzma; package body Util.Streams.Buffered.Lzma is -- ----------------------- -- Initialize the stream to write on the given stream. -- An internal buffer is allocated for writing the stream. -- ----------------------- procedure Initialize (Stream : in out Compress_Stream; Output : in Output_Stream_Access; Size : in Natural; Format : in String) is pragma Unreferenced (Format); begin Stream.Initialize (Output, Size); Stream.Transform := new Util.Encoders.Lzma.Compress; end Initialize; -- ----------------------- -- Close the sink. -- ----------------------- overriding procedure Close (Stream : in out Compress_Stream) is begin Stream.Flush; Stream.Output.Close; end Close; -- ----------------------- -- Write the buffer array to the output stream. -- ----------------------- overriding procedure Write (Stream : in out Compress_Stream; Buffer : in Ada.Streams.Stream_Element_Array) is First_Encoded : Ada.Streams.Stream_Element_Offset := Buffer'First; Last_Encoded : Ada.Streams.Stream_Element_Offset; Last_Pos : Ada.Streams.Stream_Element_Offset; begin while First_Encoded <= Buffer'Last loop Stream.Transform.Transform (Data => Buffer (First_Encoded .. Buffer'Last), Into => Stream.Buffer (Stream.Write_Pos .. Stream.Buffer'Last), Last => Last_Pos, Encoded => Last_Encoded); if Last_Pos + 1 >= Stream.Buffer'Last then Stream.Output.Write (Stream.Buffer (Stream.Buffer'First .. Last_Pos)); Stream.Write_Pos := Stream.Buffer'First; else Stream.Write_Pos := Last_Pos + 1; end if; First_Encoded := Last_Encoded + 1; end loop; end Write; -- ----------------------- -- Flush the buffer by writing on the output stream. -- Raises Data_Error if there is no output stream. -- ----------------------- overriding procedure Flush (Stream : in out Compress_Stream) is Last_Pos : Ada.Streams.Stream_Element_Offset := Stream.Write_Pos - 1; begin loop Stream.Transform.Finish (Stream.Buffer (Stream.Write_Pos .. Stream.Buffer'Last), Last_Pos); Stream.Write_Pos := Last_Pos + 1; Output_Buffer_Stream (Stream).Flush; exit when Stream.Write_Pos < Stream.Buffer'Last; Stream.Write_Pos := 1; end loop; end Flush; -- ----------------------- -- Flush the stream and release the buffer. -- ----------------------- overriding procedure Finalize (Object : in out Compress_Stream) is begin null; end Finalize; end Util.Streams.Buffered.Lzma;
----------------------------------------------------------------------- -- util-streams-buffered-lzma -- LZMA streams -- Copyright (C) 2018, 2019 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Lzma.Check; with Lzma.Container; with Interfaces.C; package body Util.Streams.Buffered.Lzma is use type Interfaces.C.size_t; use type Base.lzma_ret; subtype Offset is Ada.Streams.Stream_Element_Offset; -- ----------------------- -- Initialize the stream to write on the given stream. -- An internal buffer is allocated for writing the stream. -- ----------------------- overriding procedure Initialize (Stream : in out Compress_Stream; Output : in Output_Stream_Access; Size : in Positive) is Result : Base.lzma_ret; begin Output_Buffer_Stream (Stream).Initialize (Output, Size); Stream.Stream.next_out := Stream.Buffer (Stream.Buffer'First)'Unchecked_Access; Stream.Stream.avail_out := Stream.Buffer'Length; Result := Container.lzma_easy_encoder (Stream.Stream'Unchecked_Access, 6, Check.LZMA_CHECK_CRC64); end Initialize; -- ----------------------- -- Close the sink. -- ----------------------- overriding procedure Close (Stream : in out Compress_Stream) is begin Stream.Flush; Stream.Output.Close; end Close; -- ----------------------- -- Write the buffer array to the output stream. -- ----------------------- overriding procedure Write (Stream : in out Compress_Stream; Buffer : in Ada.Streams.Stream_Element_Array) is Last_Pos : Ada.Streams.Stream_Element_Offset; Encoded : Boolean := False; Result : Base.lzma_ret; begin loop if Stream.Stream.avail_in = 0 then Stream.Stream.next_in := Buffer (Buffer'First)'Unrestricted_Access; Stream.Stream.avail_in := Interfaces.C.size_t (Buffer'Length); Encoded := True; end if; Result := Base.lzma_code (Stream.Stream'Unchecked_Access, Base.LZMA_RUN); -- Write the output data when the buffer is full or we reached the end of stream. if Stream.Stream.avail_out = 0 or Result = Base.LZMA_STREAM_END then Last_Pos := Stream.Buffer'First + Stream.Buffer'Length - Offset (Stream.Stream.avail_out) - 1; Stream.Output.Write (Stream.Buffer (Stream.Buffer'First .. Last_Pos)); Stream.Stream.next_out := Stream.Buffer (Stream.Buffer'First)'Unchecked_Access; Stream.Stream.avail_out := Stream.Buffer'Length; end if; exit when Result /= Base.LZMA_OK or (Stream.Stream.avail_in = 0 and Encoded); end loop; end Write; -- ----------------------- -- Flush the buffer by writing on the output stream. -- Raises Data_Error if there is no output stream. -- ----------------------- overriding procedure Flush (Stream : in out Compress_Stream) is Last_Pos : Ada.Streams.Stream_Element_Offset; Result : Base.lzma_ret; begin Stream.Stream.next_in := null; Stream.Stream.avail_in := 0; loop Result := Base.lzma_code (Stream.Stream'Unchecked_Access, Base.LZMA_FINISH); if Stream.Stream.avail_out = 0 or Result = Base.LZMA_STREAM_END then Last_Pos := Stream.Buffer'First + Stream.Buffer'Length - Offset (Stream.Stream.avail_out) - 1; Stream.Output.Write (Stream.Buffer (Stream.Buffer'First .. Last_Pos)); Stream.Stream.next_out := Stream.Buffer (Stream.Buffer'First)'Unchecked_Access; Stream.Stream.avail_out := Stream.Buffer'Length; end if; exit when Result /= Base.LZMA_OK; end loop; end Flush; -- ----------------------- -- Flush the stream and release the buffer. -- ----------------------- overriding procedure Finalize (Object : in out Compress_Stream) is begin null; end Finalize; end Util.Streams.Buffered.Lzma;
Refactor the implementation of the buffered LZMA stream
Refactor the implementation of the buffered LZMA stream
Ada
apache-2.0
stcarrez/ada-util,stcarrez/ada-util
d26481cfb47798937e888a5aa1b7c1061895e94c
src/asf-components-widgets-gravatars.adb
src/asf-components-widgets-gravatars.adb
----------------------------------------------------------------------- -- components-widgets-gravatars -- Gravatar Components -- Copyright (C) 2013 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Strings.Transforms; with GNAT.MD5; with ASF.Utils; with ASF.Contexts.Writer; package body ASF.Components.Widgets.Gravatars is IMAGE_ATTRIBUTE_NAMES : Util.Strings.String_Set.Set; -- ------------------------------ -- Given an Email address, return the Gravatar link to the user image. -- (See http://en.gravatar.com/site/implement/hash/ and -- http://en.gravatar.com/site/implement/images/) -- ------------------------------ function Get_Link (Email : in String; Secure : in Boolean := False) return String is E : constant String := Util.Strings.Transforms.To_Lower_Case (Email); C : constant GNAT.MD5.Message_Digest := GNAT.MD5.Digest (E); begin if Secure then return "https://secure.gravatar.com/avatar/" & C; else return "http://www.gravatar.com/avatar/" & C; end if; end Get_Link; -- ------------------------------ -- Render an image with the source link created from an email address to the Gravatars service. -- ------------------------------ overriding procedure Encode_Begin (UI : in UIGravatar; Context : in out ASF.Contexts.Faces.Faces_Context'Class) is Writer : constant Contexts.Writer.Response_Writer_Access := Context.Get_Response_Writer; begin if UI.Is_Rendered (Context) then Writer.Start_Element ("img"); UI.Render_Attributes (Context, IMAGE_ATTRIBUTE_NAMES, Writer); declare Email : constant String := UI.Get_Attribute ("email", Context, ""); Size : constant Natural := UI.Get_Attribute ("size", Context, 60); Default : constant String := UI.Get_Attribute ("default", Context, "identicon"); Secure : constant Boolean := UI.Get_Attribute ("secure", Context, False); D : constant String := Util.Strings.Image (Size); begin Writer.Write_Attribute ("width", D); Writer.Write_Attribute ("height", D); Writer.Write_Attribute ("src", Get_Link (Email, Secure) & "?d=" & Default & "&s=" & D); end; Writer.End_Element ("img"); end if; end Encode_Begin; begin Utils.Set_Text_Attributes (IMAGE_ATTRIBUTE_NAMES); end ASF.Components.Widgets.Gravatars;
----------------------------------------------------------------------- -- components-widgets-gravatars -- Gravatar Components -- Copyright (C) 2013 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Strings.Transforms; with GNAT.MD5; with ASF.Utils; with ASF.Contexts.Writer; package body ASF.Components.Widgets.Gravatars is IMAGE_ATTRIBUTE_NAMES : Util.Strings.String_Set.Set; -- ------------------------------ -- Given an Email address, return the Gravatar link to the user image. -- (See http://en.gravatar.com/site/implement/hash/ and -- http://en.gravatar.com/site/implement/images/) -- ------------------------------ function Get_Link (Email : in String; Secure : in Boolean := False) return String is E : constant String := Util.Strings.Transforms.To_Lower_Case (Email); C : constant GNAT.MD5.Message_Digest := GNAT.MD5.Digest (E); begin if Secure then return "https://secure.gravatar.com/avatar/" & C; else return "http://www.gravatar.com/avatar/" & C; end if; end Get_Link; -- ------------------------------ -- Render an image with the source link created from an email address to the Gravatars service. -- ------------------------------ overriding procedure Encode_Begin (UI : in UIGravatar; Context : in out ASF.Contexts.Faces.Faces_Context'Class) is Writer : constant Contexts.Writer.Response_Writer_Access := Context.Get_Response_Writer; begin if UI.Is_Rendered (Context) then Writer.Start_Element ("img"); UI.Render_Attributes (Context, IMAGE_ATTRIBUTE_NAMES, Writer); declare Email : constant String := UI.Get_Attribute ("email", Context, ""); Size : Natural := UI.Get_Attribute ("size", Context, 80); Default : constant String := UI.Get_Attribute ("default", Context, "identicon"); Secure : constant Boolean := UI.Get_Attribute ("secure", Context, False); D : constant String := Util.Strings.Image (Size); Alt : constant String := UI.Get_Attribute ("alt", Context, ""); begin if Size < 0 or Size > 2048 then Size := 80; end if; Writer.Write_Attribute ("width", D); Writer.Write_Attribute ("height", D); if Alt'Length > 0 then Writer.Write_Attribute ("alt", Alt); else Writer.Write_Attribute ("alt", Email); end if; Writer.Write_Attribute ("src", Get_Link (Email, Secure) & "?d=" & Default & "&s=" & D); end; Writer.End_Element ("img"); end if; end Encode_Begin; begin Utils.Set_Text_Attributes (IMAGE_ATTRIBUTE_NAMES); end ASF.Components.Widgets.Gravatars;
Add the 'alt' attribute on the gravatar image Make sure the image size is in the 1 .. 2048 range, ignore the size attribute if it is not valid
Add the 'alt' attribute on the gravatar image Make sure the image size is in the 1 .. 2048 range, ignore the size attribute if it is not valid
Ada
apache-2.0
Letractively/ada-asf,Letractively/ada-asf,Letractively/ada-asf
a54feaafdb41c95963646cc01b629ec1cb30187f
awa/plugins/awa-wikis/src/awa-wikis-servlets.adb
awa/plugins/awa-wikis/src/awa-wikis-servlets.adb
----------------------------------------------------------------------- -- awa-wikis-servlets -- Serve files saved in the storage service -- Copyright (C) 2016, 2018 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with AWA.Images.Modules; with AWA.Wikis.Modules; package body AWA.Wikis.Servlets is -- ------------------------------ -- Load the data content that correspond to the GET request and get the name as well -- as mime-type and date. -- ------------------------------ overriding procedure Load (Server : in Image_Servlet; Request : in out ASF.Requests.Request'Class; Name : out Ada.Strings.Unbounded.Unbounded_String; Mime : out Ada.Strings.Unbounded.Unbounded_String; Date : out Ada.Calendar.Time; Data : out ADO.Blob_Ref) is pragma Unreferenced (Server, Name); Wiki : constant String := Request.Get_Path_Parameter (1); File : constant String := Request.Get_Path_Parameter (2); Size : constant String := Request.Get_Path_Parameter (3); Module : constant AWA.Wikis.Modules.Wiki_Module_Access := Wikis.Modules.Get_Wiki_Module; Wiki_Id : ADO.Identifier; File_Id : ADO.Identifier; Width : Natural; Height : Natural; Img_Width : Natural; Img_Height : Natural; begin Wiki_Id := ADO.Identifier'Value (Wiki); File_Id := ADO.Identifier'Value (File); AWA.Images.Modules.Get_Sizes (Dimension => Size, Width => Width, Height => Height); Img_Width := Width; Img_Height := Height; Module.Load_Image (Wiki_Id => Wiki_Id, Image_Id => File_Id, Width => Img_Width, Height => Img_Height, Mime => Mime, Date => Date, Into => Data); end Load; end AWA.Wikis.Servlets;
----------------------------------------------------------------------- -- awa-wikis-servlets -- Serve files saved in the storage service -- Copyright (C) 2016, 2018 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with AWA.Images.Modules; with AWA.Wikis.Modules; package body AWA.Wikis.Servlets is -- ------------------------------ -- Load the data content that correspond to the GET request and get the name as well -- as mime-type and date. -- ------------------------------ overriding procedure Load (Server : in Image_Servlet; Request : in out ASF.Requests.Request'Class; Name : out Ada.Strings.Unbounded.Unbounded_String; Mime : out Ada.Strings.Unbounded.Unbounded_String; Date : out Ada.Calendar.Time; Data : out ADO.Blob_Ref) is pragma Unreferenced (Server, Name); Wiki : constant String := Request.Get_Path_Parameter (1); File : constant String := Request.Get_Path_Parameter (2); Size : constant String := Request.Get_Path_Parameter (3); Module : constant AWA.Wikis.Modules.Wiki_Module_Access := Wikis.Modules.Get_Wiki_Module; Wiki_Id : ADO.Identifier; File_Id : ADO.Identifier; Width : Natural; Height : Natural; Img_Width : Natural; Img_Height : Natural; begin Wiki_Id := ADO.Identifier'Value (Wiki); File_Id := ADO.Identifier'Value (File); AWA.Images.Modules.Get_Sizes (Dimension => Size, Width => Width, Height => Height); Img_Width := Width; Img_Height := Height; Module.Load_Image (Wiki_Id => Wiki_Id, Image_Id => File_Id, Width => Img_Width, Height => Img_Height, Mime => Mime, Date => Date, Into => Data); end Load; -- ------------------------------ -- Get the expected return mode (content disposition for download or inline). -- ------------------------------ overriding function Get_Format (Server : in Image_Servlet; Request : in ASF.Requests.Request'Class) return AWA.Storages.Servlets.Get_Type is pragma Unreferenced (Server, Request); begin return AWA.Storages.Servlets.DEFAULT; end Get_Format; end AWA.Wikis.Servlets;
Implement the overriden Get_Format function
Implement the overriden Get_Format function
Ada
apache-2.0
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
94967001ea8706bc8e5fbc665de430b45cc14d7b
regtests/ado-drivers-tests.adb
regtests/ado-drivers-tests.adb
----------------------------------------------------------------------- -- ado-drivers-tests -- Unit tests for database drivers -- Copyright (C) 2014 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Test_Caller; with ADO.Drivers.Connections; package body ADO.Drivers.Tests is use ADO.Drivers.Connections; package Caller is new Util.Test_Caller (Test, "ADO.Drivers"); procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is begin Caller.Add_Test (Suite, "Test ADO.Drivers.Get_Config", Test_Get_Config'Access); Caller.Add_Test (Suite, "Test ADO.Drivers.Get_Driver", Test_Get_Driver'Access); Caller.Add_Test (Suite, "Test ADO.Drivers.Get_Driver_Index", Test_Get_Driver_Index'Access); Caller.Add_Test (Suite, "Test ADO.Drivers.Get_Driver", Test_Load_Invalid_Driver'Access); end Add_Tests; -- ------------------------------ -- Test the Get_Config operation. -- ------------------------------ procedure Test_Get_Config (T : in out Test) is begin T.Assert (ADO.Drivers.Get_Config ("test.database")'Length > 0, "The Get_Config operation returned no value for the test database"); end Test_Get_Config; -- ------------------------------ -- Test the Get_Driver operation. -- ------------------------------ procedure Test_Get_Driver (T : in out Test) is Mysql_Driver : constant Driver_Access := ADO.Drivers.Connections.Get_Driver ("mysql"); Sqlite_Driver : constant Driver_Access := ADO.Drivers.Connections.Get_Driver ("sqlite"); begin T.Assert (Mysql_Driver /= null or Sqlite_Driver /= null, "No database driver was found!"); end Test_Get_Driver; -- ------------------------------ -- Test loading some invalid database driver. -- ------------------------------ procedure Test_Load_Invalid_Driver (T : in out Test) is Invalid_Driver : constant Driver_Access := ADO.Drivers.Connections.Get_Driver ("invalid"); begin T.Assert (Invalid_Driver = null, "The Get_Driver operation must return null for invalid drivers"); end Test_Load_Invalid_Driver; -- ------------------------------ -- Test the Get_Driver_Index operation. -- ------------------------------ procedure Test_Get_Driver_Index (T : in out Test) is Mysql_Driver : constant Driver_Access := ADO.Drivers.Connections.Get_Driver ("mysql"); Sqlite_Driver : constant Driver_Access := ADO.Drivers.Connections.Get_Driver ("sqlite"); begin if Mysql_Driver /= null then T.Assert (Mysql_Driver.Get_Driver_Index > 0, "The driver index must be positive"); end if; if Sqlite_Driver /= null then T.Assert (Sqlite_Driver.Get_Driver_Index > 0, "The driver index must be positive"); end if; if Mysql_Driver /= null and Sqlite_Driver /= null then T.Assert (Mysql_Driver.Get_Driver_Index /= Sqlite_Driver.Get_Driver_Index, "Two drivers must have different driver indexes"); end if; end Test_Get_Driver_Index; end ADO.Drivers.Tests;
----------------------------------------------------------------------- -- ado-drivers-tests -- Unit tests for database drivers -- Copyright (C) 2014, 2015 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Test_Caller; with ADO.Drivers.Connections; package body ADO.Drivers.Tests is use ADO.Drivers.Connections; package Caller is new Util.Test_Caller (Test, "ADO.Drivers"); procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is begin Caller.Add_Test (Suite, "Test ADO.Drivers.Get_Config", Test_Get_Config'Access); Caller.Add_Test (Suite, "Test ADO.Drivers.Get_Driver", Test_Get_Driver'Access); Caller.Add_Test (Suite, "Test ADO.Drivers.Get_Driver_Index", Test_Get_Driver_Index'Access); Caller.Add_Test (Suite, "Test ADO.Drivers.Get_Driver", Test_Load_Invalid_Driver'Access); Caller.Add_Test (Suite, "Test ADO.Drivers.Connections.Set_Connection (Errors)", Test_Set_Connection_Error'Access); end Add_Tests; -- ------------------------------ -- Test the Get_Config operation. -- ------------------------------ procedure Test_Get_Config (T : in out Test) is begin T.Assert (ADO.Drivers.Get_Config ("test.database")'Length > 0, "The Get_Config operation returned no value for the test database"); end Test_Get_Config; -- ------------------------------ -- Test the Get_Driver operation. -- ------------------------------ procedure Test_Get_Driver (T : in out Test) is Mysql_Driver : constant Driver_Access := ADO.Drivers.Connections.Get_Driver ("mysql"); Sqlite_Driver : constant Driver_Access := ADO.Drivers.Connections.Get_Driver ("sqlite"); begin T.Assert (Mysql_Driver /= null or Sqlite_Driver /= null, "No database driver was found!"); end Test_Get_Driver; -- ------------------------------ -- Test loading some invalid database driver. -- ------------------------------ procedure Test_Load_Invalid_Driver (T : in out Test) is Invalid_Driver : constant Driver_Access := ADO.Drivers.Connections.Get_Driver ("invalid"); begin T.Assert (Invalid_Driver = null, "The Get_Driver operation must return null for invalid drivers"); end Test_Load_Invalid_Driver; -- ------------------------------ -- Test the Get_Driver_Index operation. -- ------------------------------ procedure Test_Get_Driver_Index (T : in out Test) is Mysql_Driver : constant Driver_Access := ADO.Drivers.Connections.Get_Driver ("mysql"); Sqlite_Driver : constant Driver_Access := ADO.Drivers.Connections.Get_Driver ("sqlite"); begin if Mysql_Driver /= null then T.Assert (Mysql_Driver.Get_Driver_Index > 0, "The driver index must be positive"); end if; if Sqlite_Driver /= null then T.Assert (Sqlite_Driver.Get_Driver_Index > 0, "The driver index must be positive"); end if; if Mysql_Driver /= null and Sqlite_Driver /= null then T.Assert (Mysql_Driver.Get_Driver_Index /= Sqlite_Driver.Get_Driver_Index, "Two drivers must have different driver indexes"); end if; end Test_Get_Driver_Index; -- ------------------------------ -- Test the Set_Connection procedure with several error cases. -- ------------------------------ procedure Test_Set_Connection_Error (T : in out Test) is procedure Check_Invalid_Connection (URI : in String); Controller : ADO.Drivers.Connections.Configuration; procedure Check_Invalid_Connection (URI : in String) is begin Controller.Set_Connection (URI); T.Fail ("No Connection_Error exception raised for " & URI); exception when Connection_Error => null; end Check_Invalid_Connection; begin Check_Invalid_Connection (""); Check_Invalid_Connection ("http://"); Check_Invalid_Connection ("mysql://"); Check_Invalid_Connection ("sqlite://"); Check_Invalid_Connection ("mysql://:toto/"); Check_Invalid_Connection ("sqlite://:toto/"); end Test_Set_Connection_Error; end ADO.Drivers.Tests;
Implement Test_Set_Connection_Error to check various invalid URI and check that an exception is raised
Implement Test_Set_Connection_Error to check various invalid URI and check that an exception is raised
Ada
apache-2.0
stcarrez/ada-ado
d9998fe4579f2cc79b2f823f70299b18bc3fe880
mat/src/mat-formats.adb
mat/src/mat-formats.adb
----------------------------------------------------------------------- -- mat-formats - Format various types for the console or GUI interface -- Copyright (C) 2015 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- package body MAT.Formats is Hex_Prefix : Boolean := True; -- ------------------------------ -- Format the address into a string. -- ------------------------------ function Addr (Value : in MAT.Types.Target_Addr) return String is Hex : constant String := MAT.Types.Hex_Image (Value); begin if Hex_Prefix then return "0x" & Hex; else return Hex; end if; end Addr; -- ------------------------------ -- Format the size into a string. -- ------------------------------ function Size (Value : in MAT.Types.Target_Size) return String is Result : constant String := MAT.Types.Target_Size'Image (Value); begin if Result (Result'First) = ' ' then return Result (Result'First + 1 .. Result'Last); else return Result; end if; end Size; function Location (File : in Ada.Strings.Unbounded.Unbounded_String) return String is Pos : constant Natural := Ada.Strings.Unbounded.Index (File, "/", Ada.Strings.Backward); Len : constant Natural := Ada.Strings.Unbounded.Length (File); begin if Pos /= 0 then return Ada.Strings.Unbounded.Slice (File, Pos + 1, Len); else return Ada.Strings.Unbounded.To_String (File); end if; end Location; -- ------------------------------ -- Format a file, line, function information into a string. -- ------------------------------ function Location (File : in Ada.Strings.Unbounded.Unbounded_String; Line : in Natural; Func : in Ada.Strings.Unbounded.Unbounded_String) return String is begin if Ada.Strings.Unbounded.Length (File) = 0 then return Ada.Strings.Unbounded.To_String (Func); elsif Line > 0 then declare Num : constant String := Natural'Image (Line); begin return Ada.Strings.Unbounded.To_String (Func) & " (" & Location (File) & ":" & Num (Num'First + 1 .. Num'Last) & ")"; end; else return Ada.Strings.Unbounded.To_String (Func) & " (" & Location (File) & ")"; end if; end Location; function Event (Item : in MAT.Events.Targets.Probe_Event_Type) return String is begin case Item.Index is when MAT.Events.Targets.MSG_MALLOC => return Size (Item.Size) & " bytes allocated"; when MAT.Events.Targets.MSG_REALLOC => return Size (Item.Size) & " bytes reallocated"; when MAT.Events.Targets.MSG_FREE => return Size (Item.Size) & " bytes freed"; when others => return "unknown"; end case; end Event; function Event_Malloc (Item : in MAT.Events.Targets.Probe_Event_Type; Related : in MAT.Events.Targets.Target_Event_Vector) return String is Iter : MAT.Events.Targets.Target_Event_Cursor := Related.First; Free_Event : MAT.Events.Targets.Probe_Event_Type; begin Free_Event := MAT.Events.Targets.Find (Related, MAT.Events.Targets.MSG_FREE); return Size (Item.Size) & " bytes allocated, "; exception when MAT.Events.Targets.Not_Found => return Size (Item.Size) & " bytes allocated"; end Event_Malloc; -- Format a short description of the event. function Event (Item : in MAT.Events.Targets.Probe_Event_Type; Related : in MAT.Events.Targets.Target_Event_Vector) return String is begin case Item.Index is when MAT.Events.Targets.MSG_MALLOC => return Event_Malloc (Item, Related); when MAT.Events.Targets.MSG_REALLOC => return Size (Item.Size) & " bytes reallocated"; when MAT.Events.Targets.MSG_FREE => return Size (Item.Size) & " bytes freed"; when MAT.Events.Targets.MSG_BEGIN => return "Begin event"; when MAT.Events.Targets.MSG_END => return "End event"; when MAT.Events.Targets.MSG_LIBRARY => return "Library information event"; when others => return "unknown"; end case; end Event; end MAT.Formats;
----------------------------------------------------------------------- -- mat-formats - Format various types for the console or GUI interface -- Copyright (C) 2015 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- package body MAT.Formats is Hex_Prefix : Boolean := True; Conversion : constant String (1 .. 10) := "0123456789"; -- ------------------------------ -- Format the address into a string. -- ------------------------------ function Addr (Value : in MAT.Types.Target_Addr) return String is Hex : constant String := MAT.Types.Hex_Image (Value); begin if Hex_Prefix then return "0x" & Hex; else return Hex; end if; end Addr; -- ------------------------------ -- Format the size into a string. -- ------------------------------ function Size (Value : in MAT.Types.Target_Size) return String is Result : constant String := MAT.Types.Target_Size'Image (Value); begin if Result (Result'First) = ' ' then return Result (Result'First + 1 .. Result'Last); else return Result; end if; end Size; -- ------------------------------ -- Format the time relative to the start time. -- ------------------------------ function Time (Value : in MAT.Types.Target_Tick_Ref; Start : in MAT.Types.Target_Tick_Ref) return String is use type MAT.Types.Target_Tick_Ref; T : constant MAT.Types.Target_Tick_Ref := Value - Start; Sec : constant MAT.Types.Target_Tick_Ref := T / 1_000_000; Usec : constant MAT.Types.Target_Tick_Ref := T mod 1_000_000; Msec : Natural := Natural (Usec / 1_000); Frac : String (1 .. 5); begin Frac (5) := 's'; Frac (4) := Conversion (Msec mod 10 + 1); Msec := Msec / 10; Frac (3) := Conversion (Msec mod 10 + 1); Msec := Msec / 10; Frac (2) := Conversion (Msec mod 10 + 1); Frac (1) := '.'; return MAT.Types.Target_Tick_Ref'Image (Sec) & Frac; end Time; function Location (File : in Ada.Strings.Unbounded.Unbounded_String) return String is Pos : constant Natural := Ada.Strings.Unbounded.Index (File, "/", Ada.Strings.Backward); Len : constant Natural := Ada.Strings.Unbounded.Length (File); begin if Pos /= 0 then return Ada.Strings.Unbounded.Slice (File, Pos + 1, Len); else return Ada.Strings.Unbounded.To_String (File); end if; end Location; -- ------------------------------ -- Format a file, line, function information into a string. -- ------------------------------ function Location (File : in Ada.Strings.Unbounded.Unbounded_String; Line : in Natural; Func : in Ada.Strings.Unbounded.Unbounded_String) return String is begin if Ada.Strings.Unbounded.Length (File) = 0 then return Ada.Strings.Unbounded.To_String (Func); elsif Line > 0 then declare Num : constant String := Natural'Image (Line); begin return Ada.Strings.Unbounded.To_String (Func) & " (" & Location (File) & ":" & Num (Num'First + 1 .. Num'Last) & ")"; end; else return Ada.Strings.Unbounded.To_String (Func) & " (" & Location (File) & ")"; end if; end Location; function Event (Item : in MAT.Events.Targets.Probe_Event_Type) return String is begin case Item.Index is when MAT.Events.Targets.MSG_MALLOC => return Size (Item.Size) & " bytes allocated"; when MAT.Events.Targets.MSG_REALLOC => return Size (Item.Size) & " bytes reallocated"; when MAT.Events.Targets.MSG_FREE => return Size (Item.Size) & " bytes freed"; when others => return "unknown"; end case; end Event; function Event_Malloc (Item : in MAT.Events.Targets.Probe_Event_Type; Related : in MAT.Events.Targets.Target_Event_Vector) return String is Iter : MAT.Events.Targets.Target_Event_Cursor := Related.First; Free_Event : MAT.Events.Targets.Probe_Event_Type; begin Free_Event := MAT.Events.Targets.Find (Related, MAT.Events.Targets.MSG_FREE); return Size (Item.Size) & " bytes allocated, " & Time (Free_Event.Time, Item.Time); exception when MAT.Events.Targets.Not_Found => return Size (Item.Size) & " bytes allocated"; end Event_Malloc; -- Format a short description of the event. function Event (Item : in MAT.Events.Targets.Probe_Event_Type; Related : in MAT.Events.Targets.Target_Event_Vector) return String is begin case Item.Index is when MAT.Events.Targets.MSG_MALLOC => return Event_Malloc (Item, Related); when MAT.Events.Targets.MSG_REALLOC => return Size (Item.Size) & " bytes reallocated"; when MAT.Events.Targets.MSG_FREE => return Size (Item.Size) & " bytes freed"; when MAT.Events.Targets.MSG_BEGIN => return "Begin event"; when MAT.Events.Targets.MSG_END => return "End event"; when MAT.Events.Targets.MSG_LIBRARY => return "Library information event"; when others => return "unknown"; end case; end Event; end MAT.Formats;
Implement the Time operation to format a relative time
Implement the Time operation to format a relative time
Ada
apache-2.0
stcarrez/mat,stcarrez/mat,stcarrez/mat
d2824898bc03c887c5c7f5601f74decb4ff7aeb6
mat/src/mat-formats.adb
mat/src/mat-formats.adb
----------------------------------------------------------------------- -- mat-formats - Format various types for the console or GUI interface -- Copyright (C) 2015 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Strings; package body MAT.Formats is use type MAT.Types.Target_Tick_Ref; Hex_Prefix : Boolean := True; Conversion : constant String (1 .. 10) := "0123456789"; -- ------------------------------ -- Format the address into a string. -- ------------------------------ function Addr (Value : in MAT.Types.Target_Addr) return String is Hex : constant String := MAT.Types.Hex_Image (Value); begin if Hex_Prefix then return "0x" & Hex; else return Hex; end if; end Addr; -- ------------------------------ -- Format the size into a string. -- ------------------------------ function Size (Value : in MAT.Types.Target_Size) return String is Result : constant String := MAT.Types.Target_Size'Image (Value); begin if Result (Result'First) = ' ' then return Result (Result'First + 1 .. Result'Last); else return Result; end if; end Size; -- ------------------------------ -- Format the time relative to the start time. -- ------------------------------ function Time (Value : in MAT.Types.Target_Tick_Ref; Start : in MAT.Types.Target_Tick_Ref) return String is T : constant MAT.Types.Target_Tick_Ref := Value - Start; Sec : constant MAT.Types.Target_Tick_Ref := T / 1_000_000; Usec : constant MAT.Types.Target_Tick_Ref := T mod 1_000_000; Msec : Natural := Natural (Usec / 1_000); Frac : String (1 .. 5); begin Frac (5) := 's'; Frac (4) := Conversion (Msec mod 10 + 1); Msec := Msec / 10; Frac (3) := Conversion (Msec mod 10 + 1); Msec := Msec / 10; Frac (2) := Conversion (Msec mod 10 + 1); Frac (1) := '.'; return MAT.Types.Target_Tick_Ref'Image (Sec) & Frac; end Time; -- ------------------------------ -- Format the duration in seconds, milliseconds or microseconds. -- ------------------------------ function Duration (Value : in MAT.Types.Target_Tick_Ref) return String is Sec : constant MAT.Types.Target_Tick_Ref := Value / 1_000_000; Usec : constant MAT.Types.Target_Tick_Ref := Value mod 1_000_000; Msec : Natural := Natural (Usec / 1_000); Val : Natural; Frac : String (1 .. 5); begin if Sec = 0 and Msec = 0 then return Util.Strings.Image (Integer (Usec)) & "us"; elsif Sec = 0 then Val := Natural (Usec mod 1_000); Frac (5) := 's'; Frac (4) := 'm'; Frac (3) := Conversion (Val mod 10 + 1); Val := Val / 10; Frac (3) := Conversion (Val mod 10 + 1); Val := Val / 10; Frac (2) := Conversion (Val mod 10 + 1); Frac (1) := '.'; return Util.Strings.Image (Integer (Msec)) & Frac; else Val := Msec; Frac (4) := 's'; Frac (3) := Conversion (Val mod 10 + 1); Val := Val / 10; Frac (3) := Conversion (Val mod 10 + 1); Val := Val / 10; Frac (2) := Conversion (Val mod 10 + 1); Frac (1) := '.'; return Util.Strings.Image (Integer (Msec)) & Frac (1 .. 4); end if; end Duration; function Location (File : in Ada.Strings.Unbounded.Unbounded_String) return String is Pos : constant Natural := Ada.Strings.Unbounded.Index (File, "/", Ada.Strings.Backward); Len : constant Natural := Ada.Strings.Unbounded.Length (File); begin if Pos /= 0 then return Ada.Strings.Unbounded.Slice (File, Pos + 1, Len); else return Ada.Strings.Unbounded.To_String (File); end if; end Location; -- ------------------------------ -- Format a file, line, function information into a string. -- ------------------------------ function Location (File : in Ada.Strings.Unbounded.Unbounded_String; Line : in Natural; Func : in Ada.Strings.Unbounded.Unbounded_String) return String is begin if Ada.Strings.Unbounded.Length (File) = 0 then return Ada.Strings.Unbounded.To_String (Func); elsif Line > 0 then declare Num : constant String := Natural'Image (Line); begin return Ada.Strings.Unbounded.To_String (Func) & " (" & Location (File) & ":" & Num (Num'First + 1 .. Num'Last) & ")"; end; else return Ada.Strings.Unbounded.To_String (Func) & " (" & Location (File) & ")"; end if; end Location; function Event (Item : in MAT.Events.Targets.Probe_Event_Type) return String is begin case Item.Index is when MAT.Events.Targets.MSG_MALLOC => return Size (Item.Size) & " bytes allocated"; when MAT.Events.Targets.MSG_REALLOC => return Size (Item.Size) & " bytes reallocated"; when MAT.Events.Targets.MSG_FREE => return Size (Item.Size) & " bytes freed"; when others => return "unknown"; end case; end Event; function Event_Malloc (Item : in MAT.Events.Targets.Probe_Event_Type; Related : in MAT.Events.Targets.Target_Event_Vector; Start_Time : in MAT.Types.Target_Tick_Ref) return String is Iter : MAT.Events.Targets.Target_Event_Cursor := Related.First; Free_Event : MAT.Events.Targets.Probe_Event_Type; begin Free_Event := MAT.Events.Targets.Find (Related, MAT.Events.Targets.MSG_FREE); return Size (Item.Size) & " bytes allocated after " & Duration (Item.Time - Start_Time) & ", freed by event" & MAT.Events.Targets.Event_Id_Type'Image (Free_Event.Id) & " after " & Duration (Free_Event.Time - Item.Time) ; exception when MAT.Events.Targets.Not_Found => return Size (Item.Size) & " bytes allocated"; end Event_Malloc; function Event_Free (Item : in MAT.Events.Targets.Probe_Event_Type; Related : in MAT.Events.Targets.Target_Event_Vector; Start_Time : in MAT.Types.Target_Tick_Ref) return String is Iter : MAT.Events.Targets.Target_Event_Cursor := Related.First; Alloc_Event : MAT.Events.Targets.Probe_Event_Type; begin Alloc_Event := MAT.Events.Targets.Find (Related, MAT.Events.Targets.MSG_MALLOC); return Size (Alloc_Event.Size) & " bytes freed after " & Duration (Item.Time - Start_Time) & ", alloc'ed for " & Duration (Item.Time - Alloc_Event.Time) & " by event" & MAT.Events.Targets.Event_Id_Type'Image (Alloc_Event.Id) ; exception when MAT.Events.Targets.Not_Found => return Size (Item.Size) & " bytes freed"; end Event_Free; -- Format a short description of the event. function Event (Item : in MAT.Events.Targets.Probe_Event_Type; Related : in MAT.Events.Targets.Target_Event_Vector; Start_Time : in MAT.Types.Target_Tick_Ref) return String is begin case Item.Index is when MAT.Events.Targets.MSG_MALLOC => return Event_Malloc (Item, Related, Start_Time); when MAT.Events.Targets.MSG_REALLOC => return Size (Item.Size) & " bytes reallocated"; when MAT.Events.Targets.MSG_FREE => return Event_Free (Item, Related, Start_Time); when MAT.Events.Targets.MSG_BEGIN => return "Begin event"; when MAT.Events.Targets.MSG_END => return "End event"; when MAT.Events.Targets.MSG_LIBRARY => return "Library information event"; when others => return "unknown"; end case; end Event; end MAT.Formats;
----------------------------------------------------------------------- -- mat-formats - Format various types for the console or GUI interface -- Copyright (C) 2015 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Strings; package body MAT.Formats is use type MAT.Types.Target_Tick_Ref; Hex_Prefix : Boolean := True; Conversion : constant String (1 .. 10) := "0123456789"; -- ------------------------------ -- Format the address into a string. -- ------------------------------ function Addr (Value : in MAT.Types.Target_Addr) return String is Hex : constant String := MAT.Types.Hex_Image (Value); begin if Hex_Prefix then return "0x" & Hex; else return Hex; end if; end Addr; -- ------------------------------ -- Format the size into a string. -- ------------------------------ function Size (Value : in MAT.Types.Target_Size) return String is Result : constant String := MAT.Types.Target_Size'Image (Value); begin if Result (Result'First) = ' ' then return Result (Result'First + 1 .. Result'Last); else return Result; end if; end Size; -- ------------------------------ -- Format the time relative to the start time. -- ------------------------------ function Time (Value : in MAT.Types.Target_Tick_Ref; Start : in MAT.Types.Target_Tick_Ref) return String is T : constant MAT.Types.Target_Tick_Ref := Value - Start; Sec : constant MAT.Types.Target_Tick_Ref := T / 1_000_000; Usec : constant MAT.Types.Target_Tick_Ref := T mod 1_000_000; Msec : Natural := Natural (Usec / 1_000); Frac : String (1 .. 5); begin Frac (5) := 's'; Frac (4) := Conversion (Msec mod 10 + 1); Msec := Msec / 10; Frac (3) := Conversion (Msec mod 10 + 1); Msec := Msec / 10; Frac (2) := Conversion (Msec mod 10 + 1); Frac (1) := '.'; return MAT.Types.Target_Tick_Ref'Image (Sec) & Frac; end Time; -- ------------------------------ -- Format the duration in seconds, milliseconds or microseconds. -- ------------------------------ function Duration (Value : in MAT.Types.Target_Tick_Ref) return String is Sec : constant MAT.Types.Target_Tick_Ref := Value / 1_000_000; Usec : constant MAT.Types.Target_Tick_Ref := Value mod 1_000_000; Msec : Natural := Natural (Usec / 1_000); Val : Natural; Frac : String (1 .. 5); begin if Sec = 0 and Msec = 0 then return Util.Strings.Image (Integer (Usec)) & "us"; elsif Sec = 0 then Val := Natural (Usec mod 1_000); Frac (5) := 's'; Frac (4) := 'm'; Frac (3) := Conversion (Val mod 10 + 1); Val := Val / 10; Frac (3) := Conversion (Val mod 10 + 1); Val := Val / 10; Frac (2) := Conversion (Val mod 10 + 1); Frac (1) := '.'; return Util.Strings.Image (Integer (Msec)) & Frac; else Val := Msec; Frac (4) := 's'; Frac (3) := Conversion (Val mod 10 + 1); Val := Val / 10; Frac (3) := Conversion (Val mod 10 + 1); Val := Val / 10; Frac (2) := Conversion (Val mod 10 + 1); Frac (1) := '.'; return Util.Strings.Image (Integer (Msec)) & Frac (1 .. 4); end if; end Duration; function Location (File : in Ada.Strings.Unbounded.Unbounded_String) return String is Pos : constant Natural := Ada.Strings.Unbounded.Index (File, "/", Ada.Strings.Backward); Len : constant Natural := Ada.Strings.Unbounded.Length (File); begin if Pos /= 0 then return Ada.Strings.Unbounded.Slice (File, Pos + 1, Len); else return Ada.Strings.Unbounded.To_String (File); end if; end Location; -- ------------------------------ -- Format a file, line, function information into a string. -- ------------------------------ function Location (File : in Ada.Strings.Unbounded.Unbounded_String; Line : in Natural; Func : in Ada.Strings.Unbounded.Unbounded_String) return String is begin if Ada.Strings.Unbounded.Length (File) = 0 then return Ada.Strings.Unbounded.To_String (Func); elsif Line > 0 then declare Num : constant String := Natural'Image (Line); begin return Ada.Strings.Unbounded.To_String (Func) & " (" & Location (File) & ":" & Num (Num'First + 1 .. Num'Last) & ")"; end; else return Ada.Strings.Unbounded.To_String (Func) & " (" & Location (File) & ")"; end if; end Location; -- ------------------------------ -- Format a short description of the event. -- ------------------------------ function Event (Item : in MAT.Events.Targets.Probe_Event_Type) return String is begin case Item.Index is when MAT.Events.Targets.MSG_MALLOC => return "malloc(" & Size (Item.Size) & ") = " & Addr (Item.Addr); when MAT.Events.Targets.MSG_REALLOC => return "realloc(" & Addr (Item.Old_Addr) & "," & Size (Item.Size) & ") = " & Addr (Item.Addr); when MAT.Events.Targets.MSG_FREE => return "free(" & Addr (Item.Addr) & ")"; when MAT.Events.Targets.MSG_BEGIN => return "begin"; when MAT.Events.Targets.MSG_END => return "end"; when MAT.Events.Targets.MSG_LIBRARY => return "library"; when others => return "unknown"; end case; end Event; function Event_Malloc (Item : in MAT.Events.Targets.Probe_Event_Type; Related : in MAT.Events.Targets.Target_Event_Vector; Start_Time : in MAT.Types.Target_Tick_Ref) return String is Iter : MAT.Events.Targets.Target_Event_Cursor := Related.First; Free_Event : MAT.Events.Targets.Probe_Event_Type; begin Free_Event := MAT.Events.Targets.Find (Related, MAT.Events.Targets.MSG_FREE); return Size (Item.Size) & " bytes allocated after " & Duration (Item.Time - Start_Time) & ", freed " & Duration (Free_Event.Time - Item.Time) & " after by event" & MAT.Events.Targets.Event_Id_Type'Image (Free_Event.Id) ; exception when MAT.Events.Targets.Not_Found => return Size (Item.Size) & " bytes allocated (never freed)"; end Event_Malloc; function Event_Free (Item : in MAT.Events.Targets.Probe_Event_Type; Related : in MAT.Events.Targets.Target_Event_Vector; Start_Time : in MAT.Types.Target_Tick_Ref) return String is Iter : MAT.Events.Targets.Target_Event_Cursor := Related.First; Alloc_Event : MAT.Events.Targets.Probe_Event_Type; begin Alloc_Event := MAT.Events.Targets.Find (Related, MAT.Events.Targets.MSG_MALLOC); return Size (Alloc_Event.Size) & " bytes freed after " & Duration (Item.Time - Start_Time) & ", alloc'ed for " & Duration (Item.Time - Alloc_Event.Time) & " by event" & MAT.Events.Targets.Event_Id_Type'Image (Alloc_Event.Id) ; exception when MAT.Events.Targets.Not_Found => return Size (Item.Size) & " bytes freed"; end Event_Free; -- Format a short description of the event. function Event (Item : in MAT.Events.Targets.Probe_Event_Type; Related : in MAT.Events.Targets.Target_Event_Vector; Start_Time : in MAT.Types.Target_Tick_Ref) return String is begin case Item.Index is when MAT.Events.Targets.MSG_MALLOC => return Event_Malloc (Item, Related, Start_Time); when MAT.Events.Targets.MSG_REALLOC => return Size (Item.Size) & " bytes reallocated"; when MAT.Events.Targets.MSG_FREE => return Event_Free (Item, Related, Start_Time); when MAT.Events.Targets.MSG_BEGIN => return "Begin event"; when MAT.Events.Targets.MSG_END => return "End event"; when MAT.Events.Targets.MSG_LIBRARY => return "Library information event"; when others => return "unknown"; end case; end Event; end MAT.Formats;
Implement the new Event function to print a short description of an event
Implement the new Event function to print a short description of an event
Ada
apache-2.0
stcarrez/mat,stcarrez/mat,stcarrez/mat
20b139f4045974fa43bf33becf68b90ece17e059
regtests/wiki-tests.adb
regtests/wiki-tests.adb
----------------------------------------------------------------------- -- Render Tests - Unit tests for AWA Wiki rendering -- Copyright (C) 2013, 2016 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Text_IO; with Ada.Directories; with Ada.Characters.Conversions; with Util.Files; with Util.Measures; with Wiki.Render.Wiki; with Wiki.Filters.Html; with Wiki.Streams.Html.Builders; with Wiki.Utils; package body Wiki.Tests is use Ada.Strings.Unbounded; use type Wiki.Parsers.Wiki_Syntax_Type; -- ------------------------------ -- Test rendering a wiki text in HTML or text. -- ------------------------------ procedure Test_Render (T : in out Test) is function To_Wide (Item : in String) return Wide_Wide_String renames Ada.Characters.Conversions.To_Wide_Wide_String; Result_File : constant String := To_String (T.Result); Content : Unbounded_String; begin Util.Files.Read_File (Path => To_String (T.File), Into => Content, Max_Size => 10000); declare Time : Util.Measures.Stamp; begin if T.Source = Wiki.Parsers.SYNTAX_HTML then declare Html_Filter : aliased Wiki.Filters.Html.Html_Filter_Type; Writer : aliased Wiki.Writers.Builders.Writer_Builder_Type; Renderer : aliased Wiki.Render.Wiki.Wiki_Renderer; begin Renderer.Set_Writer (Writer'Unchecked_Access, T.Format); Html_Filter.Set_Document (Renderer'Unchecked_Access); Wiki.Parsers.Parse (Html_Filter'Unchecked_Access, To_Wide (To_String (Content)), Wiki.Parsers.SYNTAX_HTML); Content := To_Unbounded_String (Writer.To_String); end; elsif T.Is_Html then Content := To_Unbounded_String (Utils.To_Html (To_Wide (To_String (Content)), T.Format)); else Content := To_Unbounded_String (Utils.To_Text (To_Wide (To_String (Content)), T.Format)); end if; Util.Measures.Report (Time, "Render " & To_String (T.Name)); end; Util.Files.Write_File (Result_File, Content); Util.Tests.Assert_Equal_Files (T => T, Expect => To_String (T.Expect), Test => Result_File, Message => "Render"); end Test_Render; -- ------------------------------ -- Test case name -- ------------------------------ overriding function Name (T : in Test) return Util.Tests.Message_String is begin if T.Source = Wiki.Parsers.SYNTAX_HTML then return Util.Tests.Format ("Test IMPORT " & To_String (T.Name)); elsif T.Is_Html then return Util.Tests.Format ("Test HTML " & To_String (T.Name)); else return Util.Tests.Format ("Test TEXT " & To_String (T.Name)); end if; end Name; -- ------------------------------ -- Perform the test. -- ------------------------------ overriding procedure Run_Test (T : in out Test) is begin T.Test_Render; end Run_Test; procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is use Ada.Directories; procedure Add_Import_Tests; procedure Add_Wiki_Tests; function Create_Test (Name : in String; Path : in String; Format : in Wiki.Parsers.Wiki_Syntax_Type; Prefix : in String; Is_Html : in Boolean) return Test_Case_Access; Result_Dir : constant String := "regtests/result"; Expect_Dir : constant String := "regtests/expect"; Expect_Path : constant String := Util.Tests.Get_Path (Expect_Dir); Result_Path : constant String := Util.Tests.Get_Test_Path (Result_Dir); Search : Search_Type; Filter : constant Filter_Type := (others => True); Ent : Directory_Entry_Type; function Create_Test (Name : in String; Path : in String; Format : in Wiki.Parsers.Wiki_Syntax_Type; Prefix : in String; Is_Html : in Boolean) return Test_Case_Access is Tst : Test_Case_Access; begin Tst := new Test; Tst.Is_Html := Is_Html; Tst.Name := To_Unbounded_String (Name); Tst.File := To_Unbounded_String (Path); Tst.Expect := To_Unbounded_String (Expect_Path & Prefix & Name); Tst.Result := To_Unbounded_String (Result_Path & Prefix & Name); Tst.Format := Format; Tst.Source := Format; return Tst; end Create_Test; procedure Add_Wiki_Tests is Dir : constant String := "regtests/files/wiki"; Path : constant String := Util.Tests.Get_Path (Dir); begin if Kind (Path) /= Directory then Ada.Text_IO.Put_Line ("Cannot read test directory: " & Path); end if; Start_Search (Search, Directory => Path, Pattern => "*.*", Filter => Filter); while More_Entries (Search) loop Get_Next_Entry (Search, Ent); declare Simple : constant String := Simple_Name (Ent); Ext : constant String := Ada.Directories.Extension (Simple); Tst : Test_Case_Access; Format : Wiki.Parsers.Wiki_Syntax_Type; begin if Simple /= "." and then Simple /= ".." and then Simple /= ".svn" and then Simple (Simple'Last) /= '~' then if Ext = "wiki" then Format := Wiki.Parsers.SYNTAX_GOOGLE; elsif Ext = "dotclear" then Format := Wiki.Parsers.SYNTAX_DOTCLEAR; elsif Ext = "creole" then Format := Wiki.Parsers.SYNTAX_CREOLE; elsif Ext = "phpbb" then Format := Wiki.Parsers.SYNTAX_PHPBB; elsif Ext = "mediawiki" then Format := Wiki.Parsers.SYNTAX_MEDIA_WIKI; else Format := Wiki.Parsers.SYNTAX_MIX; end if; Tst := Create_Test (Simple, Path & "/" & Simple, Format, "/wiki-html/", True); Suite.Add_Test (Tst.all'Access); Tst := Create_Test (Simple, Path & "/" & Simple, Format, "/wiki-txt/", False); Suite.Add_Test (Tst.all'Access); end if; end; end loop; end Add_Wiki_Tests; procedure Add_Import_Tests is Dir : constant String := "regtests/files/html"; Path : constant String := Util.Tests.Get_Path (Dir); begin if Kind (Path) /= Directory then Ada.Text_IO.Put_Line ("Cannot read test directory: " & Path); end if; Start_Search (Search, Directory => Path, Pattern => "*.*", Filter => Filter); while More_Entries (Search) loop Get_Next_Entry (Search, Ent); declare Simple : constant String := Simple_Name (Ent); Name : constant String := Base_Name (Simple); Tst : Test_Case_Access; begin if Simple /= "." and then Simple /= ".." and then Simple /= ".svn" and then Simple (Simple'Last) /= '~' then for Syntax in Wiki.Parsers.Wiki_Syntax_Type'Range loop case Syntax is when Wiki.Parsers.SYNTAX_CREOLE => Tst := Create_Test (Name & ".creole", Path & "/" & Simple, Syntax, "/wiki-import/", True); when Wiki.Parsers.SYNTAX_DOTCLEAR => Tst := Create_Test (Name & ".dotclear", Path & "/" & Simple, Syntax, "/wiki-import/", True); when Wiki.Parsers.SYNTAX_MEDIA_WIKI => Tst := Create_Test (Name & ".mediawiki", Path & "/" & Simple, Syntax, "/wiki-import/", True); when others => Tst := null; end case; if Tst /= null then Tst.Source := Wiki.Parsers.SYNTAX_HTML; Suite.Add_Test (Tst.all'Access); end if; end loop; end if; end; end loop; end Add_Import_Tests; begin Add_Wiki_Tests; Add_Import_Tests; end Add_Tests; end Wiki.Tests;
----------------------------------------------------------------------- -- Render Tests - Unit tests for AWA Wiki rendering -- Copyright (C) 2013, 2016 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Text_IO; with Ada.Directories; with Ada.Characters.Conversions; with Util.Files; with Util.Measures; with Wiki.Render.Wiki; with Wiki.Filters.Html; with Wiki.Streams.Html.Builders; with Wiki.Streams.Builders; with Wiki.Utils; with Wiki.Nodes; package body Wiki.Tests is use Ada.Strings.Unbounded; use type Wiki.Parsers.Wiki_Syntax_Type; -- ------------------------------ -- Test rendering a wiki text in HTML or text. -- ------------------------------ procedure Test_Render (T : in out Test) is function To_Wide (Item : in String) return Wide_Wide_String renames Ada.Characters.Conversions.To_Wide_Wide_String; Result_File : constant String := To_String (T.Result); Content : Unbounded_String; begin Util.Files.Read_File (Path => To_String (T.File), Into => Content, Max_Size => 10000); declare Time : Util.Measures.Stamp; begin if T.Source = Wiki.Parsers.SYNTAX_HTML then declare Html_Filter : aliased Wiki.Filters.Html.Html_Filter_Type; Writer : aliased Wiki.Streams.Builders.Output_Builder_Stream; Renderer : aliased Wiki.Render.Wiki.Wiki_Renderer; Doc : Wiki.Nodes.Document; Engine : Wiki.Parsers.Parser; begin Renderer.Set_Output_Stream (Writer'Unchecked_Access, T.Format); Engine.Add_Filter (Html_Filter'Unchecked_Access); Engine.Set_Syntax (Wiki.Parsers.SYNTAX_HTML); Engine.Parse (To_Wide (To_String (Content)), Doc); Renderer.Render (Doc); Content := To_Unbounded_String (Writer.To_String); end; elsif T.Is_Html then Content := To_Unbounded_String (Utils.To_Html (To_Wide (To_String (Content)), T.Format)); else Content := To_Unbounded_String (Utils.To_Text (To_Wide (To_String (Content)), T.Format)); end if; Util.Measures.Report (Time, "Render " & To_String (T.Name)); end; Util.Files.Write_File (Result_File, Content); Util.Tests.Assert_Equal_Files (T => T, Expect => To_String (T.Expect), Test => Result_File, Message => "Render"); end Test_Render; -- ------------------------------ -- Test case name -- ------------------------------ overriding function Name (T : in Test) return Util.Tests.Message_String is begin if T.Source = Wiki.Parsers.SYNTAX_HTML then return Util.Tests.Format ("Test IMPORT " & To_String (T.Name)); elsif T.Is_Html then return Util.Tests.Format ("Test HTML " & To_String (T.Name)); else return Util.Tests.Format ("Test TEXT " & To_String (T.Name)); end if; end Name; -- ------------------------------ -- Perform the test. -- ------------------------------ overriding procedure Run_Test (T : in out Test) is begin T.Test_Render; end Run_Test; procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is use Ada.Directories; procedure Add_Import_Tests; procedure Add_Wiki_Tests; function Create_Test (Name : in String; Path : in String; Format : in Wiki.Parsers.Wiki_Syntax_Type; Prefix : in String; Is_Html : in Boolean) return Test_Case_Access; Result_Dir : constant String := "regtests/result"; Expect_Dir : constant String := "regtests/expect"; Expect_Path : constant String := Util.Tests.Get_Path (Expect_Dir); Result_Path : constant String := Util.Tests.Get_Test_Path (Result_Dir); Search : Search_Type; Filter : constant Filter_Type := (others => True); Ent : Directory_Entry_Type; function Create_Test (Name : in String; Path : in String; Format : in Wiki.Parsers.Wiki_Syntax_Type; Prefix : in String; Is_Html : in Boolean) return Test_Case_Access is Tst : Test_Case_Access; begin Tst := new Test; Tst.Is_Html := Is_Html; Tst.Name := To_Unbounded_String (Name); Tst.File := To_Unbounded_String (Path); Tst.Expect := To_Unbounded_String (Expect_Path & Prefix & Name); Tst.Result := To_Unbounded_String (Result_Path & Prefix & Name); Tst.Format := Format; Tst.Source := Format; return Tst; end Create_Test; procedure Add_Wiki_Tests is Dir : constant String := "regtests/files/wiki"; Path : constant String := Util.Tests.Get_Path (Dir); begin if Kind (Path) /= Directory then Ada.Text_IO.Put_Line ("Cannot read test directory: " & Path); end if; Start_Search (Search, Directory => Path, Pattern => "*.*", Filter => Filter); while More_Entries (Search) loop Get_Next_Entry (Search, Ent); declare Simple : constant String := Simple_Name (Ent); Ext : constant String := Ada.Directories.Extension (Simple); Tst : Test_Case_Access; Format : Wiki.Parsers.Wiki_Syntax_Type; begin if Simple /= "." and then Simple /= ".." and then Simple /= ".svn" and then Simple (Simple'Last) /= '~' then if Ext = "wiki" then Format := Wiki.Parsers.SYNTAX_GOOGLE; elsif Ext = "dotclear" then Format := Wiki.Parsers.SYNTAX_DOTCLEAR; elsif Ext = "creole" then Format := Wiki.Parsers.SYNTAX_CREOLE; elsif Ext = "phpbb" then Format := Wiki.Parsers.SYNTAX_PHPBB; elsif Ext = "mediawiki" then Format := Wiki.Parsers.SYNTAX_MEDIA_WIKI; else Format := Wiki.Parsers.SYNTAX_MIX; end if; Tst := Create_Test (Simple, Path & "/" & Simple, Format, "/wiki-html/", True); Suite.Add_Test (Tst.all'Access); Tst := Create_Test (Simple, Path & "/" & Simple, Format, "/wiki-txt/", False); Suite.Add_Test (Tst.all'Access); end if; end; end loop; end Add_Wiki_Tests; procedure Add_Import_Tests is Dir : constant String := "regtests/files/html"; Path : constant String := Util.Tests.Get_Path (Dir); begin if Kind (Path) /= Directory then Ada.Text_IO.Put_Line ("Cannot read test directory: " & Path); end if; Start_Search (Search, Directory => Path, Pattern => "*.*", Filter => Filter); while More_Entries (Search) loop Get_Next_Entry (Search, Ent); declare Simple : constant String := Simple_Name (Ent); Name : constant String := Base_Name (Simple); Tst : Test_Case_Access; begin if Simple /= "." and then Simple /= ".." and then Simple /= ".svn" and then Simple (Simple'Last) /= '~' then for Syntax in Wiki.Parsers.Wiki_Syntax_Type'Range loop case Syntax is when Wiki.Parsers.SYNTAX_CREOLE => Tst := Create_Test (Name & ".creole", Path & "/" & Simple, Syntax, "/wiki-import/", True); when Wiki.Parsers.SYNTAX_DOTCLEAR => Tst := Create_Test (Name & ".dotclear", Path & "/" & Simple, Syntax, "/wiki-import/", True); when Wiki.Parsers.SYNTAX_MEDIA_WIKI => Tst := Create_Test (Name & ".mediawiki", Path & "/" & Simple, Syntax, "/wiki-import/", True); when others => Tst := null; end case; if Tst /= null then Tst.Source := Wiki.Parsers.SYNTAX_HTML; Suite.Add_Test (Tst.all'Access); end if; end loop; end if; end; end loop; end Add_Import_Tests; begin Add_Wiki_Tests; Add_Import_Tests; end Add_Tests; end Wiki.Tests;
Update the Wiki to Wiki generation for the test
Update the Wiki to Wiki generation for the test
Ada
apache-2.0
stcarrez/ada-wiki,stcarrez/ada-wiki
35fecea52a0a088ad36276e5220a4c665d19ad91
matp/regtests/mat-readers-tests.adb
matp/regtests/mat-readers-tests.adb
----------------------------------------------------------------------- -- mat-readers-tests -- Unit tests for MAT readers -- Copyright (C) 2014, 2019 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Test_Caller; with MAT.Readers.Streams.Files; package body MAT.Readers.Tests is package Caller is new Util.Test_Caller (Test, "Files"); procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is begin Caller.Add_Test (Suite, "Test MAT.Readers.Read_File", Test_Read_File'Access); end Add_Tests; -- ------------------------------ -- Test reading a file into a string -- Reads this ada source file and checks we have read it correctly -- ------------------------------ procedure Test_Read_File (T : in out Test) is pragma Unreferenced (T); Path : constant String := Util.Tests.Get_Test_Path ("regtests/files/file-v1.dat"); Reader : MAT.Readers.Streams.Files.File_Reader_Type; begin Reader.Open (Path); Reader.Read_All; end Test_Read_File; end MAT.Readers.Tests;
----------------------------------------------------------------------- -- mat-readers-tests -- Unit tests for MAT readers -- Copyright (C) 2014, 2019, 2021 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Test_Caller; with MAT.Readers.Streams.Files; package body MAT.Readers.Tests is package Caller is new Util.Test_Caller (Test, "Files"); procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is begin Caller.Add_Test (Suite, "Test MAT.Readers.Read_File", Test_Read_File'Access); end Add_Tests; -- ------------------------------ -- Test reading a file into a string -- Reads this ada source file and checks we have read it correctly -- ------------------------------ procedure Test_Read_File (T : in out Test) is pragma Unreferenced (T); Path : constant String := Util.Tests.Get_Path ("regtests/files/file-v1.dat"); Reader : MAT.Readers.Streams.Files.File_Reader_Type; begin Reader.Open (Path); Reader.Read_All; end Test_Read_File; end MAT.Readers.Tests;
Replace Get_Test_Path by Get_Path
Replace Get_Test_Path by Get_Path
Ada
apache-2.0
stcarrez/mat,stcarrez/mat,stcarrez/mat
f8c0c5014e96fbeb001cb9d3e00e4f695ca9a456
ibv_message_passing_ada_project/source/coverage_for_ada_task/coverage_for_ada_task.adb
ibv_message_passing_ada_project/source/coverage_for_ada_task/coverage_for_ada_task.adb
-- @file coverage_for_ada_task.adb -- @date 28 May 2022 -- @author Chester Gillon -- @brief Example program to test getting coverage for an Ada task with Ada.Text_IO; procedure Coverage_For_Ada_Task is task Print_Task is entry Print; end Print_Task; task body Print_Task is begin loop select accept Print do Ada.Text_IO.Put_Line ("In task Print_Task"); end Print; or terminate; end select; end loop; end Print_Task; begin for index in 1..3 loop Print_Task.Print; end loop; Ada.Text_IO.Put_Line ("In main"); end Coverage_For_Ada_Task;
-- @file coverage_for_ada_task.adb -- @date 28 May 2022 -- @author Chester Gillon -- @brief Example program to test getting coverage for an Ada task with Ada.Text_IO; procedure Coverage_For_Ada_Task is generic Name : String; package Generic_Name is procedure Display_Name; end Generic_Name; package body Generic_Name is procedure Display_Name is begin Ada.Text_IO.Put_Line ("My name is " & Name); end Display_Name; end Generic_Name; task Print_Task is entry Print; end Print_Task; task body Print_Task is begin loop select accept Print do Ada.Text_IO.Put_Line ("In task Print_Task"); end Print; or terminate; end select; end loop; end Print_Task; package Package_A is new Generic_Name ("A"); package Package_B is new Generic_Name ("B"); begin Package_A.Display_Name; for index in 1..3 loop Print_Task.Print; end loop; Package_B.Display_Name; Ada.Text_IO.Put_Line ("In main"); end Coverage_For_Ada_Task;
Add coverage test for simple generic package
Add coverage test for simple generic package
Ada
mit
Chester-Gillon/ibv_message_passing,Chester-Gillon/ibv_message_passing,Chester-Gillon/ibv_message_passing
8afc5e243f66a5c9a1ed04c2978e9e31c731f864
src/security-policies.ads
src/security-policies.ads
----------------------------------------------------------------------- -- security-policies -- Security Policies -- Copyright (C) 2010, 2011, 2012 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Finalization; with Util.Beans.Objects; with Util.Beans.Objects.Vectors; with Util.Serialize.IO.XML; with Util.Strings; with Security.Permissions; limited with Security.Controllers; limited with Security.Contexts; package Security.Policies is type Security_Context_Access is access all Contexts.Security_Context'Class; type Controller_Access is access all Security.Controllers.Controller'Class; type Controller_Access_Array is array (Permissions.Permission_Index range <>) of Controller_Access; type Policy is new Ada.Finalization.Limited_Controlled with private; type Policy_Access is access all Policy'Class; procedure Set_Reader_Config (Pol : in out Policy; Reader : in out Util.Serialize.IO.XML.Parser) is null; -- Get the policy name. function Get_Name (From : in Policy) return String; -- Add a permission under the given permission name and associated with the controller. -- To verify the permission, the controller will be called. procedure Add_Permission (Manager : in out Policy; Name : in String; Permission : in Controller_Access); Invalid_Name : exception; Policy_Error : exception; -- Each permission is represented by a <b>Permission_Type</b> number to provide a fast -- and efficient permission check. type Permission_Type is new Natural range 0 .. 63; -- The <b>Permission_Map</b> represents a set of permissions which are granted to a user. -- Each permission is represented by a boolean in the map. The implementation is limited -- to 64 permissions. type Permission_Map is array (Permission_Type'Range) of Boolean; pragma Pack (Permission_Map); -- ------------------------------ -- Permission Manager -- ------------------------------ -- The <b>Permission_Manager</b> verifies through some policy that a permission -- is granted to a user. type Policy_Manager (Max_Policies : Positive) is new Ada.Finalization.Limited_Controlled with private; type Policy_Manager_Access is access all Policy_Manager'Class; -- Add the policy to the policy manager. After a policy is added in the manager, -- it can participate in the security policy. -- Raises Policy_Error if the policy table is full. procedure Add_Policy (Manager : in out Policy_Manager; Policy : in Policy_Access); -- Add a permission under the given permission name and associated with the controller. -- To verify the permission, the controller will be called. procedure Add_Permission (Manager : in out Policy_Manager; Name : in String; Permission : in Controller_Access); -- Get the security controller associated with the permission index <b>Index</b>. -- Returns null if there is no such controller. function Get_Controller (Manager : in Policy_Manager'Class; Index : in Permissions.Permission_Index) return Controller_Access; pragma Inline_Always (Get_Controller); -- Read the policy file procedure Read_Policy (Manager : in out Policy_Manager; File : in String); -- Initialize the permission manager. overriding procedure Initialize (Manager : in out Policy_Manager); -- Finalize the permission manager. overriding procedure Finalize (Manager : in out Policy_Manager); -- ------------------------------ -- Policy Configuration -- ------------------------------ type Policy_Config is record Id : Natural := 0; Permissions : Util.Beans.Objects.Vectors.Vector; Patterns : Util.Beans.Objects.Vectors.Vector; Manager : Policy_Manager_Access; end record; type Policy_Config_Access is access all Policy_Config; -- Setup the XML parser to read the <b>policy</b> description. For example: -- -- <policy id='1'> -- <permission>create-workspace</permission> -- <permission>admin</permission> -- <url-pattern>/workspace/create</url-pattern> -- <url-pattern>/workspace/setup/*</url-pattern> -- </policy> -- -- This policy gives access to the URL that match one of the URL pattern if the -- security context has the permission <b>create-workspace</b> or <b>admin</b>. generic Reader : in out Util.Serialize.IO.XML.Parser; Manager : in Policy_Manager_Access; package Reader_Config is Config : aliased Policy_Config; end Reader_Config; private use Util.Strings; subtype Permission_Index is Permissions.Permission_Index; type Permission_Type_Array is array (1 .. 10) of Permission_Type; type Permission_Index_Array is array (Positive range <>) of Permissions.Permission_Index; type Controller_Access_Array_Access is access all Controller_Access_Array; type Policy_Access_Array is array (Positive range <>) of Policy_Access; type Policy is new Ada.Finalization.Limited_Controlled with record Manager : Policy_Manager_Access; end record; type Policy_Manager (Max_Policies : Positive) is new Ada.Finalization.Limited_Controlled with record -- Cache : Rules_Ref_Access; -- Policies : Policy_Vector.Vector; Permissions : Controller_Access_Array_Access; Last_Index : Permission_Index := Permission_Index'First; -- The security policies. Policies : Policy_Access_Array (1 .. Max_Policies); end record; end Security.Policies;
----------------------------------------------------------------------- -- security-policies -- Security Policies -- Copyright (C) 2010, 2011, 2012 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Finalization; with Util.Beans.Objects; with Util.Beans.Objects.Vectors; with Util.Serialize.IO.XML; with Util.Strings; with Security.Permissions; limited with Security.Controllers; limited with Security.Contexts; package Security.Policies is type Security_Context_Access is access all Contexts.Security_Context'Class; type Controller_Access is access all Security.Controllers.Controller'Class; type Controller_Access_Array is array (Permissions.Permission_Index range <>) of Controller_Access; type Policy is new Ada.Finalization.Limited_Controlled with private; type Policy_Access is access all Policy'Class; procedure Set_Reader_Config (Pol : in out Policy; Reader : in out Util.Serialize.IO.XML.Parser) is null; -- Get the policy name. function Get_Name (From : in Policy) return String; -- Add a permission under the given permission name and associated with the controller. -- To verify the permission, the controller will be called. procedure Add_Permission (Manager : in out Policy; Name : in String; Permission : in Controller_Access); Invalid_Name : exception; Policy_Error : exception; -- ------------------------------ -- Permission Manager -- ------------------------------ -- The <b>Permission_Manager</b> verifies through some policy that a permission -- is granted to a user. type Policy_Manager (Max_Policies : Positive) is new Ada.Finalization.Limited_Controlled with private; type Policy_Manager_Access is access all Policy_Manager'Class; -- Add the policy to the policy manager. After a policy is added in the manager, -- it can participate in the security policy. -- Raises Policy_Error if the policy table is full. procedure Add_Policy (Manager : in out Policy_Manager; Policy : in Policy_Access); -- Add a permission under the given permission name and associated with the controller. -- To verify the permission, the controller will be called. procedure Add_Permission (Manager : in out Policy_Manager; Name : in String; Permission : in Controller_Access); -- Get the security controller associated with the permission index <b>Index</b>. -- Returns null if there is no such controller. function Get_Controller (Manager : in Policy_Manager'Class; Index : in Permissions.Permission_Index) return Controller_Access; pragma Inline_Always (Get_Controller); -- Read the policy file procedure Read_Policy (Manager : in out Policy_Manager; File : in String); -- Initialize the permission manager. overriding procedure Initialize (Manager : in out Policy_Manager); -- Finalize the permission manager. overriding procedure Finalize (Manager : in out Policy_Manager); -- ------------------------------ -- Policy Configuration -- ------------------------------ type Policy_Config is record Id : Natural := 0; Permissions : Util.Beans.Objects.Vectors.Vector; Patterns : Util.Beans.Objects.Vectors.Vector; Manager : Policy_Manager_Access; end record; type Policy_Config_Access is access all Policy_Config; -- Setup the XML parser to read the <b>policy</b> description. For example: -- -- <policy id='1'> -- <permission>create-workspace</permission> -- <permission>admin</permission> -- <url-pattern>/workspace/create</url-pattern> -- <url-pattern>/workspace/setup/*</url-pattern> -- </policy> -- -- This policy gives access to the URL that match one of the URL pattern if the -- security context has the permission <b>create-workspace</b> or <b>admin</b>. generic Reader : in out Util.Serialize.IO.XML.Parser; Manager : in Policy_Manager_Access; package Reader_Config is Config : aliased Policy_Config; end Reader_Config; private use Util.Strings; subtype Permission_Index is Permissions.Permission_Index; type Permission_Index_Array is array (Positive range <>) of Permissions.Permission_Index; type Controller_Access_Array_Access is access all Controller_Access_Array; type Policy_Access_Array is array (Positive range <>) of Policy_Access; type Policy is new Ada.Finalization.Limited_Controlled with record Manager : Policy_Manager_Access; end record; type Policy_Manager (Max_Policies : Positive) is new Ada.Finalization.Limited_Controlled with record -- Cache : Rules_Ref_Access; -- Policies : Policy_Vector.Vector; Permissions : Controller_Access_Array_Access; Last_Index : Permission_Index := Permission_Index'First; -- The security policies. Policies : Policy_Access_Array (1 .. Max_Policies); end record; end Security.Policies;
Remove unused type definitions
Remove unused type definitions
Ada
apache-2.0
stcarrez/ada-security
804488b2ec2910d6a6cdd6d975a7950648f86227
awa/plugins/awa-setup/src/awa-setup-applications.ads
awa/plugins/awa-setup/src/awa-setup-applications.ads
----------------------------------------------------------------------- -- awa-setup -- Setup and installation -- Copyright (C) 2016 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Strings.Unbounded; with ASF.Applications.Main; with ASF.Servlets.Faces; with ASF.Servlets.Files; with ASF.Server; with Util.Beans.Objects; with Util.Beans.Basic; with Util.Beans.Methods; with ADO.Drivers.Connections; package AWA.Setup.Applications is type Application is new ASF.Applications.Main.Application and Util.Beans.Basic.Bean and Util.Beans.Methods.Method_Bean with record Faces : aliased ASF.Servlets.Faces.Faces_Servlet; Files : aliased ASF.Servlets.Files.File_Servlet; Config : ASF.Applications.Config; Changed : ASF.Applications.Config; Factory : ASF.Applications.Main.Application_Factory; Path : Ada.Strings.Unbounded.Unbounded_String; Database : ADO.Drivers.Connections.Configuration; Done : Boolean := False; pragma Atomic (Done); pragma Volatile (Done); end record; -- Get the value identified by the name. function Get_Value (From : in Application; Name : in String) return Util.Beans.Objects.Object; -- Set the value identified by the name. procedure Set_Value (From : in out Application; Name : in String; Value : in Util.Beans.Objects.Object); -- Configure the database. procedure Configure_Database (From : in out Application; Outcome : in out Ada.Strings.Unbounded.Unbounded_String); -- Save the configuration. procedure Save (From : in out Application; Outcome : in out Ada.Strings.Unbounded.Unbounded_String); -- Finish the setup and exit the setup. procedure Finish (From : in out Application; Outcome : in out Ada.Strings.Unbounded.Unbounded_String); -- This bean provides some methods that can be used in a Method_Expression overriding function Get_Method_Bindings (From : in Application) return Util.Beans.Methods.Method_Binding_Array_Access; -- Enter in the application setup procedure Setup (App : in out Application; Config : in String; Server : in out ASF.Server.Container'Class); end AWA.Setup.Applications;
----------------------------------------------------------------------- -- awa-setup -- Setup and installation -- Copyright (C) 2016 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Strings.Unbounded; with ASF.Applications.Main; with ASF.Servlets.Faces; with ASF.Servlets.Files; with ASF.Server; with Util.Beans.Objects; with Util.Beans.Basic; with Util.Beans.Methods; with ADO.Drivers.Connections; package AWA.Setup.Applications is type Application is new ASF.Applications.Main.Application and Util.Beans.Basic.Bean and Util.Beans.Methods.Method_Bean with record Faces : aliased ASF.Servlets.Faces.Faces_Servlet; Files : aliased ASF.Servlets.Files.File_Servlet; Config : ASF.Applications.Config; Changed : ASF.Applications.Config; Factory : ASF.Applications.Main.Application_Factory; Path : Ada.Strings.Unbounded.Unbounded_String; Database : ADO.Drivers.Connections.Configuration; Done : Boolean := False; pragma Atomic (Done); pragma Volatile (Done); end record; -- Get the value identified by the name. function Get_Value (From : in Application; Name : in String) return Util.Beans.Objects.Object; -- Set the value identified by the name. procedure Set_Value (From : in out Application; Name : in String; Value : in Util.Beans.Objects.Object); -- Get the database connection string to be used by the application. function Get_Database_URL (From : in Application) return String; -- Configure the database. procedure Configure_Database (From : in out Application; Outcome : in out Ada.Strings.Unbounded.Unbounded_String); -- Save the configuration. procedure Save (From : in out Application; Outcome : in out Ada.Strings.Unbounded.Unbounded_String); -- Finish the setup and exit the setup. procedure Finish (From : in out Application; Outcome : in out Ada.Strings.Unbounded.Unbounded_String); -- This bean provides some methods that can be used in a Method_Expression overriding function Get_Method_Bindings (From : in Application) return Util.Beans.Methods.Method_Binding_Array_Access; -- Enter in the application setup procedure Setup (App : in out Application; Config : in String; Server : in out ASF.Server.Container'Class); end AWA.Setup.Applications;
Declare the Get_Database_URL function
Declare the Get_Database_URL function
Ada
apache-2.0
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
0c0abc5cc97a0d5553b5e81e981d9fbaad0f92e3
awa/plugins/awa-tags/src/awa-tags-beans.adb
awa/plugins/awa-tags/src/awa-tags-beans.adb
----------------------------------------------------------------------- -- awa-tags-beans -- Beans for the tags module -- Copyright (C) 2013 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Unchecked_Deallocation; with ADO.Queries; with ADO.Statements; with ADO.Sessions.Entities; package body AWA.Tags.Beans is -- ------------------------------ -- Set the value identified by the name. -- If the name cannot be found, the method should raise the No_Value -- exception. -- ------------------------------ overriding procedure Set_Value (From : in out Tag_List_Bean; Name : in String; Value : in Util.Beans.Objects.Object) is begin if Name = "entity_type" then From.Entity_Type := Util.Beans.Objects.To_Unbounded_String (Value); elsif Name = "permission" then From.Permission := Util.Beans.Objects.To_Unbounded_String (Value); end if; end Set_Value; -- ------------------------------ -- Set the entity type (database table) onto which the tags are associated. -- ------------------------------ procedure Set_Entity_Type (Into : in out Tag_List_Bean; Table : in ADO.Schemas.Class_Mapping_Access) is begin Into.Entity_Type := Ada.Strings.Unbounded.To_Unbounded_String (Table.Table.all); end Set_Entity_Type; -- ------------------------------ -- Set the permission to check before removing or adding a tag on the entity. -- ------------------------------ procedure Set_Permission (Into : in out Tag_List_Bean; Permission : in String) is begin Into.Permission := Ada.Strings.Unbounded.To_Unbounded_String (Permission); end Set_Permission; -- ------------------------------ -- Load the tags associated with the given database identifier. -- ------------------------------ procedure Load_Tags (Into : in out Tag_List_Bean; Session : in ADO.Sessions.Session; For_Entity_Id : in ADO.Identifier) is use ADO.Sessions.Entities; Entity_Type : constant String := Ada.Strings.Unbounded.To_String (Into.Entity_Type); Kind : constant ADO.Entity_Type := Find_Entity_Type (Session, Entity_Type); Query : ADO.Queries.Context; begin Query.Set_Query (AWA.Tags.Models.Query_Tag_List); Query.Bind_Param ("entity_type", Kind); Query.Bind_Param ("entity_id", For_Entity_Id); declare Stmt : ADO.Statements.Query_Statement := Session.Create_Statement (Query); begin Stmt.Execute; while Stmt.Has_Elements loop Into.List.Append (Util.Beans.Objects.To_Object (Stmt.Get_String (0))); Stmt.Next; end loop; end; end Load_Tags; -- ------------------------------ -- Set the list of tags to add. -- ------------------------------ procedure Set_Added (Into : in out Tag_List_Bean; Tags : in Util.Strings.Vectors.Vector) is begin Into.Added := Tags; end Set_Added; -- ------------------------------ -- Set the list of tags to remove. -- ------------------------------ procedure Set_Deleted (Into : in out Tag_List_Bean; Tags : in Util.Strings.Vectors.Vector) is begin Into.Deleted := Tags; end Set_Deleted; -- ------------------------------ -- Update the tags associated with the tag entity represented by <tt>For_Entity_Id</tt>. -- The list of tags defined by <tt>Set_Deleted</tt> are removed first and the list of -- tags defined by <tt>Set_Added</tt> are associated with the database entity. -- ------------------------------ procedure Update_Tags (From : in Tag_List_Bean; For_Entity_Id : in ADO.Identifier) is use type AWA.Tags.Modules.Tag_Module_Access; Entity_Type : constant String := Ada.Strings.Unbounded.To_String (From.Entity_Type); Service : AWA.Tags.Modules.Tag_Module_Access := From.Module; begin if Service = null then Service := AWA.Tags.Modules.Get_Tag_Module; end if; Service.Update_Tags (Id => For_Entity_Id, Entity_Type => Entity_Type, Permission => Ada.Strings.Unbounded.To_String (From.Permission), Added => From.Added, Deleted => From.Deleted); end Update_Tags; -- ------------------------------ -- Create the tag list bean instance. -- ------------------------------ function Create_Tag_List_Bean (Module : in AWA.Tags.Modules.Tag_Module_Access) return Util.Beans.Basic.Readonly_Bean_Access is Result : constant Tag_List_Bean_Access := new Tag_List_Bean; begin Result.Module := Module; return Result.all'Access; end Create_Tag_List_Bean; -- ------------------------------ -- Search the tags that match the search string. -- ------------------------------ procedure Search_Tags (Into : in out Tag_Search_Bean; Session : in ADO.Sessions.Session; Search : in String) is use ADO.Sessions.Entities; Entity_Type : constant String := Ada.Strings.Unbounded.To_String (Into.Entity_Type); Kind : constant ADO.Entity_Type := Find_Entity_Type (Session, Entity_Type); Query : ADO.Queries.Context; begin Query.Set_Query (AWA.Tags.Models.Query_Tag_Search); Query.Bind_Param ("entity_type", Kind); Query.Bind_Param ("search", Search & "%"); declare Stmt : ADO.Statements.Query_Statement := Session.Create_Statement (Query); begin Stmt.Execute; while Stmt.Has_Elements loop Into.List.Append (Util.Beans.Objects.To_Object (Stmt.Get_String (0))); Stmt.Next; end loop; end; end Search_Tags; -- ------------------------------ -- Set the value identified by the name. -- If the name cannot be found, the method should raise the No_Value -- exception. -- ------------------------------ overriding procedure Set_Value (From : in out Tag_Search_Bean; Name : in String; Value : in Util.Beans.Objects.Object) is begin if Name = "entity_type" then From.Entity_Type := Util.Beans.Objects.To_Unbounded_String (Value); elsif Name = "search" then declare Session : constant ADO.Sessions.Session := From.Module.Get_Session; begin From.Search_Tags (Session, Util.Beans.Objects.To_String (Value)); end; end if; end Set_Value; -- ------------------------------ -- Set the entity type (database table) onto which the tags are associated. -- ------------------------------ procedure Set_Entity_Type (Into : in out Tag_Search_Bean; Table : in ADO.Schemas.Class_Mapping_Access) is begin Into.Entity_Type := Ada.Strings.Unbounded.To_Unbounded_String (Table.Table.all); end Set_Entity_Type; -- ------------------------------ -- Create the tag search bean instance. -- ------------------------------ function Create_Tag_Search_Bean (Module : in AWA.Tags.Modules.Tag_Module_Access) return Util.Beans.Basic.Readonly_Bean_Access is Result : constant Tag_Search_Bean_Access := new Tag_Search_Bean; begin Result.Module := Module; return Result.all'Access; end Create_Tag_Search_Bean; -- ------------------------------ -- Set the value identified by the name. -- If the name cannot be found, the method should raise the No_Value -- exception. -- ------------------------------ overriding procedure Set_Value (From : in out Tag_Info_List_Bean; Name : in String; Value : in Util.Beans.Objects.Object) is begin if Name = "entity_type" then From.Entity_Type := Util.Beans.Objects.To_Unbounded_String (Value); declare Session : ADO.Sessions.Session := From.Module.Get_Session; begin From.Load_Tags (Session); end; end if; end Set_Value; -- ------------------------------ -- Load the list of tags. -- ------------------------------ procedure Load_Tags (Into : in out Tag_Info_List_Bean; Session : in out ADO.Sessions.Session) is use ADO.Sessions.Entities; Entity_Type : constant String := Ada.Strings.Unbounded.To_String (Into.Entity_Type); Kind : constant ADO.Entity_Type := Find_Entity_Type (Session, Entity_Type); Query : ADO.Queries.Context; begin Query.Set_Query (AWA.Tags.Models.Query_Tag_List_All); Query.Bind_Param ("entity_type", Kind); AWA.Tags.Models.List (Into, Session, Query); end Load_Tags; -- ------------------------------ -- Create the tag info list bean instance. -- ------------------------------ function Create_Tag_Info_List_Bean (Module : in AWA.Tags.Modules.Tag_Module_Access) return Util.Beans.Basic.Readonly_Bean_Access is Result : constant Tag_Info_List_Bean_Access := new Tag_Info_List_Bean; begin Result.Module := Module; return Result.all'Access; end Create_Tag_Info_List_Bean; -- ------------------------------ -- Get the list of tags associated with the given entity. -- Returns null if the entity does not have any tag. -- ------------------------------ function Get_Tags (From : in Entity_Tag_Map; For_Entity : in ADO.Identifier) return Util.Beans.Lists.Strings.List_Bean_Access is Pos : constant Entity_Tag_Maps.Cursor := From.Tags.Find (For_Entity); begin if Entity_Tag_Maps.Has_Element (Pos) then return Entity_Tag_Maps.Element (Pos); else return null; end if; end Get_Tags; -- ------------------------------ -- Get the list of tags associated with the given entity. -- Returns a null object if the entity does not have any tag. -- ------------------------------ function Get_Tags (From : in Entity_Tag_Map; For_Entity : in ADO.Identifier) return Util.Beans.Objects.Object is Pos : constant Entity_Tag_Maps.Cursor := From.Tags.Find (For_Entity); begin if Entity_Tag_Maps.Has_Element (Pos) then return Util.Beans.Objects.To_Object (Value => Entity_Tag_Maps.Element (Pos).all'Access, Storage => Util.Beans.Objects.STATIC); else return Util.Beans.Objects.Null_Object; end if; end Get_Tags; -- ------------------------------ -- Load the list of tags associated with a list of entities. -- ------------------------------ procedure Load_Tags (Into : in out Entity_Tag_Map; Session : in out ADO.Sessions.Session'Class; Entity_Type : in String; List : in ADO.Utils.Identifier_Vector) is Query : ADO.Queries.Context; Kind : ADO.Entity_Type; begin Into.Clear; if List.Is_Empty then return; end if; Kind := ADO.Sessions.Entities.Find_Entity_Type (Session, Entity_Type); Query.Set_Query (AWA.Tags.Models.Query_Tag_List_For_Entities); Query.Bind_Param ("entity_id_list", List); Query.Bind_Param ("entity_type", Kind); declare Stmt : ADO.Statements.Query_Statement := Session.Create_Statement (Query); Id : ADO.Identifier; List : Util.Beans.Lists.Strings.List_Bean_Access; Pos : Entity_Tag_Maps.Cursor; begin Stmt.Execute; while Stmt.Has_Elements loop Id := Stmt.Get_Identifier (0); Pos := Into.Tags.Find (Id); if not Entity_Tag_Maps.Has_Element (Pos) then List := new Util.Beans.Lists.Strings.List_Bean; Into.Tags.Insert (Id, List); else List := Entity_Tag_Maps.Element (Pos); end if; List.List.Append (Stmt.Get_String (1)); Stmt.Next; end loop; end; end Load_Tags; -- ------------------------------ -- Release the list of tags. -- ------------------------------ procedure Clear (List : in out Entity_Tag_Map) is procedure Free is new Ada.Unchecked_Deallocation (Object => Util.Beans.Lists.Strings.List_Bean'Class, Name => Util.Beans.Lists.Strings.List_Bean_Access); Pos : Entity_Tag_Maps.Cursor; Tags : Util.Beans.Lists.Strings.List_Bean_Access; begin loop Pos := List.Tags.First; exit when not Entity_Tag_Maps.Has_Element (Pos); Tags := Entity_Tag_Maps.Element (Pos); List.Tags.Delete (Pos); Free (Tags); end loop; end Clear; -- ------------------------------ -- Release the list of tags. -- ------------------------------ overriding procedure Finalize (List : in out Entity_Tag_Map) is begin List.Clear; end Finalize; end AWA.Tags.Beans;
----------------------------------------------------------------------- -- awa-tags-beans -- Beans for the tags module -- Copyright (C) 2013 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Unchecked_Deallocation; with ADO.Queries; with ADO.Statements; with ADO.Sessions.Entities; package body AWA.Tags.Beans is -- ------------------------------ -- Compare two tags on their count and name. -- ------------------------------ function "<" (Left, Right : in AWA.Tags.Models.Tag_Info) return Boolean is use type Ada.Strings.Unbounded.Unbounded_String; begin if Left.Count = Right.Count then return Left.Tag < Right.Tag; else return Left.Count < Right.Count; end if; end "<"; -- ------------------------------ -- Set the value identified by the name. -- If the name cannot be found, the method should raise the No_Value -- exception. -- ------------------------------ overriding procedure Set_Value (From : in out Tag_List_Bean; Name : in String; Value : in Util.Beans.Objects.Object) is begin if Name = "entity_type" then From.Entity_Type := Util.Beans.Objects.To_Unbounded_String (Value); elsif Name = "permission" then From.Permission := Util.Beans.Objects.To_Unbounded_String (Value); end if; end Set_Value; -- ------------------------------ -- Set the entity type (database table) onto which the tags are associated. -- ------------------------------ procedure Set_Entity_Type (Into : in out Tag_List_Bean; Table : in ADO.Schemas.Class_Mapping_Access) is begin Into.Entity_Type := Ada.Strings.Unbounded.To_Unbounded_String (Table.Table.all); end Set_Entity_Type; -- ------------------------------ -- Set the permission to check before removing or adding a tag on the entity. -- ------------------------------ procedure Set_Permission (Into : in out Tag_List_Bean; Permission : in String) is begin Into.Permission := Ada.Strings.Unbounded.To_Unbounded_String (Permission); end Set_Permission; -- ------------------------------ -- Load the tags associated with the given database identifier. -- ------------------------------ procedure Load_Tags (Into : in out Tag_List_Bean; Session : in ADO.Sessions.Session; For_Entity_Id : in ADO.Identifier) is use ADO.Sessions.Entities; Entity_Type : constant String := Ada.Strings.Unbounded.To_String (Into.Entity_Type); Kind : constant ADO.Entity_Type := Find_Entity_Type (Session, Entity_Type); Query : ADO.Queries.Context; begin Query.Set_Query (AWA.Tags.Models.Query_Tag_List); Query.Bind_Param ("entity_type", Kind); Query.Bind_Param ("entity_id", For_Entity_Id); declare Stmt : ADO.Statements.Query_Statement := Session.Create_Statement (Query); begin Stmt.Execute; while Stmt.Has_Elements loop Into.List.Append (Util.Beans.Objects.To_Object (Stmt.Get_String (0))); Stmt.Next; end loop; end; end Load_Tags; -- ------------------------------ -- Set the list of tags to add. -- ------------------------------ procedure Set_Added (Into : in out Tag_List_Bean; Tags : in Util.Strings.Vectors.Vector) is begin Into.Added := Tags; end Set_Added; -- ------------------------------ -- Set the list of tags to remove. -- ------------------------------ procedure Set_Deleted (Into : in out Tag_List_Bean; Tags : in Util.Strings.Vectors.Vector) is begin Into.Deleted := Tags; end Set_Deleted; -- ------------------------------ -- Update the tags associated with the tag entity represented by <tt>For_Entity_Id</tt>. -- The list of tags defined by <tt>Set_Deleted</tt> are removed first and the list of -- tags defined by <tt>Set_Added</tt> are associated with the database entity. -- ------------------------------ procedure Update_Tags (From : in Tag_List_Bean; For_Entity_Id : in ADO.Identifier) is use type AWA.Tags.Modules.Tag_Module_Access; Entity_Type : constant String := Ada.Strings.Unbounded.To_String (From.Entity_Type); Service : AWA.Tags.Modules.Tag_Module_Access := From.Module; begin if Service = null then Service := AWA.Tags.Modules.Get_Tag_Module; end if; Service.Update_Tags (Id => For_Entity_Id, Entity_Type => Entity_Type, Permission => Ada.Strings.Unbounded.To_String (From.Permission), Added => From.Added, Deleted => From.Deleted); end Update_Tags; -- ------------------------------ -- Create the tag list bean instance. -- ------------------------------ function Create_Tag_List_Bean (Module : in AWA.Tags.Modules.Tag_Module_Access) return Util.Beans.Basic.Readonly_Bean_Access is Result : constant Tag_List_Bean_Access := new Tag_List_Bean; begin Result.Module := Module; return Result.all'Access; end Create_Tag_List_Bean; -- ------------------------------ -- Search the tags that match the search string. -- ------------------------------ procedure Search_Tags (Into : in out Tag_Search_Bean; Session : in ADO.Sessions.Session; Search : in String) is use ADO.Sessions.Entities; Entity_Type : constant String := Ada.Strings.Unbounded.To_String (Into.Entity_Type); Kind : constant ADO.Entity_Type := Find_Entity_Type (Session, Entity_Type); Query : ADO.Queries.Context; begin Query.Set_Query (AWA.Tags.Models.Query_Tag_Search); Query.Bind_Param ("entity_type", Kind); Query.Bind_Param ("search", Search & "%"); declare Stmt : ADO.Statements.Query_Statement := Session.Create_Statement (Query); begin Stmt.Execute; while Stmt.Has_Elements loop Into.List.Append (Util.Beans.Objects.To_Object (Stmt.Get_String (0))); Stmt.Next; end loop; end; end Search_Tags; -- ------------------------------ -- Set the value identified by the name. -- If the name cannot be found, the method should raise the No_Value -- exception. -- ------------------------------ overriding procedure Set_Value (From : in out Tag_Search_Bean; Name : in String; Value : in Util.Beans.Objects.Object) is begin if Name = "entity_type" then From.Entity_Type := Util.Beans.Objects.To_Unbounded_String (Value); elsif Name = "search" then declare Session : constant ADO.Sessions.Session := From.Module.Get_Session; begin From.Search_Tags (Session, Util.Beans.Objects.To_String (Value)); end; end if; end Set_Value; -- ------------------------------ -- Set the entity type (database table) onto which the tags are associated. -- ------------------------------ procedure Set_Entity_Type (Into : in out Tag_Search_Bean; Table : in ADO.Schemas.Class_Mapping_Access) is begin Into.Entity_Type := Ada.Strings.Unbounded.To_Unbounded_String (Table.Table.all); end Set_Entity_Type; -- ------------------------------ -- Create the tag search bean instance. -- ------------------------------ function Create_Tag_Search_Bean (Module : in AWA.Tags.Modules.Tag_Module_Access) return Util.Beans.Basic.Readonly_Bean_Access is Result : constant Tag_Search_Bean_Access := new Tag_Search_Bean; begin Result.Module := Module; return Result.all'Access; end Create_Tag_Search_Bean; -- ------------------------------ -- Set the value identified by the name. -- If the name cannot be found, the method should raise the No_Value -- exception. -- ------------------------------ overriding procedure Set_Value (From : in out Tag_Info_List_Bean; Name : in String; Value : in Util.Beans.Objects.Object) is begin if Name = "entity_type" then From.Entity_Type := Util.Beans.Objects.To_Unbounded_String (Value); declare Session : ADO.Sessions.Session := From.Module.Get_Session; begin From.Load_Tags (Session); end; end if; end Set_Value; -- ------------------------------ -- Load the list of tags. -- ------------------------------ procedure Load_Tags (Into : in out Tag_Info_List_Bean; Session : in out ADO.Sessions.Session) is use ADO.Sessions.Entities; Entity_Type : constant String := Ada.Strings.Unbounded.To_String (Into.Entity_Type); Kind : constant ADO.Entity_Type := Find_Entity_Type (Session, Entity_Type); Query : ADO.Queries.Context; begin Query.Set_Query (AWA.Tags.Models.Query_Tag_List_All); Query.Bind_Param ("entity_type", Kind); AWA.Tags.Models.List (Into, Session, Query); end Load_Tags; -- ------------------------------ -- Create the tag info list bean instance. -- ------------------------------ function Create_Tag_Info_List_Bean (Module : in AWA.Tags.Modules.Tag_Module_Access) return Util.Beans.Basic.Readonly_Bean_Access is Result : constant Tag_Info_List_Bean_Access := new Tag_Info_List_Bean; begin Result.Module := Module; return Result.all'Access; end Create_Tag_Info_List_Bean; -- ------------------------------ -- Get the list of tags associated with the given entity. -- Returns null if the entity does not have any tag. -- ------------------------------ function Get_Tags (From : in Entity_Tag_Map; For_Entity : in ADO.Identifier) return Util.Beans.Lists.Strings.List_Bean_Access is Pos : constant Entity_Tag_Maps.Cursor := From.Tags.Find (For_Entity); begin if Entity_Tag_Maps.Has_Element (Pos) then return Entity_Tag_Maps.Element (Pos); else return null; end if; end Get_Tags; -- ------------------------------ -- Get the list of tags associated with the given entity. -- Returns a null object if the entity does not have any tag. -- ------------------------------ function Get_Tags (From : in Entity_Tag_Map; For_Entity : in ADO.Identifier) return Util.Beans.Objects.Object is Pos : constant Entity_Tag_Maps.Cursor := From.Tags.Find (For_Entity); begin if Entity_Tag_Maps.Has_Element (Pos) then return Util.Beans.Objects.To_Object (Value => Entity_Tag_Maps.Element (Pos).all'Access, Storage => Util.Beans.Objects.STATIC); else return Util.Beans.Objects.Null_Object; end if; end Get_Tags; -- ------------------------------ -- Load the list of tags associated with a list of entities. -- ------------------------------ procedure Load_Tags (Into : in out Entity_Tag_Map; Session : in out ADO.Sessions.Session'Class; Entity_Type : in String; List : in ADO.Utils.Identifier_Vector) is Query : ADO.Queries.Context; Kind : ADO.Entity_Type; begin Into.Clear; if List.Is_Empty then return; end if; Kind := ADO.Sessions.Entities.Find_Entity_Type (Session, Entity_Type); Query.Set_Query (AWA.Tags.Models.Query_Tag_List_For_Entities); Query.Bind_Param ("entity_id_list", List); Query.Bind_Param ("entity_type", Kind); declare Stmt : ADO.Statements.Query_Statement := Session.Create_Statement (Query); Id : ADO.Identifier; List : Util.Beans.Lists.Strings.List_Bean_Access; Pos : Entity_Tag_Maps.Cursor; begin Stmt.Execute; while Stmt.Has_Elements loop Id := Stmt.Get_Identifier (0); Pos := Into.Tags.Find (Id); if not Entity_Tag_Maps.Has_Element (Pos) then List := new Util.Beans.Lists.Strings.List_Bean; Into.Tags.Insert (Id, List); else List := Entity_Tag_Maps.Element (Pos); end if; List.List.Append (Stmt.Get_String (1)); Stmt.Next; end loop; end; end Load_Tags; -- ------------------------------ -- Release the list of tags. -- ------------------------------ procedure Clear (List : in out Entity_Tag_Map) is procedure Free is new Ada.Unchecked_Deallocation (Object => Util.Beans.Lists.Strings.List_Bean'Class, Name => Util.Beans.Lists.Strings.List_Bean_Access); Pos : Entity_Tag_Maps.Cursor; Tags : Util.Beans.Lists.Strings.List_Bean_Access; begin loop Pos := List.Tags.First; exit when not Entity_Tag_Maps.Has_Element (Pos); Tags := Entity_Tag_Maps.Element (Pos); List.Tags.Delete (Pos); Free (Tags); end loop; end Clear; -- ------------------------------ -- Release the list of tags. -- ------------------------------ overriding procedure Finalize (List : in out Entity_Tag_Map) is begin List.Clear; end Finalize; end AWA.Tags.Beans;
Implement the comparison function for tag info
Implement the comparison function for tag info
Ada
apache-2.0
tectronics/ada-awa,Letractively/ada-awa,Letractively/ada-awa,tectronics/ada-awa,tectronics/ada-awa,Letractively/ada-awa
4b50bc6a5297d3f273b768deefe3586f3d7ee799
mat/src/mat-readers-marshaller.ads
mat/src/mat-readers-marshaller.ads
----------------------------------------------------------------------- -- Marshaller -- Marshalling of data in communication buffer -- Copyright (C) 2014 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with System; with MAT.Types; with MAT.Events; package MAT.Readers.Marshaller is Buffer_Underflow_Error : exception; Buffer_Overflow_Error : exception; function Get_Raw_Uint32 (Buf : System.Address) return MAT.Types.Uint32; function Get_Uint8 (Buffer : in Buffer_Ptr) return MAT.Types.Uint8; function Get_Uint16 (Buffer : in Buffer_Ptr) return MAT.Types.Uint16; function Get_Uint32 (Buffer : in Buffer_Ptr) return MAT.Types.Uint32; function Get_Uint64 (Buffer : in Buffer_Ptr) return MAT.Types.Uint64; -- procedure Put_Uint8 (Buffer : in Buffer_Ptr; Data : in Uint8); -- procedure Put_Uint16 (Buffer : in Buffer_Ptr; Data : in Uint16); -- procedure Put_Uint32 (Buffer : in Buffer_Ptr; Data : in Uint32); generic type Target_Type is mod <>; function Get_Target_Value (Msg : in Buffer_Ptr; Kind : in MAT.Events.Attribute_Type) return Target_Type; function Get_Target_Size is new Get_Target_Value (MAT.Types.Target_Size); function Get_Target_Addr is new Get_Target_Value (MAT.Types.Target_Addr); function Get_Target_Tick is new Get_Target_Value (MAT.Types.Target_Tick_Ref); function Get_Target_Thread is new Get_Target_Value (MAT.Types.Target_Thread_Ref); procedure Skip (Msg : in Buffer_Ptr; Size : in Natural); end MAT.Readers.Marshaller;
----------------------------------------------------------------------- -- Marshaller -- Marshalling of data in communication buffer -- Copyright (C) 2014 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with System; with MAT.Types; with MAT.Events; package MAT.Readers.Marshaller is Buffer_Underflow_Error : exception; Buffer_Overflow_Error : exception; function Get_Raw_Uint32 (Buf : System.Address) return MAT.Types.Uint32; function Get_Uint8 (Buffer : in Buffer_Ptr) return MAT.Types.Uint8; function Get_Uint16 (Buffer : in Buffer_Ptr) return MAT.Types.Uint16; function Get_Uint32 (Buffer : in Buffer_Ptr) return MAT.Types.Uint32; function Get_Uint64 (Buffer : in Buffer_Ptr) return MAT.Types.Uint64; -- Extract a string from the buffer. The string starts with a byte that -- indicates the string length. function Get_String (Buffer : in Buffer_Ptr) return String; -- procedure Put_Uint8 (Buffer : in Buffer_Ptr; Data : in Uint8); -- procedure Put_Uint16 (Buffer : in Buffer_Ptr; Data : in Uint16); -- procedure Put_Uint32 (Buffer : in Buffer_Ptr; Data : in Uint32); generic type Target_Type is mod <>; function Get_Target_Value (Msg : in Buffer_Ptr; Kind : in MAT.Events.Attribute_Type) return Target_Type; function Get_Target_Size is new Get_Target_Value (MAT.Types.Target_Size); function Get_Target_Addr is new Get_Target_Value (MAT.Types.Target_Addr); function Get_Target_Tick is new Get_Target_Value (MAT.Types.Target_Tick_Ref); function Get_Target_Thread is new Get_Target_Value (MAT.Types.Target_Thread_Ref); procedure Skip (Msg : in Buffer_Ptr; Size : in Natural); end MAT.Readers.Marshaller;
Declare the Get_String operation
Declare the Get_String operation
Ada
apache-2.0
stcarrez/mat,stcarrez/mat,stcarrez/mat
a48212b4ecd5f9dfd867b2f4e3811a9a05faa3ff
mat/src/memory/mat-memory-readers.adb
mat/src/memory/mat-memory-readers.adb
----------------------------------------------------------------------- -- Memory Events - Definition and Analysis of memory events -- Copyright (C) 2014 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Log.Loggers; with MAT.Types; with MAT.Readers.Marshaller; with MAT.Memory; package body MAT.Memory.Readers is -- The logger Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("MAT.Memory.Readers"); MSG_MALLOC : constant MAT.Events.Internal_Reference := 0; MSG_FREE : constant MAT.Events.Internal_Reference := 1; MSG_REALLOC : constant MAT.Events.Internal_Reference := 2; M_SIZE : constant MAT.Events.Internal_Reference := 1; M_FRAME : constant MAT.Events.Internal_Reference := 2; M_ADDR : constant MAT.Events.Internal_Reference := 3; M_OLD_ADDR : constant MAT.Events.Internal_Reference := 4; M_THREAD : constant MAT.Events.Internal_Reference := 5; M_UNKNOWN : constant MAT.Events.Internal_Reference := 6; M_TIME : constant MAT.Events.Internal_Reference := 7; -- Defines the possible data kinds which are recognized by -- the memory unmarshaller. All others are ignored. SIZE_NAME : aliased constant String := "size"; FRAME_NAME : aliased constant String := "frame"; ADDR_NAME : aliased constant String := "pointer"; OLD_NAME : aliased constant String := "old-pointer"; THREAD_NAME : aliased constant String := "thread"; TIME_NAME : aliased constant String := "time"; Memory_Attributes : aliased constant MAT.Events.Attribute_Table := (1 => (Name => SIZE_NAME'Access, Size => 0, Kind => MAT.Events.T_SIZE_T, Ref => M_SIZE), 2 => (Name => FRAME_NAME'Access, Size => 0, Kind => MAT.Events.T_FRAME, Ref => M_FRAME), 3 => (Name => ADDR_NAME'Access, Size => 0, Kind => MAT.Events.T_POINTER, Ref => M_ADDR), 4 => (Name => OLD_NAME'Access, Size => 0, Kind => MAT.Events.T_POINTER, Ref => M_ADDR), 5 => (Name => THREAD_NAME'Access, Size => 0, Kind => MAT.Events.T_THREAD, Ref => M_THREAD), 6 => (Name => TIME_NAME'Access, Size => 0, Kind => MAT.Events.T_TIME, Ref => M_TIME)); procedure Unmarshall_Allocation (Msg : in out MAT.Readers.Message; Slot : in out Allocation; Addr : in out MAT.Types.Target_Addr; Old_Addr : in out MAT.Types.Target_Addr; Defs : in MAT.Events.Attribute_Table); procedure Process_Malloc_Message (Client : in out Memory_Servant; Addr : in MAT.Types.Target_Addr; Slot : in out Allocation); procedure Process_Free_Message (Client : in out Memory_Servant; Addr : in MAT.Types.Target_Addr; Slot : in Allocation); procedure Process_Realloc_Message (Client : in out Memory_Servant; Addr : in MAT.Types.Target_Addr; Old_Addr : in MAT.Types.Target_Addr; Slot : in Allocation); ---------------------- -- Register the reader to extract and analyze memory events. ---------------------- procedure Register (Into : in out MAT.Readers.Manager_Base'Class; Reader : in Memory_Reader_Access) is begin Into.Register_Reader (Reader.all'Access, "malloc", MSG_MALLOC, Memory_Attributes'Access); Into.Register_Reader (Reader.all'Access, "free", MSG_FREE, Memory_Attributes'Access); Into.Register_Reader (Reader.all'Access, "realloc", MSG_REALLOC, Memory_Attributes'Access); end Register; ---------------------- -- A memory allocation message is received. Register the memory -- slot in the allocated memory list. An event is posted on the -- event channel to notify the listeners that a new slot is allocated. ---------------------- procedure Process_Malloc_Message (Client : in out Memory_Servant; Addr : in MAT.Types.Target_Addr; Slot : in out Allocation) is -- Ev : MAT.Memory.Events.Memory_Event := (Kind => EV_MALLOC, Addr => Addr); begin if Log.Get_Level = Util.Log.DEBUG_LEVEL then Log.Debug ("Malloc at {0} size {1}", MAT.Types.Hex_Image (Addr), MAT.Types.Target_Size'Image (Slot.Size)); end if; Client.Data.Memory_Slots.Insert (Addr, Slot); -- Post (Client.Event_Channel, Ev); end Process_Malloc_Message; ---------------------- -- A memory deallocation message. Find the memory slot being freed -- and remove it from the allocated list. Post an event on the event -- channel to notify the listeners that the slot is removed. ---------------------- procedure Process_Free_Message (Client : in out Memory_Servant; Addr : in MAT.Types.Target_Addr; Slot : in Allocation) is It : MAT.Memory.Allocation_Maps.Cursor := Client.Data.Memory_Slots.Find (Addr); -- Ev : Memory_Event := (Kind => EV_FREE, Addr => Addr); begin if Log.Get_Level = Util.Log.DEBUG_LEVEL then Log.Debug ("Free {0}", MAT.Types.Hex_Image (Addr)); end if; if not MAT.Memory.Allocation_Maps.Has_Element (It) then -- Address is not in the map. The application is freeing -- an already freed memory or something wrong. return; end if; -- Post (Client.Event_Channel, Ev); declare Old_Slot : constant Allocation := MAT.Memory.Allocation_Maps.Element (It); begin -- Remove the memory slot from our map. Client.Data.Memory_Slots.Delete (It); Frames.Release (Old_Slot.Frame); end; end Process_Free_Message; ---------------------- -- A memory deallocation message. Find the memory slot being freed -- and remove it from the allocated list. Post an event on the event -- channel to notify the listeners that the slot is removed. ---------------------- procedure Process_Realloc_Message (Client : in out Memory_Servant; Addr : in MAT.Types.Target_Addr; Old_Addr : in MAT.Types.Target_Addr; Slot : in Allocation) is It : MAT.Memory.Allocation_Maps.Cursor := Client.Data.Memory_Slots.Find (Old_Addr); -- Ev : Memory_Event := (Kind => EV_FREE, Addr => Addr); begin if Log.Get_Level = Util.Log.DEBUG_LEVEL then Log.Debug ("Realloc {0} to {1} size {2}", MAT.Types.Hex_Image (Old_Addr), MAT.Types.Hex_Image (Addr), MAT.Types.Target_Size'Image (Slot.Size)); end if; if MAT.Memory.Allocation_Maps.Has_Element (It) then -- Address is not in the map. The application is freeing -- an already freed memory or something wrong. -- Post (Client.Event_Channel, Ev); declare Old_Slot : constant Allocation := MAT.Memory.Allocation_Maps.Element (It); begin -- Remove the memory slot from our map. Client.Data.Memory_Slots.Delete (It); Frames.Release (Old_Slot.Frame); end; end if; Client.Data.Memory_Slots.Insert (Addr, Slot); end Process_Realloc_Message; ---------------------- -- Unmarshall from the message the memory slot information. -- The data is described by the Defs table. ---------------------- procedure Unmarshall_Allocation (Msg : in out MAT.Readers.Message; Slot : in out Allocation; Addr : in out MAT.Types.Target_Addr; Old_Addr : in out MAT.Types.Target_Addr; Defs : in MAT.Events.Attribute_Table) is begin for I in Defs'Range loop declare Def : MAT.Events.Attribute renames Defs (I); begin case Def.Ref is when M_SIZE => Slot.Size := MAT.Readers.Marshaller.Get_Target_Size (Msg.Buffer, Def.Kind); when M_ADDR => Addr := MAT.Readers.Marshaller.Get_Target_Addr (Msg.Buffer, Def.Kind); when M_OLD_ADDR => Old_Addr := MAT.Readers.Marshaller.Get_Target_Addr (Msg.Buffer, Def.Kind); when M_UNKNOWN => MAT.Readers.Marshaller.Skip (Msg.Buffer, Def.Size); when others => MAT.Readers.Marshaller.Skip (Msg.Buffer, Def.Size); end case; end; end loop; end Unmarshall_Allocation; overriding procedure Dispatch (For_Servant : in out Memory_Servant; Id : in MAT.Events.Internal_Reference; Params : in MAT.Events.Const_Attribute_Table_Access; Frame : in MAT.Events.Frame_Info; Msg : in out MAT.Readers.Message) is Slot : Allocation; Addr : MAT.Types.Target_Addr := 0; Old_Addr : MAT.Types.Target_Addr := 0; begin case Id is when MSG_MALLOC => Unmarshall_Allocation (Msg, Slot, Addr, Old_Addr, Params.all); Frames.Insert (Frame => For_Servant.Data.Frames, Pc => Frame.Frame (1 .. Frame.Cur_Depth), Result => Slot.Frame); For_Servant.Data.Probe_Malloc (Addr, Slot); when MSG_FREE => Unmarshall_Allocation (Msg, Slot, Addr, Old_Addr, Params.all); For_Servant.Data.Probe_Free (Addr, Slot); when MSG_REALLOC => Unmarshall_Allocation (Msg, Slot, Addr, Old_Addr, Params.all); Frames.Insert (Frame => For_Servant.Data.Frames, Pc => Frame.Frame (1 .. Frame.Cur_Depth), Result => Slot.Frame); For_Servant.Data.Probe_Realloc (Addr, Old_Addr, Slot); when others => raise Program_Error; end case; end Dispatch; end MAT.Memory.Readers;
----------------------------------------------------------------------- -- Memory Events - Definition and Analysis of memory events -- Copyright (C) 2014 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Log.Loggers; with MAT.Types; with MAT.Readers.Marshaller; with MAT.Memory; package body MAT.Memory.Readers is -- The logger Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("MAT.Memory.Readers"); MSG_MALLOC : constant MAT.Events.Internal_Reference := 0; MSG_FREE : constant MAT.Events.Internal_Reference := 1; MSG_REALLOC : constant MAT.Events.Internal_Reference := 2; M_SIZE : constant MAT.Events.Internal_Reference := 1; M_FRAME : constant MAT.Events.Internal_Reference := 2; M_ADDR : constant MAT.Events.Internal_Reference := 3; M_OLD_ADDR : constant MAT.Events.Internal_Reference := 4; M_THREAD : constant MAT.Events.Internal_Reference := 5; M_UNKNOWN : constant MAT.Events.Internal_Reference := 6; M_TIME : constant MAT.Events.Internal_Reference := 7; -- Defines the possible data kinds which are recognized by -- the memory unmarshaller. All others are ignored. SIZE_NAME : aliased constant String := "size"; FRAME_NAME : aliased constant String := "frame"; ADDR_NAME : aliased constant String := "pointer"; OLD_NAME : aliased constant String := "old-pointer"; THREAD_NAME : aliased constant String := "thread"; TIME_NAME : aliased constant String := "time"; Memory_Attributes : aliased constant MAT.Events.Attribute_Table := (1 => (Name => SIZE_NAME'Access, Size => 0, Kind => MAT.Events.T_SIZE_T, Ref => M_SIZE), 2 => (Name => FRAME_NAME'Access, Size => 0, Kind => MAT.Events.T_FRAME, Ref => M_FRAME), 3 => (Name => ADDR_NAME'Access, Size => 0, Kind => MAT.Events.T_POINTER, Ref => M_ADDR), 4 => (Name => OLD_NAME'Access, Size => 0, Kind => MAT.Events.T_POINTER, Ref => M_ADDR), 5 => (Name => THREAD_NAME'Access, Size => 0, Kind => MAT.Events.T_THREAD, Ref => M_THREAD), 6 => (Name => TIME_NAME'Access, Size => 0, Kind => MAT.Events.T_TIME, Ref => M_TIME)); procedure Unmarshall_Allocation (Msg : in out MAT.Readers.Message; Slot : in out Allocation; Addr : in out MAT.Types.Target_Addr; Old_Addr : in out MAT.Types.Target_Addr; Defs : in MAT.Events.Attribute_Table); ---------------------- -- Register the reader to extract and analyze memory events. ---------------------- procedure Register (Into : in out MAT.Readers.Manager_Base'Class; Reader : in Memory_Reader_Access) is begin Into.Register_Reader (Reader.all'Access, "malloc", MSG_MALLOC, Memory_Attributes'Access); Into.Register_Reader (Reader.all'Access, "free", MSG_FREE, Memory_Attributes'Access); Into.Register_Reader (Reader.all'Access, "realloc", MSG_REALLOC, Memory_Attributes'Access); end Register; ---------------------- -- Unmarshall from the message the memory slot information. -- The data is described by the Defs table. ---------------------- procedure Unmarshall_Allocation (Msg : in out MAT.Readers.Message; Slot : in out Allocation; Addr : in out MAT.Types.Target_Addr; Old_Addr : in out MAT.Types.Target_Addr; Defs : in MAT.Events.Attribute_Table) is begin for I in Defs'Range loop declare Def : MAT.Events.Attribute renames Defs (I); begin case Def.Ref is when M_SIZE => Slot.Size := MAT.Readers.Marshaller.Get_Target_Size (Msg.Buffer, Def.Kind); when M_ADDR => Addr := MAT.Readers.Marshaller.Get_Target_Addr (Msg.Buffer, Def.Kind); when M_OLD_ADDR => Old_Addr := MAT.Readers.Marshaller.Get_Target_Addr (Msg.Buffer, Def.Kind); when M_UNKNOWN => MAT.Readers.Marshaller.Skip (Msg.Buffer, Def.Size); when others => MAT.Readers.Marshaller.Skip (Msg.Buffer, Def.Size); end case; end; end loop; end Unmarshall_Allocation; overriding procedure Dispatch (For_Servant : in out Memory_Servant; Id : in MAT.Events.Internal_Reference; Params : in MAT.Events.Const_Attribute_Table_Access; Frame : in MAT.Events.Frame_Info; Msg : in out MAT.Readers.Message) is Slot : Allocation; Addr : MAT.Types.Target_Addr := 0; Old_Addr : MAT.Types.Target_Addr := 0; begin case Id is when MSG_MALLOC => Unmarshall_Allocation (Msg, Slot, Addr, Old_Addr, Params.all); Frames.Insert (Frame => For_Servant.Data.Frames, Pc => Frame.Frame (1 .. Frame.Cur_Depth), Result => Slot.Frame); For_Servant.Data.Probe_Malloc (Addr, Slot); when MSG_FREE => Unmarshall_Allocation (Msg, Slot, Addr, Old_Addr, Params.all); For_Servant.Data.Probe_Free (Addr, Slot); when MSG_REALLOC => Unmarshall_Allocation (Msg, Slot, Addr, Old_Addr, Params.all); Frames.Insert (Frame => For_Servant.Data.Frames, Pc => Frame.Frame (1 .. Frame.Cur_Depth), Result => Slot.Frame); For_Servant.Data.Probe_Realloc (Addr, Old_Addr, Slot); when others => raise Program_Error; end case; end Dispatch; end MAT.Memory.Readers;
Remove the unused old Probe_xxx operations
Remove the unused old Probe_xxx operations
Ada
apache-2.0
stcarrez/mat,stcarrez/mat,stcarrez/mat
4a9c292ef1c5c440c59ccf0aa4b96c9f7eea138d
src/util-commands-consoles.ads
src/util-commands-consoles.ads
----------------------------------------------------------------------- -- util-commands-consoles -- Console interface -- Copyright (C) 2014, 2015, 2017, 2018 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Strings.Unbounded; generic type Field_Type is (<>); type Notice_Type is (<>); package Util.Commands.Consoles is type Justify_Type is (J_LEFT, -- Justify left |item | J_RIGHT, -- Justify right | item| J_CENTER, -- Justify center | item | J_RIGHT_NO_FILL -- Justify right |item| ); type Console_Type is abstract tagged limited private; type Console_Access is access all Console_Type'Class; -- Report an error message. procedure Error (Console : in out Console_Type; Message : in String) is abstract; -- Report a notice message. procedure Notice (Console : in out Console_Type; Kind : in Notice_Type; Message : in String) is abstract; -- Print the field value for the given field. procedure Print_Field (Console : in out Console_Type; Field : in Field_Type; Value : in String; Justify : in Justify_Type := J_LEFT) is abstract; -- Print the title for the given field. procedure Print_Title (Console : in out Console_Type; Field : in Field_Type; Title : in String) is abstract; -- Start a new title in a report. procedure Start_Title (Console : in out Console_Type) is abstract; -- Finish a new title in a report. procedure End_Title (Console : in out Console_Type) is abstract; -- Start a new row in a report. procedure Start_Row (Console : in out Console_Type) is abstract; -- Finish a new row in a report. procedure End_Row (Console : in out Console_Type) is abstract; -- Print the title for the given field and setup the associated field size. procedure Print_Title (Console : in out Console_Type; Field : in Field_Type; Title : in String; Length : in Positive); -- Format the integer and print it for the given field. procedure Print_Field (Console : in out Console_Type; Field : in Field_Type; Value : in Integer; Justify : in Justify_Type := J_LEFT); -- Format the integer and print it for the given field. procedure Print_Field (Console : in out Console_Type; Field : in Field_Type; Value : in Ada.Strings.Unbounded.Unbounded_String; Justify : in Justify_Type := J_LEFT); -- Get the field count that was setup through the Print_Title calls. function Get_Field_Count (Console : in Console_Type) return Natural; -- Reset the field count. procedure Clear_Fields (Console : in out Console_Type); private type Field_Size_Array is array (Field_Type) of Natural; type Field_List_Array is array (1 .. Field_Type'Pos (Field_Type'Last)) of Field_Type; type Console_Type is abstract tagged limited record Sizes : Field_Size_Array := (others => 1); Cols : Field_Size_Array := (others => 1); Fields : Field_List_Array; Field_Count : Natural := 0; end record; end Util.Commands.Consoles;
----------------------------------------------------------------------- -- util-commands-consoles -- Console interface -- Copyright (C) 2014, 2015, 2017, 2018 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Strings.Unbounded; generic type Field_Type is (<>); type Notice_Type is (<>); package Util.Commands.Consoles is type Justify_Type is (J_LEFT, -- Justify left |item | J_RIGHT, -- Justify right | item| J_CENTER, -- Justify center | item | J_RIGHT_NO_FILL -- Justify right |item| ); type Console_Type is abstract tagged limited private; type Console_Access is access all Console_Type'Class; -- Report an error message. procedure Error (Console : in out Console_Type; Message : in String) is abstract; -- Report a notice message. procedure Notice (Console : in out Console_Type; Kind : in Notice_Type; Message : in String) is abstract; -- Print the field value for the given field. procedure Print_Field (Console : in out Console_Type; Field : in Field_Type; Value : in String; Justify : in Justify_Type := J_LEFT) is abstract; -- Print the title for the given field. procedure Print_Title (Console : in out Console_Type; Field : in Field_Type; Title : in String) is abstract; -- Start a new title in a report. procedure Start_Title (Console : in out Console_Type) is abstract; -- Finish a new title in a report. procedure End_Title (Console : in out Console_Type) is abstract; -- Start a new row in a report. procedure Start_Row (Console : in out Console_Type) is abstract; -- Finish a new row in a report. procedure End_Row (Console : in out Console_Type) is abstract; -- Print the title for the given field and setup the associated field size. procedure Print_Title (Console : in out Console_Type; Field : in Field_Type; Title : in String; Length : in Positive); -- Format the integer and print it for the given field. procedure Print_Field (Console : in out Console_Type; Field : in Field_Type; Value : in Integer; Justify : in Justify_Type := J_LEFT); -- Format the integer and print it for the given field. procedure Print_Field (Console : in out Console_Type; Field : in Field_Type; Value : in Ada.Strings.Unbounded.Unbounded_String; Justify : in Justify_Type := J_LEFT); -- Get the field count that was setup through the Print_Title calls. function Get_Field_Count (Console : in Console_Type) return Natural; -- Reset the field count. procedure Clear_Fields (Console : in out Console_Type); private type Field_Size_Array is array (Field_Type) of Natural; type Field_List_Array is array (1 .. Field_Size_Array'Length) of Field_Type; type Console_Type is abstract tagged limited record Sizes : Field_Size_Array := (others => 1); Cols : Field_Size_Array := (others => 1); Fields : Field_List_Array; Field_Count : Natural := 0; end record; end Util.Commands.Consoles;
Use Field_Size_Array'Length for the length of the Field_List_Array
Use Field_Size_Array'Length for the length of the Field_List_Array
Ada
apache-2.0
stcarrez/ada-util,stcarrez/ada-util
d9674b521e660066295a91356f223097fd98e4e1
src/asf-server.ads
src/asf-server.ads
----------------------------------------------------------------------- -- asf.server -- ASF Server -- Copyright (C) 2009, 2010, 2011, 2012, 2015 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Finalization; with Ada.Strings.Unbounded; with ASF.Requests; with ASF.Responses; with ASF.Servlets; package ASF.Server is type Container is tagged limited private; -- Register the application to serve requests procedure Register_Application (Server : in out Container; URI : in String; Context : in ASF.Servlets.Servlet_Registry_Access); -- Start the applications that have been registered. procedure Start (Server : in out Container); -- Receives standard HTTP requests from the public service method and dispatches -- them to the Do_XXX methods defined in this class. This method is an HTTP-specific -- version of the Servlet.service(Request, Response) method. There's no need -- to override this method. procedure Service (Server : in Container; Request : in out Requests.Request'Class; Response : in out Responses.Response'Class); -- Get the current registry associated with the current request being processed -- by the current thread. Returns null if there is no current request. function Current return ASF.Servlets.Servlet_Registry_Access; -- Give access to the current request and response object to the <b>Process</b> -- procedure. If there is no current request for the thread, do nothing. procedure Update_Context (Process : not null access procedure (Request : in out Requests.Request'Class; Response : in out Responses.Response'Class)); private -- Binding to record the ASF applications and bind them to URI prefixes. -- It is expected that the number of ASF applications is small (1-10 per server). type Binding is record Context : ASF.Servlets.Servlet_Registry_Access; Base_URI : Ada.Strings.Unbounded.Unbounded_String; end record; type Binding_Array is array (Natural range <>) of Binding; type Binding_Array_Access is access all Binding_Array; type Container is new Ada.Finalization.Limited_Controlled with record Nb_Bindings : Natural := 0; Applications : Binding_Array_Access := null; Default : ASF.Servlets.Servlet_Registry; end record; type Request_Context is record Application : ASF.Servlets.Servlet_Registry_Access; Request : ASF.Requests.Request_Access; Response : ASF.Responses.Response_Access; end record; -- Set the current registry. This is called by <b>Service</b> once the -- registry is identified from the URI. procedure Set_Context (Context : in Request_Context); -- Release the storage. overriding procedure Finalize (Server : in out Container); end ASF.Server;
----------------------------------------------------------------------- -- asf.server -- ASF Server -- Copyright (C) 2009, 2010, 2011, 2012, 2015, 2016 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Finalization; with Ada.Strings.Unbounded; with ASF.Requests; with ASF.Responses; with ASF.Servlets; package ASF.Server is type Container is tagged limited private; -- Register the application to serve requests procedure Register_Application (Server : in out Container; URI : in String; Context : in ASF.Servlets.Servlet_Registry_Access); -- Remove the application procedure Remove_Application (Server : in out Container; Context : in ASF.Servlets.Servlet_Registry_Access); -- Start the applications that have been registered. procedure Start (Server : in out Container); -- Receives standard HTTP requests from the public service method and dispatches -- them to the Do_XXX methods defined in this class. This method is an HTTP-specific -- version of the Servlet.service(Request, Response) method. There's no need -- to override this method. procedure Service (Server : in Container; Request : in out Requests.Request'Class; Response : in out Responses.Response'Class); -- Get the current registry associated with the current request being processed -- by the current thread. Returns null if there is no current request. function Current return ASF.Servlets.Servlet_Registry_Access; -- Give access to the current request and response object to the <b>Process</b> -- procedure. If there is no current request for the thread, do nothing. procedure Update_Context (Process : not null access procedure (Request : in out Requests.Request'Class; Response : in out Responses.Response'Class)); private -- Binding to record the ASF applications and bind them to URI prefixes. -- It is expected that the number of ASF applications is small (1-10 per server). type Binding is record Context : ASF.Servlets.Servlet_Registry_Access; Base_URI : Ada.Strings.Unbounded.Unbounded_String; end record; type Binding_Array is array (Natural range <>) of Binding; type Binding_Array_Access is access all Binding_Array; type Container is new Ada.Finalization.Limited_Controlled with record Nb_Bindings : Natural := 0; Applications : Binding_Array_Access := null; Default : ASF.Servlets.Servlet_Registry; end record; type Request_Context is record Application : ASF.Servlets.Servlet_Registry_Access; Request : ASF.Requests.Request_Access; Response : ASF.Responses.Response_Access; end record; -- Set the current registry. This is called by <b>Service</b> once the -- registry is identified from the URI. procedure Set_Context (Context : in Request_Context); -- Release the storage. overriding procedure Finalize (Server : in out Container); end ASF.Server;
Declare the Remove_Application procedure
Declare the Remove_Application procedure
Ada
apache-2.0
stcarrez/ada-asf,stcarrez/ada-asf,stcarrez/ada-asf
b01023dedae876f94efb7d1cb89153a14ec2e813
mat/src/events/mat-events-targets.ads
mat/src/events/mat-events-targets.ads
----------------------------------------------------------------------- -- mat-events-targets - Events received and collected from a target -- Copyright (C) 2014 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Containers.Ordered_Maps; with Ada.Containers.Vectors; with Util.Concurrent.Counters; with MAT.Frames; package MAT.Events.Targets is type Event_Type is mod 16; type Probe_Index_Type is mod 16; type Probe_Event_Type is record Event : MAT.Events.Internal_Reference; Index : Probe_Index_Type; Time : MAT.Types.Target_Time; Thread : MAT.Types.Target_Thread_Ref; Frame : MAT.Frames.Frame_Type; Addr : MAT.Types.Target_Addr; Size : MAT.Types.Target_Size; Old_Addr : MAT.Types.Target_Addr; end record; type Target_Event is record Event : MAT.Types.Uint16; Time : MAT.Types.Target_Time; Thread : MAT.Types.Target_Thread_Ref; Frame : MAT.Frames.Frame_Type; Addr : MAT.Types.Target_Addr; Size : MAT.Types.Target_Size; Old_Addr : MAT.Types.Target_Addr; end record; package Target_Event_Vectors is new Ada.Containers.Vectors (Positive, Target_Event); subtype Target_Event_Vector is Target_Event_Vectors.Vector; subtype Target_Event_Cursor is Target_Event_Vectors.Cursor; type Target_Events is tagged limited private; type Target_Events_Access is access all Target_Events'Class; -- Add the event in the list of events and increment the event counter. procedure Insert (Target : in out Target_Events; Event : in MAT.Types.Uint16; Frame : in MAT.Events.Frame_Info); -- Add the event in the list of events and increment the event counter. procedure Insert (Target : in out Target_Events; Event : in Probe_Event_Type); procedure Get_Events (Target : in out Target_Events; Start : in MAT.Types.Target_Time; Finish : in MAT.Types.Target_Time; Into : in out Target_Event_Vector); -- Get the current event counter. function Get_Event_Counter (Target : in Target_Events) return Integer; private use type MAT.Types.Target_Time; package Event_Maps is new Ada.Containers.Ordered_Maps (Key_Type => MAT.Types.Target_Time, Element_Type => Target_Event); subtype Event_Map is Event_Maps.Map; subtype Event_Cursor is Event_Maps.Cursor; protected type Event_Collector is -- Add the event in the list of events. procedure Insert (Event : in MAT.Types.Uint16; Frame : in MAT.Events.Frame_Info); procedure Get_Events (Start : in MAT.Types.Target_Time; Finish : in MAT.Types.Target_Time; Into : in out Target_Event_Vector); private Events : Event_Map; end Event_Collector; type Target_Events is tagged limited record Events : Event_Collector; Event_Count : Util.Concurrent.Counters.Counter; end record; end MAT.Events.Targets;
----------------------------------------------------------------------- -- mat-events-targets - Events received and collected from a target -- Copyright (C) 2014 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Containers.Ordered_Maps; with Ada.Containers.Vectors; with Util.Concurrent.Counters; with MAT.Frames; package MAT.Events.Targets is type Event_Type is mod 16; type Probe_Index_Type is mod 16; type Probe_Event_Type is record Event : MAT.Types.Uint16; Index : Probe_Index_Type; Time : MAT.Types.Target_Time; Thread : MAT.Types.Target_Thread_Ref; Frame : MAT.Frames.Frame_Type; Addr : MAT.Types.Target_Addr; Size : MAT.Types.Target_Size; Old_Addr : MAT.Types.Target_Addr; end record; type Target_Event is record Event : MAT.Types.Uint16; Time : MAT.Types.Target_Time; Thread : MAT.Types.Target_Thread_Ref; Frame : MAT.Frames.Frame_Type; Addr : MAT.Types.Target_Addr; Size : MAT.Types.Target_Size; Old_Addr : MAT.Types.Target_Addr; end record; package Target_Event_Vectors is new Ada.Containers.Vectors (Positive, Target_Event); subtype Target_Event_Vector is Target_Event_Vectors.Vector; subtype Target_Event_Cursor is Target_Event_Vectors.Cursor; type Target_Events is tagged limited private; type Target_Events_Access is access all Target_Events'Class; -- Add the event in the list of events and increment the event counter. procedure Insert (Target : in out Target_Events; Event : in MAT.Types.Uint16; Frame : in MAT.Events.Frame_Info); -- Add the event in the list of events and increment the event counter. procedure Insert (Target : in out Target_Events; Event : in Probe_Event_Type); procedure Get_Events (Target : in out Target_Events; Start : in MAT.Types.Target_Time; Finish : in MAT.Types.Target_Time; Into : in out Target_Event_Vector); -- Get the current event counter. function Get_Event_Counter (Target : in Target_Events) return Integer; private use type MAT.Types.Target_Time; package Event_Maps is new Ada.Containers.Ordered_Maps (Key_Type => MAT.Types.Target_Time, Element_Type => Target_Event); subtype Event_Map is Event_Maps.Map; subtype Event_Cursor is Event_Maps.Cursor; protected type Event_Collector is -- Add the event in the list of events. procedure Insert (Event : in MAT.Types.Uint16; Frame : in MAT.Events.Frame_Info); procedure Get_Events (Start : in MAT.Types.Target_Time; Finish : in MAT.Types.Target_Time; Into : in out Target_Event_Vector); private Events : Event_Map; end Event_Collector; type Target_Events is tagged limited record Events : Event_Collector; Event_Count : Util.Concurrent.Counters.Counter; end record; end MAT.Events.Targets;
Fix the probe event definition
Fix the probe event definition
Ada
apache-2.0
stcarrez/mat,stcarrez/mat,stcarrez/mat
dd881a8bd674b564b89e420da8aab2e1542ec193
matp/src/events/mat-events-probes.ads
matp/src/events/mat-events-probes.ads
----------------------------------------------------------------------- -- mat-events-probes -- Event probes -- Copyright (C) 2014, 2015 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Containers; with Ada.Containers.Hashed_Maps; with Ada.Containers.Indefinite_Hashed_Maps; with Ada.Strings.Hash; with Ada.Finalization; with MAT.Types; with MAT.Events; with MAT.Events.Targets; with MAT.Readers; with MAT.Frames; package MAT.Events.Probes is ----------------- -- Abstract probe definition ----------------- type Probe_Type is abstract tagged limited private; type Probe_Type_Access is access all Probe_Type'Class; -- Extract the probe information from the message. procedure Extract (Probe : in Probe_Type; Params : in MAT.Events.Const_Attribute_Table_Access; Msg : in out MAT.Readers.Message_Type; Event : in out Target_Event_Type) is abstract; procedure Execute (Probe : in Probe_Type; Event : in out Target_Event_Type) is abstract; -- Update the Size and Prev_Id information in the event identified by <tt>Id</tt>. -- Update the event represented by <tt>Prev_Id</tt> so that its Next_Id refers -- to the <tt>Id</tt> event. procedure Update_Event (Probe : in Probe_Type; Id : in MAT.Events.Event_Id_Type; Size : in MAT.Types.Target_Size; Prev_Id : in MAT.Events.Event_Id_Type); ----------------- -- Probe Manager ----------------- type Probe_Manager_Type is abstract new Ada.Finalization.Limited_Controlled with private; type Probe_Manager_Type_Access is access all Probe_Manager_Type'Class; -- Initialize the probe manager instance. overriding procedure Initialize (Manager : in out Probe_Manager_Type); -- Register the probe to handle the event identified by the given name. -- The event is mapped to the given id and the attributes table is used -- to setup the mapping from the data stream attributes. procedure Register_Probe (Into : in out Probe_Manager_Type; Probe : in Probe_Type_Access; Name : in String; Id : in MAT.Events.Probe_Index_Type; Model : in MAT.Events.Const_Attribute_Table_Access); procedure Dispatch_Message (Client : in out Probe_Manager_Type; Msg : in out MAT.Readers.Message_Type); -- Read a list of event definitions from the stream and configure the reader. procedure Read_Event_Definitions (Client : in out Probe_Manager_Type; Msg : in out MAT.Readers.Message_Type); -- Get the target events. function Get_Target_Events (Client : in Probe_Manager_Type) return MAT.Events.Targets.Target_Events_Access; -- Read a message from the stream. procedure Read_Message (Reader : in out Probe_Manager_Type; Msg : in out MAT.Readers.Message_Type) is abstract; -- Get the size of a target address (4 or 8 bytes). function Get_Address_Size (Client : in Probe_Manager_Type) return MAT.Types.Target_Size; type Reader_List_Type is limited interface; type Reader_List_Type_Access is access all Reader_List_Type'Class; -- Initialize the target object to manage the memory slots, the stack frames -- and setup the reader to analyze the memory and other events. procedure Initialize (List : in out Reader_List_Type; Manager : in out Probe_Manager_Type'Class) is abstract; private type Probe_Type is abstract tagged limited record Owner : Probe_Manager_Type_Access := null; end record; -- Record a probe type Probe_Handler is record Probe : Probe_Type_Access; Id : MAT.Events.Probe_Index_Type; Attributes : MAT.Events.Const_Attribute_Table_Access; Mapping : MAT.Events.Attribute_Table_Ptr; end record; function Hash (Key : in MAT.Types.Uint16) return Ada.Containers.Hash_Type; package Probe_Maps is new Ada.Containers.Indefinite_Hashed_Maps (Key_Type => String, Element_Type => Probe_Handler, Hash => Ada.Strings.Hash, Equivalent_Keys => "="); -- Runtime handlers associated with the events. package Handler_Maps is new Ada.Containers.Hashed_Maps (Key_Type => MAT.Types.Uint16, Element_Type => Probe_Handler, Hash => Hash, Equivalent_Keys => "="); type Probe_Manager_Type is abstract new Ada.Finalization.Limited_Controlled with record Probes : Probe_Maps.Map; Handlers : Handler_Maps.Map; Version : MAT.Types.Uint16; Flags : MAT.Types.Uint16; Addr_Size : MAT.Types.Target_Size; Probe : MAT.Events.Attribute_Table_Ptr; Frame : access MAT.Events.Frame_Info; Events : MAT.Events.Targets.Target_Events_Access; Event : Target_Event_Type; Frames : MAT.Frames.Frame_Type; end record; -- Read an event definition from the stream and configure the reader. procedure Read_Definition (Client : in out Probe_Manager_Type; Msg : in out MAT.Readers.Message); end MAT.Events.Probes;
----------------------------------------------------------------------- -- mat-events-probes -- Event probes -- Copyright (C) 2014, 2015 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Containers; with Ada.Containers.Hashed_Maps; with Ada.Containers.Indefinite_Hashed_Maps; with Ada.Strings.Hash; with Ada.Finalization; with MAT.Types; with MAT.Events; with MAT.Events.Targets; with MAT.Readers; with MAT.Frames; package MAT.Events.Probes is ----------------- -- Abstract probe definition ----------------- type Probe_Type is abstract tagged limited private; type Probe_Type_Access is access all Probe_Type'Class; -- Extract the probe information from the message. procedure Extract (Probe : in Probe_Type; Params : in MAT.Events.Const_Attribute_Table_Access; Msg : in out MAT.Readers.Message_Type; Event : in out Target_Event_Type) is abstract; procedure Execute (Probe : in Probe_Type; Event : in out Target_Event_Type) is abstract; -- Update the Size and Prev_Id information in the event identified by <tt>Id</tt>. -- Update the event represented by <tt>Prev_Id</tt> so that its Next_Id refers -- to the <tt>Id</tt> event. procedure Update_Event (Probe : in Probe_Type; Id : in MAT.Events.Event_Id_Type; Size : in MAT.Types.Target_Size; Prev_Id : in MAT.Events.Event_Id_Type); ----------------- -- Probe Manager ----------------- type Probe_Manager_Type is abstract new Ada.Finalization.Limited_Controlled with private; type Probe_Manager_Type_Access is access all Probe_Manager_Type'Class; -- Initialize the probe manager instance. overriding procedure Initialize (Manager : in out Probe_Manager_Type); -- Register the probe to handle the event identified by the given name. -- The event is mapped to the given id and the attributes table is used -- to setup the mapping from the data stream attributes. procedure Register_Probe (Into : in out Probe_Manager_Type; Probe : in Probe_Type_Access; Name : in String; Id : in MAT.Events.Probe_Index_Type; Model : in MAT.Events.Const_Attribute_Table_Access); procedure Dispatch_Message (Client : in out Probe_Manager_Type; Msg : in out MAT.Readers.Message_Type); -- Read a list of event definitions from the stream and configure the reader. procedure Read_Event_Definitions (Client : in out Probe_Manager_Type; Msg : in out MAT.Readers.Message_Type); -- Get the target events. function Get_Target_Events (Client : in Probe_Manager_Type) return MAT.Events.Targets.Target_Events_Access; -- Read a message from the stream. procedure Read_Message (Reader : in out Probe_Manager_Type; Msg : in out MAT.Readers.Message_Type) is abstract; -- Get the size of a target address (4 or 8 bytes). function Get_Address_Size (Client : in Probe_Manager_Type) return MAT.Events.Attribute_Type; type Reader_List_Type is limited interface; type Reader_List_Type_Access is access all Reader_List_Type'Class; -- Initialize the target object to manage the memory slots, the stack frames -- and setup the reader to analyze the memory and other events. procedure Initialize (List : in out Reader_List_Type; Manager : in out Probe_Manager_Type'Class) is abstract; private type Probe_Type is abstract tagged limited record Owner : Probe_Manager_Type_Access := null; end record; -- Record a probe type Probe_Handler is record Probe : Probe_Type_Access; Id : MAT.Events.Probe_Index_Type; Attributes : MAT.Events.Const_Attribute_Table_Access; Mapping : MAT.Events.Attribute_Table_Ptr; end record; function Hash (Key : in MAT.Types.Uint16) return Ada.Containers.Hash_Type; package Probe_Maps is new Ada.Containers.Indefinite_Hashed_Maps (Key_Type => String, Element_Type => Probe_Handler, Hash => Ada.Strings.Hash, Equivalent_Keys => "="); -- Runtime handlers associated with the events. package Handler_Maps is new Ada.Containers.Hashed_Maps (Key_Type => MAT.Types.Uint16, Element_Type => Probe_Handler, Hash => Hash, Equivalent_Keys => "="); type Probe_Manager_Type is abstract new Ada.Finalization.Limited_Controlled with record Probes : Probe_Maps.Map; Handlers : Handler_Maps.Map; Version : MAT.Types.Uint16; Flags : MAT.Types.Uint16; Addr_Size : MAT.Events.Attribute_Type; Probe : MAT.Events.Attribute_Table_Ptr; Frame : access MAT.Events.Frame_Info; Events : MAT.Events.Targets.Target_Events_Access; Event : Target_Event_Type; Frames : MAT.Frames.Frame_Type; end record; -- Read an event definition from the stream and configure the reader. procedure Read_Definition (Client : in out Probe_Manager_Type; Msg : in out MAT.Readers.Message); end MAT.Events.Probes;
Use MAT.Events.Attribute_Type for the address size
Use MAT.Events.Attribute_Type for the address size
Ada
apache-2.0
stcarrez/mat,stcarrez/mat,stcarrez/mat
26441e9cc26bebfa7c85b0711f59facb415ba5fd
t0032.adb
t0032.adb
-- t0032.adb - Tue Jan 14 20:20:46 2014 -- -- (c) Warren W. Gay VE3WWG [email protected] -- -- Protected under the following license: -- GNU LESSER GENERAL PUBLIC LICENSE Version 2.1, February 1999 with Ada.Text_IO; with Posix; use Posix; procedure T0032 is use Ada.Text_IO; Res : s_rusage; Error : errno_t; pragma Volatile(Error); begin Put_Line("Test 0032 - Getrlimit/Setrlimit"); Error := 0; for X in 0..999999 loop if Error < 32000 then Error := Error + 1; else Error := 0; end if; end loop; Getrusage(RUSAGE_SELF,Res,Error); pragma Assert(Error = 0); pragma Assert(Res.ru_utime.tv_sec >= 0); pragma Assert(Res.ru_utime.tv_usec > 0 or else Res.ru_utime.tv_sec > 0); Put_Line("Test 0032 Passed."); end T0032;
-- t0032.adb - Tue Jan 14 20:20:46 2014 -- -- (c) Warren W. Gay VE3WWG [email protected] -- -- Protected under the following license: -- GNU LESSER GENERAL PUBLIC LICENSE Version 2.1, February 1999 with Ada.Text_IO; with Posix; use Posix; procedure T0032 is use Ada.Text_IO; Res : s_rusage; Error : errno_t; pragma Volatile(Error); begin Put_Line("Test 0032 - Getrlimit/Setrlimit"); Error := 0; for X in 0..9999999 loop if Error < 32000 then Error := Error + 1; else Error := 0; end if; end loop; Getrusage(RUSAGE_SELF,Res,Error); pragma Assert(Error = 0); pragma Assert(Res.ru_utime.tv_sec >= 0); pragma Assert(Res.ru_utime.tv_usec > 0 or else Res.ru_utime.tv_sec > 0); Put_Line("Test 0032 Passed."); end T0032;
Increase loop for FreeBSD test
Increase loop for FreeBSD test
Ada
lgpl-2.1
ve3wwg/adafpx,ve3wwg/adafpx
c2b048bb483c3fa2a0340694633066ac87afa5b1
src/repository.adb
src/repository.adb
-- This file is covered by the Internet Software Consortium (ISC) License -- Reference: ../License.txt with Unix; with Parameters; with HelperText; with File_Operations; with PortScan.Scan; with PortScan.Operations; with Ada.Characters.Latin_1; with Ada.Directories; with Ada.Exceptions; with Ada.Text_IO; package body Repository is package PM renames Parameters; package HT renames HelperText; package FOP renames File_Operations; package LAT renames Ada.Characters.Latin_1; package DIR renames Ada.Directories; package EX renames Ada.Exceptions; package TIO renames Ada.Text_IO; -------------------------------------------------------------------------------------------- -- signing_command -------------------------------------------------------------------------------------------- function signing_command return String is filename : constant String := get_file_prefix & "-signing_command"; begin return FOP.head_n1 (filename); end signing_command; -------------------------------------------------------------------------------------------- -- profile_fingerprint -------------------------------------------------------------------------------------------- function profile_fingerprint return String is filename : constant String := get_file_prefix & "-fingerprint"; begin return FOP.head_n1 (filename); end profile_fingerprint; -------------------------------------------------------------------------------------------- -- valid_signing_command -------------------------------------------------------------------------------------------- function valid_signing_command return Boolean is file_prefix : constant String := get_file_prefix; fingerprint : constant String := file_prefix & "fingerprint"; ext_command : constant String := file_prefix & "signing_command"; found_finger : constant Boolean := DIR.Exists (fingerprint); found_command : constant Boolean := DIR.Exists (ext_command); begin if found_finger and then found_command then if HT.IsBlank (FOP.head_n1 (fingerprint)) or else HT.IsBlank (FOP.head_n1 (ext_command)) then TIO.Put_Line ("At least one of the profile signing command files is blank"); TIO.Put_Line (sorry); return False; end if; return True; end if; if found_finger then TIO.Put_Line ("The profile fingerprint was found but not the signing command"); TIO.Put_Line (sorry); elsif found_command then TIO.Put_Line ("The profile signing command was found but not the fingerprint"); TIO.Put_Line (sorry); end if; return False; end valid_signing_command; -------------------------------------------------------------------------------------------- -- acceptable_RSA_signing_support -------------------------------------------------------------------------------------------- function acceptable_RSA_signing_support return Boolean is file_prefix : constant String := get_file_prefix; key_private : constant String := file_prefix & "private.key"; key_public : constant String := file_prefix & "public.key"; found_private : constant Boolean := DIR.Exists (key_private); found_public : constant Boolean := DIR.Exists (key_public); begin if not found_private and then not found_public then return True; end if; if found_public and then not found_private then TIO.Put_Line ("A public RSA key file has been found without a " & "corresponding private key file."); TIO.Put_Line (sorry); return True; end if; if found_private and then not found_public then TIO.Put_Line ("A private RSA key file has been found without a " & "corresponding public key file."); TIO.Put_Line (sorry); return True; end if; declare mode : constant String := file_permissions (key_private); begin if mode /= "400" then TIO.Put_Line ("The private RSA key file has insecure file permissions (" & mode & ")"); TIO.Put_Line ("Please change the file mode of " & key_private & " to 400 before continuing."); return False; end if; end; return True; end acceptable_RSA_signing_support; -------------------------------------------------------------------------------------------- -- set_raven_conf_with_RSA -------------------------------------------------------------------------------------------- function set_raven_conf_with_RSA return Boolean is file_prefix : constant String := get_file_prefix; key_private : constant String := file_prefix & "private.key"; key_public : constant String := file_prefix & "public.key"; found_private : constant Boolean := DIR.Exists (key_private); found_public : constant Boolean := DIR.Exists (key_public); begin return found_public and then found_private and then file_permissions (key_private) = "400"; end set_raven_conf_with_RSA; -------------------------------------------------------------------------------------------- -- get_file_prefix -------------------------------------------------------------------------------------------- function get_file_prefix return String is begin return PM.raven_confdir & "/" & HT.USS (PM.configuration.profile) & "-"; end get_file_prefix; -------------------------------------------------------------------------------------------- -- file_permissions -------------------------------------------------------------------------------------------- function file_permissions (full_path : String) return String is command : constant String := HT.USS (PM.configuration.dir_sysroot) & "/usr/bin/stat -f %Lp " & full_path; content : HT.Text; status : Integer; begin content := Unix.piped_command (command, status); if status /= 0 then return "000"; end if; return HT.first_line (HT.USS (content)); end file_permissions; -------------------------------------------------------------------------------------------- -- host_pkg8_conservative_upgrade_set -------------------------------------------------------------------------------------------- function host_pkg8_conservative_upgrade_set return Boolean is command : constant String := host_pkg8 & " config CONSERVATIVE_UPGRADE"; content : HT.Text; status : Integer; begin content := Unix.piped_command (command, status); return (HT.first_line (HT.USS (content)) = "yes"); end host_pkg8_conservative_upgrade_set; -------------------------------------------------------------------------------------------- -- get_repos_dir -------------------------------------------------------------------------------------------- function get_repos_dir return String is command : String := host_pkg8 & " config repos_dir"; status : Integer; markers : HT.Line_Markers; repdirs : String := HT.USS (Unix.piped_command (command, status)); default : constant String := host_localbase & "/etc/pkg/repos"; begin if status /= 0 then -- command failed, use default return default; end if; HT.initialize_markers (repdirs, markers); loop exit when not HT.next_line_present (repdirs, markers); declare line : constant String := HT.extract_line (repdirs, markers); begin if line /= "/etc/pkg" then return line; end if; end; end loop; -- fallback, use default return default; end get_repos_dir; -------------------------------------------------------------------------------------------- -- write_pkg_repos_configuration_file -------------------------------------------------------------------------------------------- function write_pkg_repos_configuration_file return Boolean is repdir : constant String := get_repos_dir; target : constant String := repdir & "/00_raven.conf"; pkgdir : constant String := HT.USS (PM.configuration.dir_packages); pubkey : constant String := get_file_prefix & "-public.key"; keydir : constant String := PM.raven_confdir & "/keys"; tstdir : constant String := keydir & "/trusted"; autgen : constant String := "# Automatically generated." & LAT.LF; fpfile : constant String := tstdir & "/fingerprint." & HT.USS (PM.configuration.profile); handle : TIO.File_Type; vscmd : Boolean := False; begin if DIR.Exists (target) then DIR.Delete_File (target); elsif not DIR.Exists (repdir) then DIR.Create_Path (repdir); end if; TIO.Create (File => handle, Mode => TIO.Out_File, Name => target); TIO.Put_Line (handle, autgen); TIO.Put_Line (handle, "Raven: {"); TIO.Put_Line (handle, " url : file://" & pkgdir & ","); TIO.Put_Line (handle, " priority : 0,"); TIO.Put_Line (handle, " enabled : yes,"); if valid_signing_command then vscmd := True; TIO.Put_Line (handle, " signature_type : FINGERPRINTS,"); TIO.Put_Line (handle, " fingerprints : " & keydir); elsif set_raven_conf_with_RSA then TIO.Put_Line (handle, " signature_type : PUBKEY,"); TIO.Put_Line (handle, " pubkey : " & LAT.Quotation & pubkey & LAT.Quotation); end if; TIO.Put_Line (handle, "}"); TIO.Close (handle); if vscmd then if DIR.Exists (fpfile) then DIR.Delete_File (fpfile); elsif not DIR.Exists (tstdir) then DIR.Create_Path (tstdir); end if; TIO.Create (File => handle, Mode => TIO.Out_File, Name => fpfile); TIO.Put_Line (handle, autgen); TIO.Put_Line (handle, "function : sha256"); TIO.Put_Line (handle, "fingerprint : " & profile_fingerprint); TIO.Close (handle); end if; return True; exception when others => TIO.Put_Line ("Error: failed to create " & target); if TIO.Is_Open (handle) then TIO.Close (handle); end if; return False; end write_pkg_repos_configuration_file; -------------------------------------------------------------------------------------------- -- rebuild_local_respository -------------------------------------------------------------------------------------------- procedure preclean_repository (repository : String) is begin if PortScan.Scan.scan_repository (repository) then PortScan.Operations.eliminate_obsolete_packages; end if; end preclean_repository; -------------------------------------------------------------------------------------------- -- rebuild_local_respository -------------------------------------------------------------------------------------------- procedure rebuild_local_respository (remove_invalid_packages : Boolean) is ------------------------------------------------------------ -- fully_scan_tree must be executed before this routine -- ------------------------------------------------------------ repo : constant String := HT.USS (PM.configuration.dir_repository); main : constant String := HT.USS (PM.configuration.dir_packages); xz_meta : constant String := main & "/meta.tzst"; xz_digest : constant String := main & "/digests.tzst"; xz_pkgsite : constant String := main & "/packagesite.tzst"; bs_error : constant String := "Rebuild Repository: Failed to bootstrap builder"; build_res : Boolean; begin if remove_invalid_packages then preclean_repository (repo); end if; if DIR.Exists (xz_meta) then DIR.Delete_File (xz_meta); end if; if DIR.Exists (xz_digest) then DIR.Delete_File (xz_digest); end if; if DIR.Exists (xz_pkgsite) then DIR.Delete_File (xz_pkgsite); end if; if valid_signing_command then build_res := build_repository (signing_command); elsif acceptable_RSA_signing_support then build_res := build_repository; else build_res := False; end if; if build_res then TIO.Put_Line ("Local repository successfully rebuilt."); else TIO.Put_Line ("Failed to rebuild repository."); end if; end rebuild_local_respository; -------------------------------------------------------------------------------------------- -- silent_exec -------------------------------------------------------------------------------------------- procedure silent_exec (command : String) is cmd_output : HT.Text; success : Boolean := Unix.piped_mute_command (command, cmd_output); begin if not success then raise bad_command with command & " => failed: " & HT.USS (cmd_output); end if; end silent_exec; -------------------------------------------------------------------------------------------- -- build_repository -------------------------------------------------------------------------------------------- function build_repository (sign_command : String := "") return Boolean is key_private : constant String := get_file_prefix & "private.key"; use_key : constant Boolean := DIR.Exists (key_private); use_cmd : constant Boolean := (sign_command /= ""); pkgdir : constant String := HT.USS (PM.configuration.dir_packages); command : constant String := host_pkg8 & " repo -q " & pkgdir; sc_cmd : constant String := command & " signing_command: " & sign_command; cmd_out : HT.Text; begin if use_key then TIO.Put_Line ("Rebuilding RSA-signed local repository ..."); silent_exec (command & " " & key_private); elsif use_cmd then TIO.Put_Line ("Rebuilding externally-signed local repository ..."); silent_exec (sc_cmd); else TIO.Put_Line ("Rebuilding local repository ..."); silent_exec (command); end if; return True; exception when quepaso : others => TIO.Put_Line (EX.Exception_Message (quepaso)); return False; end build_repository; end Repository;
-- This file is covered by the Internet Software Consortium (ISC) License -- Reference: ../License.txt with Unix; with Parameters; with HelperText; with File_Operations; with PortScan.Scan; with PortScan.Operations; with Ada.Characters.Latin_1; with Ada.Directories; with Ada.Exceptions; with Ada.Text_IO; package body Repository is package PM renames Parameters; package HT renames HelperText; package FOP renames File_Operations; package LAT renames Ada.Characters.Latin_1; package DIR renames Ada.Directories; package EX renames Ada.Exceptions; package TIO renames Ada.Text_IO; -------------------------------------------------------------------------------------------- -- signing_command -------------------------------------------------------------------------------------------- function signing_command return String is filename : constant String := get_file_prefix & "-signing_command"; begin return FOP.head_n1 (filename); end signing_command; -------------------------------------------------------------------------------------------- -- profile_fingerprint -------------------------------------------------------------------------------------------- function profile_fingerprint return String is filename : constant String := get_file_prefix & "-fingerprint"; begin return FOP.head_n1 (filename); end profile_fingerprint; -------------------------------------------------------------------------------------------- -- valid_signing_command -------------------------------------------------------------------------------------------- function valid_signing_command return Boolean is file_prefix : constant String := get_file_prefix; fingerprint : constant String := file_prefix & "fingerprint"; ext_command : constant String := file_prefix & "signing_command"; found_finger : constant Boolean := DIR.Exists (fingerprint); found_command : constant Boolean := DIR.Exists (ext_command); begin if found_finger and then found_command then if HT.IsBlank (FOP.head_n1 (fingerprint)) or else HT.IsBlank (FOP.head_n1 (ext_command)) then TIO.Put_Line ("At least one of the profile signing command files is blank"); TIO.Put_Line (sorry); return False; end if; return True; end if; if found_finger then TIO.Put_Line ("The profile fingerprint was found but not the signing command"); TIO.Put_Line (sorry); elsif found_command then TIO.Put_Line ("The profile signing command was found but not the fingerprint"); TIO.Put_Line (sorry); end if; return False; end valid_signing_command; -------------------------------------------------------------------------------------------- -- acceptable_RSA_signing_support -------------------------------------------------------------------------------------------- function acceptable_RSA_signing_support return Boolean is file_prefix : constant String := get_file_prefix; key_private : constant String := file_prefix & "private.key"; key_public : constant String := file_prefix & "public.key"; found_private : constant Boolean := DIR.Exists (key_private); found_public : constant Boolean := DIR.Exists (key_public); begin if not found_private and then not found_public then return True; end if; if found_public and then not found_private then TIO.Put_Line ("A public RSA key file has been found without a " & "corresponding private key file."); TIO.Put_Line (sorry); return True; end if; if found_private and then not found_public then TIO.Put_Line ("A private RSA key file has been found without a " & "corresponding public key file."); TIO.Put_Line (sorry); return True; end if; declare mode : constant String := file_permissions (key_private); begin if mode /= "400" then TIO.Put_Line ("The private RSA key file has insecure file permissions (" & mode & ")"); TIO.Put_Line ("Please change the file mode of " & key_private & " to 400 before continuing."); return False; end if; end; return True; end acceptable_RSA_signing_support; -------------------------------------------------------------------------------------------- -- set_raven_conf_with_RSA -------------------------------------------------------------------------------------------- function set_raven_conf_with_RSA return Boolean is file_prefix : constant String := get_file_prefix; key_private : constant String := file_prefix & "private.key"; key_public : constant String := file_prefix & "public.key"; found_private : constant Boolean := DIR.Exists (key_private); found_public : constant Boolean := DIR.Exists (key_public); begin return found_public and then found_private and then file_permissions (key_private) = "400"; end set_raven_conf_with_RSA; -------------------------------------------------------------------------------------------- -- get_file_prefix -------------------------------------------------------------------------------------------- function get_file_prefix return String is begin return PM.raven_confdir & "/" & HT.USS (PM.configuration.profile) & "-"; end get_file_prefix; -------------------------------------------------------------------------------------------- -- file_permissions -------------------------------------------------------------------------------------------- function file_permissions (full_path : String) return String is function OS_command return String; content : HT.Text; status : Integer; function OS_command return String is begin case platform_type is when dragonfly | freebsd | netbsd | openbsd | macos => return "/usr/bin/stat -f %Lp "; when linux | sunos => return "/usr/bin/stat -L --format=%a "; end case; end OS_command; command : constant String := HT.USS (PM.configuration.dir_sysroot) & OS_command & full_path; begin content := Unix.piped_command (command, status); if status /= 0 then return "000"; end if; return HT.first_line (HT.USS (content)); end file_permissions; -------------------------------------------------------------------------------------------- -- host_pkg8_conservative_upgrade_set -------------------------------------------------------------------------------------------- function host_pkg8_conservative_upgrade_set return Boolean is command : constant String := host_pkg8 & " config CONSERVATIVE_UPGRADE"; content : HT.Text; status : Integer; begin content := Unix.piped_command (command, status); return (HT.first_line (HT.USS (content)) = "yes"); end host_pkg8_conservative_upgrade_set; -------------------------------------------------------------------------------------------- -- get_repos_dir -------------------------------------------------------------------------------------------- function get_repos_dir return String is command : String := host_pkg8 & " config repos_dir"; status : Integer; markers : HT.Line_Markers; repdirs : String := HT.USS (Unix.piped_command (command, status)); default : constant String := host_localbase & "/etc/pkg/repos"; begin if status /= 0 then -- command failed, use default return default; end if; HT.initialize_markers (repdirs, markers); loop exit when not HT.next_line_present (repdirs, markers); declare line : constant String := HT.extract_line (repdirs, markers); begin if line /= "/etc/pkg" then return line; end if; end; end loop; -- fallback, use default return default; end get_repos_dir; -------------------------------------------------------------------------------------------- -- write_pkg_repos_configuration_file -------------------------------------------------------------------------------------------- function write_pkg_repos_configuration_file return Boolean is repdir : constant String := get_repos_dir; target : constant String := repdir & "/00_raven.conf"; pkgdir : constant String := HT.USS (PM.configuration.dir_packages); pubkey : constant String := get_file_prefix & "-public.key"; keydir : constant String := PM.raven_confdir & "/keys"; tstdir : constant String := keydir & "/trusted"; autgen : constant String := "# Automatically generated." & LAT.LF; fpfile : constant String := tstdir & "/fingerprint." & HT.USS (PM.configuration.profile); handle : TIO.File_Type; vscmd : Boolean := False; begin if DIR.Exists (target) then DIR.Delete_File (target); elsif not DIR.Exists (repdir) then DIR.Create_Path (repdir); end if; TIO.Create (File => handle, Mode => TIO.Out_File, Name => target); TIO.Put_Line (handle, autgen); TIO.Put_Line (handle, "Raven: {"); TIO.Put_Line (handle, " url : file://" & pkgdir & ","); TIO.Put_Line (handle, " priority : 0,"); TIO.Put_Line (handle, " enabled : yes,"); if valid_signing_command then vscmd := True; TIO.Put_Line (handle, " signature_type : FINGERPRINTS,"); TIO.Put_Line (handle, " fingerprints : " & keydir); elsif set_raven_conf_with_RSA then TIO.Put_Line (handle, " signature_type : PUBKEY,"); TIO.Put_Line (handle, " pubkey : " & LAT.Quotation & pubkey & LAT.Quotation); end if; TIO.Put_Line (handle, "}"); TIO.Close (handle); if vscmd then if DIR.Exists (fpfile) then DIR.Delete_File (fpfile); elsif not DIR.Exists (tstdir) then DIR.Create_Path (tstdir); end if; TIO.Create (File => handle, Mode => TIO.Out_File, Name => fpfile); TIO.Put_Line (handle, autgen); TIO.Put_Line (handle, "function : sha256"); TIO.Put_Line (handle, "fingerprint : " & profile_fingerprint); TIO.Close (handle); end if; return True; exception when others => TIO.Put_Line ("Error: failed to create " & target); if TIO.Is_Open (handle) then TIO.Close (handle); end if; return False; end write_pkg_repos_configuration_file; -------------------------------------------------------------------------------------------- -- rebuild_local_respository -------------------------------------------------------------------------------------------- procedure preclean_repository (repository : String) is begin if PortScan.Scan.scan_repository (repository) then PortScan.Operations.eliminate_obsolete_packages; end if; end preclean_repository; -------------------------------------------------------------------------------------------- -- rebuild_local_respository -------------------------------------------------------------------------------------------- procedure rebuild_local_respository (remove_invalid_packages : Boolean) is ------------------------------------------------------------ -- fully_scan_tree must be executed before this routine -- ------------------------------------------------------------ repo : constant String := HT.USS (PM.configuration.dir_repository); main : constant String := HT.USS (PM.configuration.dir_packages); xz_meta : constant String := main & "/meta.tzst"; xz_digest : constant String := main & "/digests.tzst"; xz_pkgsite : constant String := main & "/packagesite.tzst"; bs_error : constant String := "Rebuild Repository: Failed to bootstrap builder"; build_res : Boolean; begin if remove_invalid_packages then preclean_repository (repo); end if; if DIR.Exists (xz_meta) then DIR.Delete_File (xz_meta); end if; if DIR.Exists (xz_digest) then DIR.Delete_File (xz_digest); end if; if DIR.Exists (xz_pkgsite) then DIR.Delete_File (xz_pkgsite); end if; if valid_signing_command then build_res := build_repository (signing_command); elsif acceptable_RSA_signing_support then build_res := build_repository; else build_res := False; end if; if build_res then TIO.Put_Line ("Local repository successfully rebuilt."); else TIO.Put_Line ("Failed to rebuild repository."); end if; end rebuild_local_respository; -------------------------------------------------------------------------------------------- -- silent_exec -------------------------------------------------------------------------------------------- procedure silent_exec (command : String) is cmd_output : HT.Text; success : Boolean := Unix.piped_mute_command (command, cmd_output); begin if not success then raise bad_command with command & " => failed: " & HT.USS (cmd_output); end if; end silent_exec; -------------------------------------------------------------------------------------------- -- build_repository -------------------------------------------------------------------------------------------- function build_repository (sign_command : String := "") return Boolean is key_private : constant String := get_file_prefix & "private.key"; use_key : constant Boolean := DIR.Exists (key_private); use_cmd : constant Boolean := (sign_command /= ""); pkgdir : constant String := HT.USS (PM.configuration.dir_packages); command : constant String := host_pkg8 & " repo -q " & pkgdir; sc_cmd : constant String := command & " signing_command: " & sign_command; cmd_out : HT.Text; begin if use_key then TIO.Put_Line ("Rebuilding RSA-signed local repository ..."); silent_exec (command & " " & key_private); elsif use_cmd then TIO.Put_Line ("Rebuilding externally-signed local repository ..."); silent_exec (sc_cmd); else TIO.Put_Line ("Rebuilding local repository ..."); silent_exec (command); end if; return True; exception when quepaso : others => TIO.Put_Line (EX.Exception_Message (quepaso)); return False; end build_repository; end Repository;
Fix file mode detection on linux and sunos
Fix file mode detection on linux and sunos
Ada
isc
jrmarino/ravenadm,jrmarino/ravenadm,jrmarino/ravenadm
a538515d8864b675220bceed3328b1263fd0d94f
ada/step8_macros.adb
ada/step8_macros.adb
with Ada.Command_Line; with Ada.Exceptions; with Ada.Text_IO; with Ada.IO_Exceptions; with Core; with Envs; with Evaluation; with Printer; with Reader; with Types; procedure Step8_Macros is function Read (Param : String) return Types.Mal_Handle is begin return Reader.Read_Str (Param); end Read; -- Eval can't be here because there are function pointers that point -- at it. Thus it must be at library level. See evaluation.ads function Print (Param : Types.Mal_Handle) return String is begin return Printer.Pr_Str (Param); end Print; function Rep (Param : String) return String is AST, Evaluated_AST : Types.Mal_Handle; begin AST := Read (Param); if Types.Is_Null (AST) then return ""; else Evaluated_AST := Evaluation.Eval (AST, Envs.Get_Current); return Print (Evaluated_AST); end if; end Rep; S : String (1..Reader.Max_Line_Len); Last : Natural; Cmd_Args : Natural; Command_Args : Types.Mal_Handle; Command_List : Types.List_Ptr; File_Processed : Boolean := False; begin -- Core init also creates the first environment. -- This is needed for the def!'s below. Core.Init; declare Not_S : String := Rep ("(def! not (fn* (a) (if a false true)))"); LF_S : String := Rep ("(def! load-file (fn* (f) (eval (read-string (str ""(do "" (slurp f) "")"")))))"); pragma Unreferenced (Not_S, LF_S); begin null; end; Cmd_Args := 0; Command_Args := Types.New_List_Mal_Type (Types.List_List); Command_List := Types.Deref_List (Command_Args); while Ada.Command_Line.Argument_Count > Cmd_Args loop Cmd_Args := Cmd_Args + 1; if Ada.Command_Line.Argument (Cmd_Args) = "-d" then Evaluation.Debug := True; elsif Ada.Command_Line.Argument (Cmd_Args) = "-e" then Envs.Debug := True; else if not File_Processed then -- declare -- F_S : String := ADa.Text_IO.Put_Line ( Rep ("(load-file """ & Ada.Command_Line.Argument (Cmd_Args) & """)") ); -- begin -- null; -- end; File_Processed := True; else Command_List.Append (Types.New_Atom_Mal_Type (Ada.Command_Line.Argument (Cmd_Args))); end if; end if; end loop; Envs.Set (Envs.Get_Current, "*ARGV*", Command_Args); loop begin Ada.Text_IO.Put ("user> "); Ada.Text_IO.Get_Line (S, Last); Ada.Text_IO.Put_Line (Rep (S (1..Last))); exception when Ada.IO_Exceptions.End_Error => raise; when E : others => Ada.Text_IO.Put_Line (Ada.Text_IO.Standard_Error, Ada.Exceptions.Exception_Information (E)); end; end loop; exception when Ada.IO_Exceptions.End_Error => null; -- i.e. exit without textual output end Step8_Macros;
with Ada.Command_Line; with Ada.Exceptions; with Ada.Text_IO; with Ada.IO_Exceptions; with Core; with Envs; with Evaluation; with Printer; with Reader; with Types; procedure Step8_Macros is function Read (Param : String) return Types.Mal_Handle is begin return Reader.Read_Str (Param); end Read; -- Eval can't be here because there are function pointers that point -- at it. Thus it must be at library level. See evaluation.ads function Print (Param : Types.Mal_Handle) return String is begin return Printer.Pr_Str (Param); end Print; function Rep (Param : String) return String is AST, Evaluated_AST : Types.Mal_Handle; begin AST := Read (Param); if Types.Is_Null (AST) then return ""; else Evaluated_AST := Evaluation.Eval (AST, Envs.Get_Current); return Print (Evaluated_AST); end if; end Rep; S : String (1..Reader.Max_Line_Len); Last : Natural; Cmd_Args : Natural; Command_Args : Types.Mal_Handle; Command_List : Types.List_Ptr; File_Processed : Boolean := False; begin -- Core init also creates the first environment. -- This is needed for the def!'s below. Core.Init; declare Not_S : String := Rep ("(def! not (fn* (a) (if a false true)))"); LF_S : String := Rep ("(def! load-file (fn* (f) (eval (read-string (str ""(do "" (slurp f) "")"")))))"); Cond_S : String := Rep ("(defmacro! cond (fn* (& xs) (if (> (count xs) 0) (list 'if (first xs) (if (> (count xs) 1) (nth xs 1) (throw ""odd number of forms to cond"")) (cons 'cond (rest (rest xs)))))))"); Or_S : String := Rep ("(defmacro! or (fn* (& xs) (if (empty? xs) nil (if (= 1 (count xs)) (first xs) `(let* (or_FIXME ~(first xs)) (if or_FIXME or_FIXME (or ~@(rest xs))))))))"); pragma Unreferenced (Not_S, LF_S, Cond_S, Or_S); begin null; end; Cmd_Args := 0; Command_Args := Types.New_List_Mal_Type (Types.List_List); Command_List := Types.Deref_List (Command_Args); while Ada.Command_Line.Argument_Count > Cmd_Args loop Cmd_Args := Cmd_Args + 1; if Ada.Command_Line.Argument (Cmd_Args) = "-d" then Evaluation.Debug := True; elsif Ada.Command_Line.Argument (Cmd_Args) = "-e" then Envs.Debug := True; else if not File_Processed then -- declare -- F_S : String := ADa.Text_IO.Put_Line ( Rep ("(load-file """ & Ada.Command_Line.Argument (Cmd_Args) & """)") ); -- begin -- null; -- end; File_Processed := True; else Command_List.Append (Types.New_Atom_Mal_Type (Ada.Command_Line.Argument (Cmd_Args))); end if; end if; end loop; Envs.Set (Envs.Get_Current, "*ARGV*", Command_Args); loop begin Ada.Text_IO.Put ("user> "); Ada.Text_IO.Get_Line (S, Last); Ada.Text_IO.Put_Line (Rep (S (1..Last))); exception when Ada.IO_Exceptions.End_Error => raise; when E : others => Ada.Text_IO.Put_Line (Ada.Text_IO.Standard_Error, Ada.Exceptions.Exception_Information (E)); end; end loop; exception when Ada.IO_Exceptions.End_Error => null; -- i.e. exit without textual output end Step8_Macros;
add Cond and Or macros
Ada: add Cond and Or macros
Ada
mpl-2.0
alantsev/mal,DomBlack/mal,DomBlack/mal,jwalsh/mal,hterkelsen/mal,0gajun/mal,foresterre/mal,hterkelsen/mal,0gajun/mal,DomBlack/mal,hterkelsen/mal,foresterre/mal,foresterre/mal,alantsev/mal,mpwillson/mal,foresterre/mal,0gajun/mal,alantsev/mal,0gajun/mal,DomBlack/mal,0gajun/mal,SawyerHood/mal,0gajun/mal,jwalsh/mal,hterkelsen/mal,SawyerHood/mal,jwalsh/mal,foresterre/mal,alantsev/mal,mpwillson/mal,jwalsh/mal,joncol/mal,SawyerHood/mal,jwalsh/mal,mpwillson/mal,SawyerHood/mal,SawyerHood/mal,0gajun/mal,alantsev/mal,0gajun/mal,SawyerHood/mal,jwalsh/mal,hterkelsen/mal,foresterre/mal,alantsev/mal,DomBlack/mal,DomBlack/mal,foresterre/mal,hterkelsen/mal,mpwillson/mal,jwalsh/mal,hterkelsen/mal,foresterre/mal,hterkelsen/mal,mpwillson/mal,hterkelsen/mal,joncol/mal,0gajun/mal,jwalsh/mal,hterkelsen/mal,alantsev/mal,DomBlack/mal,0gajun/mal,foresterre/mal,DomBlack/mal,SawyerHood/mal,jwalsh/mal,0gajun/mal,mpwillson/mal,hterkelsen/mal,hterkelsen/mal,mpwillson/mal,DomBlack/mal,0gajun/mal,0gajun/mal,SawyerHood/mal,0gajun/mal,SawyerHood/mal,foresterre/mal,hterkelsen/mal,joncol/mal,0gajun/mal,SawyerHood/mal,foresterre/mal,hterkelsen/mal,SawyerHood/mal,DomBlack/mal,DomBlack/mal,hterkelsen/mal,DomBlack/mal,foresterre/mal,DomBlack/mal,SawyerHood/mal,DomBlack/mal,jwalsh/mal,SawyerHood/mal,DomBlack/mal,0gajun/mal,alantsev/mal,jwalsh/mal,alantsev/mal,alantsev/mal,jwalsh/mal,hterkelsen/mal,hterkelsen/mal,mpwillson/mal,jwalsh/mal,jwalsh/mal,DomBlack/mal,alantsev/mal,DomBlack/mal,mpwillson/mal,foresterre/mal,mpwillson/mal,SawyerHood/mal,SawyerHood/mal,0gajun/mal,alantsev/mal,foresterre/mal,0gajun/mal,SawyerHood/mal,DomBlack/mal,mpwillson/mal,foresterre/mal,alantsev/mal,foresterre/mal,alantsev/mal,SawyerHood/mal,SawyerHood/mal,DomBlack/mal,hterkelsen/mal,mpwillson/mal,mpwillson/mal,0gajun/mal,foresterre/mal,alantsev/mal,jwalsh/mal,jwalsh/mal,alantsev/mal,alantsev/mal,hterkelsen/mal,0gajun/mal,mpwillson/mal,jwalsh/mal,DomBlack/mal,DomBlack/mal
cacdc640bcea890fff298dcbf6001e1db197de2f
src/bare_bones.adb
src/bare_bones.adb
-- -*- Mode: Ada -*- -- Filename : bare_bones.adb -- Description : A "hello world" style OS kernel written in Ada. -- Author : Luke A. Guest -- Created On : Thu Jun 14 11:59:53 2012 -- Licence : See LICENCE in the root directory. pragma Restrictions (No_Obsolescent_Features); with VGA_Console; use VGA_Console; with Multiboot; use Multiboot; -- with System.Address_To_Access_Conversions; -- with Ada.Unchecked_Conversion; use type Multiboot.Magic_Values; procedure Bare_Bones is Line : Screen_Height_Range := Screen_Height_Range'First; begin null; Clear; Put ("Hello, bare bones in Ada", Screen_Width_Range'First, Line); Line := Line + 1; if Magic = Magic_Value then Put ("Magic numbers match!", Screen_Width_Range'First, Line); else Put ("Magic numbers don't match!", Screen_Width_Range'First, Line); raise Program_Error; end if; -- Line := Line + 1; -- if Info.Flags.Memory then -- Put ("Memory info present", Screen_Width_Range'First, Line); -- Line := Line + 1; -- end if; -- if Info.Flags.Boot_Device then -- Put ("Boot device info present", Screen_Width_Range'First, Line); -- Line := Line + 1; -- end if; -- if Info.Flags.Command_Line then -- Put ("Command line info present", Screen_Width_Range'First, Line); -- Line := Line + 1; -- end if; -- if Info.Flags.Modules then -- Put ("Modules info present", Screen_Width_Range'First, Line); -- Line := Line + 1; -- if Info.Modules.Count = 2 then -- declare -- type My_Modules_Array is new Modules_Array -- (1 .. Natural (Info.Modules.Count)); -- type My_Modules_Array_Access is access all My_Modules_Array; -- -- My_Modules : aliased Modules_Array -- -- (1 .. Natural (Info.Modules.Count)); -- -- pragma Unreferenced (My_Modules); -- package To_Modules is new System.Address_To_Access_Conversions -- (Object => My_Modules_Array_Access); -- function Conv is new Ada.Unchecked_Conversion -- (Source => To_Modules.Object_Pointer, -- Target => My_Modules_Array_Access); -- Modules : constant My_Modules_Array_Access := -- Conv (To_Modules.To_Pointer -- (Info.Modules.First)); -- M : Multiboot.Modules; -- pragma Unreferenced (M); -- begin -- Put ("2 modules loaded is correct", -- Screen_Width_Range'First, Line); -- for I in 1 .. Info.Modules.Count loop -- M := Modules (Natural (I)); -- end loop; -- Line := Line + 1; -- end; -- end if; -- end if; -- if Info.Flags.Symbol_Table then -- Put ("Symbol table info present", Screen_Width_Range'First, Line); -- Line := Line + 1; -- end if; -- if Info.Flags.Section_Header_Table then -- Put ("Section header table info present", -- Screen_Width_Range'First, Line); -- Line := Line + 1; -- end if; -- if Info.Flags.BIOS_Memory_Map then -- Put ("BIOS memory map info present", Screen_Width_Range'First, Line); -- Line := Line + 1; -- declare -- Map : Memory_Map_Entry_Access := Multiboot.First_Memory_Map_Entry; -- begin -- while Map /= null loop -- Map := Multiboot.Next_Memory_Map_Entry (Map); -- end loop; -- end; -- end if; -- if Info.Flags.Drives then -- Put ("Drives info present", Screen_Width_Range'First, Line); -- Line := Line + 1; -- end if; -- if Info.Flags.ROM_Configuration then -- Put ("ROM configuration info present", -- Screen_Width_Range'First, Line); -- Line := Line + 1; -- end if; -- if Info.Flags.Boot_Loader then -- Put ("Boot loader info present", Screen_Width_Range'First, Line); -- Line := Line + 1; -- end if; -- if Info.Flags.APM_Table then -- Put ("APM table info present", Screen_Width_Range'First, Line); -- Line := Line + 1; -- end if; -- if Info.Flags.Graphics_Table then -- Put ("Graphics table info present", Screen_Width_Range'First, Line); -- Line := Line + 1; -- end if; -- raise Constraint_Error; -- raise Console.TE; -- raise Constraint_Error; -- Put (Natural 'Image (54), -- Screen_Width_Range'First, -- Screen_Height_Range'First + 1); -- exception -- when Constraint_Error => -- Put ("Constraint Error caught", 1, 15); -- when Program_Error => -- null; -- when Console.TE => -- Put ("TE caught", 1, 2); end Bare_Bones; pragma No_Return (Bare_Bones);
-- -*- Mode: Ada -*- -- Filename : bare_bones.adb -- Description : A "hello world" style OS kernel written in Ada. -- Author : Luke A. Guest -- Created On : Thu Jun 14 11:59:53 2012 -- Licence : See LICENCE in the root directory. pragma Restrictions (No_Obsolescent_Features); with VGA_Console; use VGA_Console; with Multiboot; use Multiboot; -- with System.Address_To_Access_Conversions; -- with Ada.Unchecked_Conversion; use type Multiboot.Magic_Values; procedure Bare_Bones is Line : Screen_Height_Range := Screen_Height_Range'First; procedure T is begin Put ("T called", Screen_Width_Range'First, Line); end T; function Hello return String is begin return "hello!!"; end Hello; begin -- null; Clear; Put ("Hello, bare bones in Ada", Screen_Width_Range'First, Line); Line := Line + 1; if Magic = Magic_Value then Put ("Magic numbers match!", Screen_Width_Range'First, Line); else Put ("Magic numbers don't match!", Screen_Width_Range'First, Line); -- comment raise Program_Error; end if; Line := Line + 1; T; Line := Line + 1; Put (Hello, Screen_Width_Range'First, Line); -- if Info.Flags.Memory then -- Put ("Memory info present", Screen_Width_Range'First, Line); -- Line := Line + 1; -- end if; -- if Info.Flags.Boot_Device then -- Put ("Boot device info present", Screen_Width_Range'First, Line); -- Line := Line + 1; -- end if; -- if Info.Flags.Command_Line then -- Put ("Command line info present", Screen_Width_Range'First, Line); -- Line := Line + 1; -- end if; -- if Info.Flags.Modules then -- Put ("Modules info present", Screen_Width_Range'First, Line); -- Line := Line + 1; -- if Info.Modules.Count = 2 then -- declare -- type My_Modules_Array is new Modules_Array -- (1 .. Natural (Info.Modules.Count)); -- type My_Modules_Array_Access is access all My_Modules_Array; -- -- My_Modules : aliased Modules_Array -- -- (1 .. Natural (Info.Modules.Count)); -- -- pragma Unreferenced (My_Modules); -- package To_Modules is new System.Address_To_Access_Conversions -- (Object => My_Modules_Array_Access); -- function Conv is new Ada.Unchecked_Conversion -- (Source => To_Modules.Object_Pointer, -- Target => My_Modules_Array_Access); -- Modules : constant My_Modules_Array_Access := -- Conv (To_Modules.To_Pointer -- (Info.Modules.First)); -- M : Multiboot.Modules; -- pragma Unreferenced (M); -- begin -- Put ("2 modules loaded is correct", -- Screen_Width_Range'First, Line); -- for I in 1 .. Info.Modules.Count loop -- M := Modules (Natural (I)); -- end loop; -- Line := Line + 1; -- end; -- end if; -- end if; -- if Info.Flags.Symbol_Table then -- Put ("Symbol table info present", Screen_Width_Range'First, Line); -- Line := Line + 1; -- end if; -- if Info.Flags.Section_Header_Table then -- Put ("Section header table info present", -- Screen_Width_Range'First, Line); -- Line := Line + 1; -- end if; -- if Info.Flags.BIOS_Memory_Map then -- Put ("BIOS memory map info present", Screen_Width_Range'First, Line); -- Line := Line + 1; -- declare -- Map : Memory_Map_Entry_Access := Multiboot.First_Memory_Map_Entry; -- begin -- while Map /= null loop -- Map := Multiboot.Next_Memory_Map_Entry (Map); -- end loop; -- end; -- end if; -- if Info.Flags.Drives then -- Put ("Drives info present", Screen_Width_Range'First, Line); -- Line := Line + 1; -- end if; -- if Info.Flags.ROM_Configuration then -- Put ("ROM configuration info present", -- Screen_Width_Range'First, Line); -- Line := Line + 1; -- end if; -- if Info.Flags.Boot_Loader then -- Put ("Boot loader info present", Screen_Width_Range'First, Line); -- Line := Line + 1; -- end if; -- if Info.Flags.APM_Table then -- Put ("APM table info present", Screen_Width_Range'First, Line); -- Line := Line + 1; -- end if; -- if Info.Flags.Graphics_Table then -- Put ("Graphics table info present", Screen_Width_Range'First, Line); -- Line := Line + 1; -- end if; -- raise Constraint_Error; -- raise Console.TE; -- raise Constraint_Error; -- Put (Natural 'Image (54), -- Screen_Width_Range'First, -- Screen_Height_Range'First + 1); -- exception -- when Constraint_Error => -- Put ("Constraint Error caught", 1, 15); -- when Program_Error => -- null; -- when Console.TE => -- Put ("TE caught", 1, 2); end Bare_Bones; -- pragma No_Return (Bare_Bones);
Add local function to make sure nested functions work. Add function which returns a string utilising secondary stack.
Add local function to make sure nested functions work. Add function which returns a string utilising secondary stack.
Ada
cc0-1.0
Lucretia/bare_bones
a0f9fd514184598c9c0665167b303ba125ef1a71
src/gen-artifacts-distribs-copies.ads
src/gen-artifacts-distribs-copies.ads
----------------------------------------------------------------------- -- gen-artifacts-distribs-copies -- Copy based distribution artifact -- Copyright (C) 2012 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- -- The <b>Gen.Artifacts.Distribs.Copies</b> package provides distribution rules -- to copy a file or a directory to the distribution area. private package Gen.Artifacts.Distribs.Copies is -- Create a distribution rule to copy a set of files or directories. function Create_Rule (Node : in DOM.Core.Node) return Distrib_Rule_Access; -- ------------------------------ -- Distribution artifact -- ------------------------------ type Copy_Rule is new Distrib_Rule with private; type Copy_Rule_Access is access all Copy_Rule'Class; -- Get a name to qualify the installation rule (used for logs). overriding function Get_Install_Name (Rule : in Copy_Rule) return String; overriding procedure Install (Rule : in Copy_Rule; Path : in String; Files : in File_Vector; Context : in out Generator'Class); private type Copy_Rule is new Distrib_Rule with null record; end Gen.Artifacts.Distribs.Copies;
----------------------------------------------------------------------- -- gen-artifacts-distribs-copies -- Copy based distribution artifact -- Copyright (C) 2012, 2013 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- -- The <b>Gen.Artifacts.Distribs.Copies</b> package provides distribution rules -- to copy a file or a directory to the distribution area. private package Gen.Artifacts.Distribs.Copies is -- Create a distribution rule to copy a set of files or directories. function Create_Rule (Node : in DOM.Core.Node; Copy_First_File : in Boolean) return Distrib_Rule_Access; -- ------------------------------ -- Distribution artifact -- ------------------------------ type Copy_Rule is new Distrib_Rule with private; type Copy_Rule_Access is access all Copy_Rule'Class; -- Get a name to qualify the installation rule (used for logs). overriding function Get_Install_Name (Rule : in Copy_Rule) return String; overriding procedure Install (Rule : in Copy_Rule; Path : in String; Files : in File_Vector; Context : in out Generator'Class); private type Copy_Rule is new Distrib_Rule with record -- When True and there are several source files, use the first file. -- Otherwise, use the last file. Copy_First_File : Boolean := False; end record; end Gen.Artifacts.Distribs.Copies;
Add a copy-first command to copy the first file found only (the default is to copy the last one since this is the reverse search path)
Add a copy-first command to copy the first file found only (the default is to copy the last one since this is the reverse search path)
Ada
apache-2.0
Letractively/ada-gen,Letractively/ada-gen,Letractively/ada-gen,Letractively/ada-gen
74a77d41da2d913f2244efee16c435c9af27552b
src/el-objects-hash.adb
src/el-objects-hash.adb
----------------------------------------------------------------------- -- EL.Objects.Hash -- Hash on an object -- Copyright (C) 2010 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Strings.Hash; with Ada.Characters.Conversions; with Ada.Unchecked_Conversion; with Interfaces; with EL.Beans; function EL.Objects.Hash (Key : in Object) return Ada.Containers.Hash_Type is use Ada.Containers; use Ada.Strings; use Ada.Characters.Conversions; use Interfaces; use EL.Beans; type Unsigned_32_Array is array (Natural range <>) of Unsigned_32; subtype U32_For_Float is Unsigned_32_Array (1 .. Long_Long_Float'Size / 32); subtype U32_For_Long is Unsigned_32_Array (1 .. Long_Long_Integer'Size / 32); subtype U32_For_Access is Unsigned_32_Array (1 .. Readonly_Bean_Access'Size / 32); -- Hash the integer and floats using 32-bit values. function To_U32_For_Long is new Ada.Unchecked_Conversion (Source => Long_Long_Integer, Target => U32_For_Long); -- Likewise for floats. function To_U32_For_Float is new Ada.Unchecked_Conversion (Source => Long_Long_Float, Target => U32_For_Float); -- Likewise for the bean pointer function To_U32_For_Access is new Ada.Unchecked_Conversion (Source => Readonly_Bean_Access, Target => U32_For_Access); Value : Unsigned_64 := 0; begin case key.V.Of_Type is when TYPE_NULL => return 0; when TYPE_BOOLEAN => if Key.V.Bool_Value then return 1; else return 2; end if; when TYPE_INTEGER => declare U32 : constant U32_For_Long := To_U32_For_Long (Key.V.Int_Value); Val : Unsigned_32 := U32 (U32'First); begin for I in U32'First + 1 .. U32'Last loop Val := Val xor U32 (I); end loop; return Hash_Type (Val); end; when TYPE_FLOAT => declare U32 : constant U32_For_Float := To_U32_For_Float (Key.V.Float_Value); Val : Unsigned_32 := U32 (U32'First); begin for I in U32'First + 1 .. U32'Last loop Val := Val xor U32 (I); end loop; return Hash_Type (Val); end; when TYPE_STRING => if Key.V.Proxy = null then return 0; else return Hash (Key.V.Proxy.String_Value.all); end if; when TYPE_TIME => declare U32 : constant U32_For_Long := To_U32_For_Long (Key.V.Time_Value); Val : Unsigned_32 := U32 (U32'First); begin for I in U32'First + 1 .. U32'Last loop Val := Val xor U32 (I); end loop; return Hash_Type (Val); end; when TYPE_WIDE_STRING => if Key.V.Proxy = null then return 0; else return Hash (To_String (Key.V.Proxy.Wide_String_Value.all)); end if; when TYPE_BEAN => if Key.V.Proxy.Bean = null then return 0; end if; declare U32 : constant U32_For_Access := To_U32_For_Access (Key.V.Proxy.Bean.all'Access); Val : Unsigned_32 := U32 (U32'First); -- The loop is not executed if pointers are 32-bit wide. pragma Warnings (Off); begin for I in U32'First + 1 .. U32'Last loop Val := Val xor U32 (I); end loop; return Hash_Type (Val); end; end case; -- Hash the 64-bit value into a 32-bit result that fits in Hash_Type. Value := (Value and 16#0ffffffff#) xor (Shift_Right (Value, 32)); return Hash_Type (Value); end EL.Objects.Hash;
----------------------------------------------------------------------- -- EL.Objects.Hash -- Hash on an object -- Copyright (C) 2010 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Strings.Hash; with Ada.Characters.Conversions; with Ada.Unchecked_Conversion; with Interfaces; with EL.Beans; function EL.Objects.Hash (Key : in Object) return Ada.Containers.Hash_Type is use Ada.Containers; use Ada.Strings; use Ada.Characters.Conversions; use Interfaces; use EL.Beans; type Unsigned_32_Array is array (Natural range <>) of Unsigned_32; subtype U32_For_Float is Unsigned_32_Array (1 .. Long_Long_Float'Size / 32); subtype U32_For_Long is Unsigned_32_Array (1 .. Long_Long_Integer'Size / 32); subtype U32_For_Access is Unsigned_32_Array (1 .. Readonly_Bean_Access'Size / 32); -- Hash the integer and floats using 32-bit values. function To_U32_For_Long is new Ada.Unchecked_Conversion (Source => Long_Long_Integer, Target => U32_For_Long); -- Likewise for floats. function To_U32_For_Float is new Ada.Unchecked_Conversion (Source => Long_Long_Float, Target => U32_For_Float); -- Likewise for the bean pointer function To_U32_For_Access is new Ada.Unchecked_Conversion (Source => Readonly_Bean_Access, Target => U32_For_Access); begin case key.V.Of_Type is when TYPE_NULL => return 0; when TYPE_BOOLEAN => if Key.V.Bool_Value then return 1; else return 2; end if; when TYPE_INTEGER => declare U32 : constant U32_For_Long := To_U32_For_Long (Key.V.Int_Value); Val : Unsigned_32 := U32 (U32'First); begin for I in U32'First + 1 .. U32'Last loop Val := Val xor U32 (I); end loop; return Hash_Type (Val); end; when TYPE_FLOAT => declare U32 : constant U32_For_Float := To_U32_For_Float (Key.V.Float_Value); Val : Unsigned_32 := U32 (U32'First); begin for I in U32'First + 1 .. U32'Last loop Val := Val xor U32 (I); end loop; return Hash_Type (Val); end; when TYPE_STRING => if Key.V.Proxy = null then return 0; else return Hash (Key.V.Proxy.String_Value.all); end if; when TYPE_TIME => declare U32 : constant U32_For_Long := To_U32_For_Long (Key.V.Time_Value); Val : Unsigned_32 := U32 (U32'First); begin for I in U32'First + 1 .. U32'Last loop Val := Val xor U32 (I); end loop; return Hash_Type (Val); end; when TYPE_WIDE_STRING => if Key.V.Proxy = null then return 0; else return Hash (To_String (Key.V.Proxy.Wide_String_Value.all)); end if; when TYPE_BEAN => if Key.V.Proxy.Bean = null then return 0; end if; declare U32 : constant U32_For_Access := To_U32_For_Access (Key.V.Proxy.Bean.all'Access); Val : Unsigned_32 := U32 (U32'First); -- The loop is not executed if pointers are 32-bit wide. pragma Warnings (Off); begin for I in U32'First + 1 .. U32'Last loop Val := Val xor U32 (I); end loop; return Hash_Type (Val); end; end case; end EL.Objects.Hash;
Remove unreachable code
Remove unreachable code
Ada
apache-2.0
Letractively/ada-el
85914f1bf4f7e3ea2026a85399d8cad04d7f9315
pgada.ads
pgada.ads
------------------------------------------------------------------------------ -- -- -- P G A D A -- -- -- -- S p e c -- -- -- -- Copyright (c) Samuel Tardieu 2000 -- -- All rights reserved. -- -- -- -- Redistribution and use in source and binary forms, with or without -- -- modification, are permitted provided that the following conditions -- -- are met: -- -- 1. Redistributions of source code must retain the above copyright -- -- notice, this list of conditions and the following disclaimer. -- -- 2. Redistributions in binary form must reproduce the above copyright -- -- notice, this list of conditions and the following disclaimer in -- -- the documentation and/or other materials provided with the -- -- distribution. -- -- 3. Neither the name of Samuel Tardieu nor the names of its contributors -- -- may be used to endorse or promote products derived from this -- -- software without specific prior written permission. -- -- -- -- THIS SOFTWARE IS PROVIDED BY SAMUEL TARDIEU AND CONTRIBUTORS ``AS -- -- IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -- -- LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS -- -- FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL SAMUEL -- -- TARDIEU OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, -- -- INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -- -- (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR -- -- SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) -- -- HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -- -- CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR -- -- OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, -- -- EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -- -- -- ------------------------------------------------------------------------------ package PGAda is pragma Pure; end PGAda;
------------------------------------------------------------------------------ -- -- -- P G A D A -- -- -- -- S p e c -- -- -- -- Copyright (c) Samuel Tardieu 2000 -- -- Copyright (c) coreland 2009 -- -- All rights reserved. -- -- -- -- Redistribution and use in source and binary forms, with or without -- -- modification, are permitted provided that the following conditions -- -- are met: -- -- 1. Redistributions of source code must retain the above copyright -- -- notice, this list of conditions and the following disclaimer. -- -- 2. Redistributions in binary form must reproduce the above copyright -- -- notice, this list of conditions and the following disclaimer in -- -- the documentation and/or other materials provided with the -- -- distribution. -- -- 3. Neither the name of Samuel Tardieu nor the names of its contributors -- -- may be used to endorse or promote products derived from this -- -- software without specific prior written permission. -- -- -- -- THIS SOFTWARE IS PROVIDED BY SAMUEL TARDIEU AND CONTRIBUTORS ``AS -- -- IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -- -- LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS -- -- FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL SAMUEL -- -- TARDIEU OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, -- -- INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -- -- (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR -- -- SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) -- -- HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -- -- CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR -- -- OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, -- -- EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -- -- -- ------------------------------------------------------------------------------ package PGAda is pragma Pure; end PGAda;
Update license on header.
Update license on header.
Ada
bsd-3-clause
io7m/coreland-postgres-ada,io7m/coreland-postgres-ada
c0e1efaf523f7eacdac7902d943cabcf343b1670
samples/render.adb
samples/render.adb
----------------------------------------------------------------------- -- render -- Wiki rendering example -- Copyright (C) 2015, 2016, 2020 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Text_IO; with Ada.IO_Exceptions; with Ada.Strings.Unbounded; with Ada.Directories; with GNAT.Command_Line; with Wiki.Documents; with Wiki.Parsers; with Wiki.Filters.TOC; with Wiki.Filters.Html; with Wiki.Filters.Autolink; with Wiki.Plugins.Templates; with Wiki.Render.Html; with Wiki.Render.Text; with Wiki.Streams.Text_IO; with Wiki.Streams.Html.Text_IO; procedure Render is use GNAT.Command_Line; use Ada.Strings.Unbounded; procedure Usage; procedure Render_Html (Doc : in out Wiki.Documents.Document; Style : in Unbounded_String); procedure Render_Text (Doc : in out Wiki.Documents.Document); procedure Usage is begin Ada.Text_IO.Put_Line ("Render a wiki text file into HTML (default) or text"); Ada.Text_IO.Put_Line ("Usage: render [-t] [-m] [-M] [-d] [-c] [-s style] {wiki-file}"); Ada.Text_IO.Put_Line (" -t Render to text only"); Ada.Text_IO.Put_Line (" -m Render a Markdown wiki content"); Ada.Text_IO.Put_Line (" -M Render a Mediawiki wiki content"); Ada.Text_IO.Put_Line (" -d Render a Dotclear wiki content"); Ada.Text_IO.Put_Line (" -g Render a Google wiki content"); Ada.Text_IO.Put_Line (" -c Render a Creole wiki content"); Ada.Text_IO.Put_Line (" -s style Use the CSS style file"); end Usage; procedure Render_Html (Doc : in out Wiki.Documents.Document; Style : in Unbounded_String) is Output : aliased Wiki.Streams.Html.Text_IO.Html_Output_Stream; Renderer : aliased Wiki.Render.Html.Html_Renderer; begin if Length (Style) > 0 then Output.Start_Element ("html"); Output.Start_Element ("head"); Output.Start_Element ("link"); Output.Write_Attribute ("type", "text/css"); Output.Write_Attribute ("rel", "stylesheet"); Output.Write_Attribute ("href", To_String (Style)); Output.End_Element ("link"); Output.End_Element ("head"); Output.Start_Element ("body"); end if; Renderer.Set_Output_Stream (Output'Unchecked_Access); Renderer.Set_Render_TOC (True); Renderer.Render (Doc); if Length (Style) > 0 then Output.End_Element ("body"); Output.End_Element ("html"); end if; end Render_Html; procedure Render_Text (Doc : in out Wiki.Documents.Document) is Output : aliased Wiki.Streams.Text_IO.File_Output_Stream; Renderer : aliased Wiki.Render.Text.Text_Renderer; begin Renderer.Set_Output_Stream (Output'Unchecked_Access); Renderer.Render (Doc); end Render_Text; Count : Natural := 0; Html_Mode : Boolean := True; Syntax : Wiki.Wiki_Syntax := Wiki.SYNTAX_MARKDOWN; Style : Unbounded_String; begin loop case Getopt ("m M d c g t s:") is when 'm' => Syntax := Wiki.SYNTAX_MARKDOWN; when 'M' => Syntax := Wiki.SYNTAX_MEDIA_WIKI; when 'c' => Syntax := Wiki.SYNTAX_CREOLE; when 'd' => Syntax := Wiki.SYNTAX_DOTCLEAR; when 'g' => Syntax := Wiki.SYNTAX_GOOGLE; when 't' => Html_Mode := False; when 's' => Style := To_Unbounded_String (Parameter); when others => exit; end case; end loop; loop declare Name : constant String := GNAT.Command_Line.Get_Argument; Input : aliased Wiki.Streams.Text_IO.File_Input_Stream; Filter : aliased Wiki.Filters.Html.Html_Filter_Type; Autolink : aliased Wiki.Filters.Autolink.Autolink_Filter; Template : aliased Wiki.Plugins.Templates.File_Template_Plugin; TOC : aliased Wiki.Filters.TOC.TOC_Filter; Doc : Wiki.Documents.Document; Engine : Wiki.Parsers.Parser; begin if Name = "" then if Count = 0 then Usage; end if; return; end if; Count := Count + 1; Template.Set_Template_Path (Ada.Directories.Containing_Directory (Name)); -- Open the file and parse it (assume UTF-8). Input.Open (Name, "WCEM=8"); Engine.Set_Plugin_Factory (Template'Unchecked_Access); Engine.Add_Filter (TOC'Unchecked_Access); Engine.Add_Filter (Autolink'Unchecked_Access); Engine.Add_Filter (Filter'Unchecked_Access); Engine.Set_Syntax (Syntax); Engine.Parse (Input'Unchecked_Access, Doc); -- Render the document in text or HTML. if Html_Mode then Render_Html (Doc, Style); else Render_Text (Doc); end if; exception when Ada.IO_Exceptions.Name_Error => Ada.Text_IO.Put_Line ("Cannot read file '" & Name & "'"); end; end loop; exception when Invalid_Switch => Ada.Text_IO.Put_Line ("Invalid option."); Usage; end Render;
----------------------------------------------------------------------- -- render -- Wiki rendering example -- Copyright (C) 2015, 2016, 2020, 2021 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Text_IO; with Ada.IO_Exceptions; with Ada.Strings.Unbounded; with Ada.Directories; with GNAT.Command_Line; with Wiki.Documents; with Wiki.Parsers; with Wiki.Filters.TOC; with Wiki.Filters.Html; with Wiki.Filters.Autolink; with Wiki.Plugins.Templates; with Wiki.Render.Html; with Wiki.Render.Text; with Wiki.Streams.Text_IO; with Wiki.Streams.Html.Text_IO; procedure Render is use GNAT.Command_Line; use Ada.Strings.Unbounded; procedure Usage; procedure Render_Html (Doc : in out Wiki.Documents.Document; Style : in Unbounded_String); procedure Render_Text (Doc : in out Wiki.Documents.Document); procedure Usage is begin Ada.Text_IO.Put_Line ("Render a wiki text file into HTML (default) or text"); Ada.Text_IO.Put_Line ("Usage: render [-t] [-m] [-M] [-H] [-d] [-c] [-s style] {wiki-file}"); Ada.Text_IO.Put_Line (" -t Render to text only"); Ada.Text_IO.Put_Line (" -m Render a Markdown wiki content"); Ada.Text_IO.Put_Line (" -M Render a Mediawiki wiki content"); Ada.Text_IO.Put_Line (" -H Render a HTML wiki content"); Ada.Text_IO.Put_Line (" -d Render a Dotclear wiki content"); Ada.Text_IO.Put_Line (" -g Render a Google wiki content"); Ada.Text_IO.Put_Line (" -c Render a Creole wiki content"); Ada.Text_IO.Put_Line (" -s style Use the CSS style file"); end Usage; procedure Render_Html (Doc : in out Wiki.Documents.Document; Style : in Unbounded_String) is Output : aliased Wiki.Streams.Html.Text_IO.Html_Output_Stream; Renderer : aliased Wiki.Render.Html.Html_Renderer; begin if Length (Style) > 0 then Output.Start_Element ("html"); Output.Start_Element ("head"); Output.Start_Element ("link"); Output.Write_Attribute ("type", "text/css"); Output.Write_Attribute ("rel", "stylesheet"); Output.Write_Attribute ("href", To_String (Style)); Output.End_Element ("link"); Output.End_Element ("head"); Output.Start_Element ("body"); end if; Renderer.Set_Output_Stream (Output'Unchecked_Access); Renderer.Set_Render_TOC (True); Renderer.Render (Doc); if Length (Style) > 0 then Output.End_Element ("body"); Output.End_Element ("html"); end if; end Render_Html; procedure Render_Text (Doc : in out Wiki.Documents.Document) is Output : aliased Wiki.Streams.Text_IO.File_Output_Stream; Renderer : aliased Wiki.Render.Text.Text_Renderer; begin Renderer.Set_Output_Stream (Output'Unchecked_Access); Renderer.Render (Doc); end Render_Text; Count : Natural := 0; Html_Mode : Boolean := True; Syntax : Wiki.Wiki_Syntax := Wiki.SYNTAX_MARKDOWN; Style : Unbounded_String; begin loop case Getopt ("m M d c g t H s:") is when 'm' => Syntax := Wiki.SYNTAX_MARKDOWN; when 'M' => Syntax := Wiki.SYNTAX_MEDIA_WIKI; when 'c' => Syntax := Wiki.SYNTAX_CREOLE; when 'd' => Syntax := Wiki.SYNTAX_DOTCLEAR; when 'H' => Syntax := Wiki.SYNTAX_HTML; when 'g' => Syntax := Wiki.SYNTAX_GOOGLE; when 't' => Html_Mode := False; when 's' => Style := To_Unbounded_String (Parameter); when others => exit; end case; end loop; loop declare Name : constant String := GNAT.Command_Line.Get_Argument; Input : aliased Wiki.Streams.Text_IO.File_Input_Stream; Filter : aliased Wiki.Filters.Html.Html_Filter_Type; Autolink : aliased Wiki.Filters.Autolink.Autolink_Filter; Template : aliased Wiki.Plugins.Templates.File_Template_Plugin; TOC : aliased Wiki.Filters.TOC.TOC_Filter; Doc : Wiki.Documents.Document; Engine : Wiki.Parsers.Parser; begin if Name = "" then if Count = 0 then Usage; end if; return; end if; Count := Count + 1; Template.Set_Template_Path (Ada.Directories.Containing_Directory (Name)); -- Open the file and parse it (assume UTF-8). Input.Open (Name, "WCEM=8"); Engine.Set_Plugin_Factory (Template'Unchecked_Access); Engine.Add_Filter (TOC'Unchecked_Access); Engine.Add_Filter (Autolink'Unchecked_Access); Engine.Add_Filter (Filter'Unchecked_Access); Engine.Set_Syntax (Syntax); Engine.Parse (Input'Unchecked_Access, Doc); -- Render the document in text or HTML. if Html_Mode then Render_Html (Doc, Style); else Render_Text (Doc); end if; exception when Ada.IO_Exceptions.Name_Error => Ada.Text_IO.Put_Line ("Cannot read file '" & Name & "'"); end; end loop; exception when Invalid_Switch => Ada.Text_IO.Put_Line ("Invalid option."); Usage; end Render;
Add -H option to parse some HTML content and produce a HTML cleaned result
Add -H option to parse some HTML content and produce a HTML cleaned result
Ada
apache-2.0
stcarrez/ada-wiki,stcarrez/ada-wiki
5a28133f71c2489112f4b2e2e67d4f268d0d805f
src/ado-drivers-dialects.adb
src/ado-drivers-dialects.adb
----------------------------------------------------------------------- -- ADO Dialects -- Driver support for basic SQL Generation -- Copyright (C) 2010, 2011, 2012, 2015 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- package body ADO.Drivers.Dialects is -- -------------------- -- Get the quote character to escape an identifier. -- -------------------- function Get_Identifier_Quote (D : in Dialect) return Character is pragma Unreferenced (D); begin return '`'; end Get_Identifier_Quote; -- ------------------------------ -- Append the item in the buffer escaping some characters if necessary. -- The default implementation only escapes the single quote ' by doubling them. -- ------------------------------ procedure Escape_Sql (D : in Dialect; Buffer : in out Unbounded_String; Item : in String) is pragma Unreferenced (D); C : Character; begin for I in Item'Range loop C := Item (I); if C = ''' then Append (Buffer, '''); end if; Append (Buffer, C); end loop; end Escape_Sql; -- ------------------------------ -- Append the item in the buffer escaping some characters if necessary -- ------------------------------ procedure Escape_Sql (D : in Dialect; Buffer : in out Unbounded_String; Item : in ADO.Blob_Ref) is pragma Unreferenced (D); use type Ada.Streams.Stream_Element; C : Ada.Streams.Stream_Element; Blob : constant ADO.Blob_Access := Item.Value; begin for I in Blob.Data'Range loop C := Blob.Data (I); case C is when Character'Pos (ASCII.NUL) => Append (Buffer, '\'); Append (Buffer, '0'); when Character'Pos (ASCII.CR) => Append (Buffer, '\'); Append (Buffer, 'r'); when Character'Pos (ASCII.LF) => Append (Buffer, '\'); Append (Buffer, 'n'); when Character'Pos ('\') | Character'Pos (''') | Character'Pos ('"') => Append (Buffer, '\'); Append (Buffer, Character'Val (C)); when others => Append (Buffer, Character'Val (C)); end case; end loop; end Escape_Sql; end ADO.Drivers.Dialects;
----------------------------------------------------------------------- -- ADO Dialects -- Driver support for basic SQL Generation -- Copyright (C) 2010, 2011, 2012, 2015 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- package body ADO.Drivers.Dialects is -- -------------------- -- Get the quote character to escape an identifier. -- -------------------- function Get_Identifier_Quote (D : in Dialect) return Character is pragma Unreferenced (D); begin return '`'; end Get_Identifier_Quote; -- ------------------------------ -- Append the item in the buffer escaping some characters if necessary. -- The default implementation only escapes the single quote ' by doubling them. -- ------------------------------ procedure Escape_Sql (D : in Dialect; Buffer : in out Unbounded_String; Item : in String) is pragma Unreferenced (D); C : Character; begin for I in Item'Range loop C := Item (I); if C = ''' then Append (Buffer, '''); end if; Append (Buffer, C); end loop; end Escape_Sql; -- ------------------------------ -- Append the item in the buffer escaping some characters if necessary -- ------------------------------ procedure Escape_Sql (D : in Dialect; Buffer : in out Unbounded_String; Item : in ADO.Blob_Ref) is pragma Unreferenced (D); C : Ada.Streams.Stream_Element; Blob : constant ADO.Blob_Access := Item.Value; begin for I in Blob.Data'Range loop C := Blob.Data (I); case C is when Character'Pos (ASCII.NUL) => Append (Buffer, '\'); Append (Buffer, '0'); when Character'Pos (ASCII.CR) => Append (Buffer, '\'); Append (Buffer, 'r'); when Character'Pos (ASCII.LF) => Append (Buffer, '\'); Append (Buffer, 'n'); when Character'Pos ('\') | Character'Pos (''') | Character'Pos ('"') => Append (Buffer, '\'); Append (Buffer, Character'Val (C)); when others => Append (Buffer, Character'Val (C)); end case; end loop; end Escape_Sql; end ADO.Drivers.Dialects;
Remove unecessary use clause
Remove unecessary use clause
Ada
apache-2.0
stcarrez/ada-ado
a4cadf8c94291c26e237c83f9e8a5ecdb3a32ac0
regtests/util-beans-objects-discrete_tests.adb
regtests/util-beans-objects-discrete_tests.adb
----------------------------------------------------------------------- -- Util.Beans.Objects.Discrete_Tests - Generic simple test for discrete object types -- Copyright (C) 2009, 2010, 2011, 2018, 2021, 2022 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Containers; with Ada.Strings.Fixed; with Ada.Text_IO; with Ada.Calendar; with Util.Test_Caller; with Util.Beans.Objects.Hash; package body Util.Beans.Objects.Discrete_Tests is use Ada.Strings.Fixed; use Ada.Containers; procedure Test_Eq (T : Test; V : String; N : Test_Type); procedure Test_Conversion (T : Test; V : String; N : Test_Type); procedure Test_Lt_Gt (T : Test; V : String; N : Test_Type); procedure Test_Le_Ge (T : Test; V : String; N : Test_Type); procedure Test_Sub (T : Test; V : String; N : Test_Type); procedure Test_Add (T : Test; V : String; N : Test_Type); procedure Test_Perf (T : Test; V : String; N : Test_Type); procedure Test_Hash (T : in out Test); -- Generic test for To_Object and To_XXX types -- Several values are specified in the Test_Values string. generic with procedure Basic_Test (T : in Test; V : String; N : Test_Type); procedure Test_Basic_Object (T : in out Test); procedure Test_Basic_Object (T : in out Test) is pragma Unmodified (T); Pos, Next : Natural; begin Pos := Test_Values'First; while Pos <= Test_Values'Last loop Next := Index (Test_Values, ",", Pos); if Next < Pos then Next := Test_Values'Last + 1; end if; declare V : constant String := Test_Values (Pos .. Next - 1); N : constant Test_Type := Value (V); begin Basic_Test (T, V, N); end; Pos := Next + 1; end loop; end Test_Basic_Object; -- ------------------------------ -- Test Util.Beans.Objects.To_Object -- ------------------------------ procedure Test_Conversion (T : Test; V : String; N : Test_Type) is Value : Util.Beans.Objects.Object; begin Value := To_Object (V); T.Assert (Condition => To_Type (Value) = N, Message => Test_Name & " returned invalid value: " & To_String (Value) & " when we expected: " & V); T.Assert (Condition => V = To_String (Value), Message => Test_Name & ".To_String returned invalid value: " & To_String (Value) & " when we expected: " & V); end Test_Conversion; procedure Test_To_Object is new Test_Basic_Object (Basic_Test => Test_Conversion); -- ------------------------------ -- Test Util.Beans.Objects.Hash -- ------------------------------ procedure Test_Hash (T : in out Test) is pragma Unmodified (T); Pos, Next : Natural; Hash_Values : array (Test_Values'Range) of Hash_Type := (others => 0); Nb_Hash : Natural := 0; begin Pos := Test_Values'First; while Pos <= Test_Values'Last loop Next := Index (Test_Values, ",", Pos); if Next < Pos then Next := Test_Values'Last + 1; end if; declare V : constant String := Test_Values (Pos .. Next - 1); N : constant Test_Type := Value (V); Value : constant Util.Beans.Objects.Object := To_Object_Test (N); H : constant Hash_Type := Util.Beans.Objects.Hash (Value); Found : Boolean := False; begin for J in 1 .. Nb_Hash loop if Hash_Values (J) = H then Found := True; end if; end loop; if not Found then Nb_Hash := Nb_Hash + 1; Hash_Values (Nb_Hash) := H; end if; end; Pos := Next + 1; end loop; Ada.Text_IO.Put_Line ("Found " & Natural'Image (Nb_Hash) & " hash values"); T.Assert (Nb_Hash > 1, "Only one hash value found"); end Test_Hash; -- ------------------------------ -- Test Util.Beans.Objects."+" -- ------------------------------ procedure Test_Add (T : Test; V : String; N : Test_Type) is Value : Util.Beans.Objects.Object := To_Object_Test (N); begin Value := Value + To_Object_Test (N); T.Assert (Condition => To_Type (Value) = N + N, Message => Test_Name & " returned invalid value: " & To_String (Value) & " when we expected: " & V); end Test_Add; procedure Test_Add is new Test_Basic_Object (Test_Add); -- ------------------------------ -- Test Util.Beans.Objects."-" -- ------------------------------ procedure Test_Sub (T : Test; V : String; N : Test_Type) is pragma Unreferenced (V); Value : Util.Beans.Objects.Object; begin Value := To_Object_Test (N) - To_Object_Test (N); T.Assert (Condition => To_Type (Value) = N - N, Message => Test_Name & " returned invalid value: " & To_String (Value) & " when we expected: 0"); end Test_Sub; procedure Test_Sub is new Test_Basic_Object (Test_Sub); -- ------------------------------ -- Test Util.Beans.Objects."<" and Util.Beans.Objects.">" -- ------------------------------ procedure Test_Lt_Gt (T : Test; V : String; N : Test_Type) is Res : Boolean; Is_Neg : constant Boolean := Index (V, "-") = V'First; O : constant Util.Beans.Objects.Object := To_Object_Test (N); begin Res := To_Object_Test (N) < To_Object_Test (N); T.Assert (Condition => Res = False, Message => Test_Name & ".'<' returned invalid value: " & Boolean'Image (Res) & " when we expected: false"); Res := To_Object_Test (N) > To_Object_Test (N); T.Assert (Condition => Res = False, Message => Test_Name & ".'>' returned invalid value: " & Boolean'Image (Res) & " when we expected: false"); Res := To_Object_Test (N) + To_Object_Test (N) < To_Object_Test (N); T.Assert (Condition => Res = Is_Neg, Message => Test_Name & ".'<' returned invalid value: " & Boolean'Image (Res) & " when we expected: " & Boolean'Image (Is_Neg) & " with value: " & V & "Num=" & Long_Long_Integer'Image (To_Long_Long_Integer (O)) & " Sum=" & Long_Long_Integer'Image (To_Long_Long_Integer (O + O))); Res := To_Object_Test (N) > To_Object_Test (N) + To_Object_Test (N); T.Assert (Condition => Res = Is_Neg, Message => Test_Name & ".'>' returned invalid value: " & Boolean'Image (Res) & " when we expected: " & Boolean'Image (Is_Neg) & " with value: " & V); if V /= "0" and V /= "false" and V /= "true" then Res := To_Object_Test (N) < To_Object_Test (N) + To_Object_Test (N); T.Assert (Condition => Res = not Is_Neg, Message => Test_Name & ".'<' returned invalid value: " & Boolean'Image (Res) & " when we expected: " & Boolean'Image (not Is_Neg) & " with value: " & V); Res := To_Object_Test (N) + To_Object_Test (N) > To_Object_Test (N); T.Assert (Condition => Res = not Is_Neg, Message => Test_Name & ".'>' returned invalid value: " & Boolean'Image (Res) & " when we expected: " & Boolean'Image (not Is_Neg) & " with value: " & V); end if; end Test_Lt_Gt; -- ------------------------------ -- Test Util.Beans.Objects."<" and Util.Beans.Objects.">" -- ------------------------------ procedure Test_Le_Ge (T : Test; V : String; N : Test_Type) is Res : Boolean; Is_Neg : constant Boolean := Index (V, "-") = V'First; O : constant Util.Beans.Objects.Object := To_Object_Test (N); begin Res := To_Object_Test (N) <= To_Object_Test (N); T.Assert (Condition => Res, Message => Test_Name & ".'<=' returned invalid value: " & Boolean'Image (Res) & " when we expected: true"); Res := To_Object_Test (N) >= To_Object_Test (N); T.Assert (Condition => Res, Message => Test_Name & ".'>=' returned invalid value: " & Boolean'Image (Res) & " when we expected: true"); if To_Object_Test (N) + To_Object_Test (N) /= To_Object_Test (N) then Res := To_Object_Test (N) + To_Object_Test (N) <= To_Object_Test (N); T.Assert (Condition => Res = Is_Neg, Message => Test_Name & ".'<=' returned invalid value: " & Boolean'Image (Res) & " when we expected: " & Boolean'Image (Is_Neg) & " with value: " & V & "Num=" & Long_Long_Integer'Image (To_Long_Long_Integer (O)) & " Sum=" & Long_Long_Integer'Image (To_Long_Long_Integer (O + O))); Res := To_Object_Test (N) >= To_Object_Test (N) + To_Object_Test (N); T.Assert (Condition => Res = Is_Neg, Message => Test_Name & ".'>' returned invalid value: " & Boolean'Image (Res) & " when we expected: " & Boolean'Image (Is_Neg) & " with value: " & V); end if; if V /= "0" and V /= "false" and V /= "true" then Res := To_Object_Test (N) <= To_Object_Test (N) + To_Object_Test (N); T.Assert (Condition => Res = not Is_Neg, Message => Test_Name & ".'<' returned invalid value: " & Boolean'Image (Res) & " when we expected: " & Boolean'Image (not Is_Neg) & " with value: " & V); Res := To_Object_Test (N) + To_Object_Test (N) >= To_Object_Test (N); T.Assert (Condition => Res = not Is_Neg, Message => Test_Name & ".'>' returned invalid value: " & Boolean'Image (Res) & " when we expected: " & Boolean'Image (not Is_Neg) & " with value: " & V); end if; end Test_Le_Ge; procedure Test_Lt_Gt is new Test_Basic_Object (Test_Lt_Gt); procedure Test_Le_Ge is new Test_Basic_Object (Test_Le_Ge); -- ------------------------------ -- Test Util.Beans.Objects."=" -- ------------------------------ procedure Test_Eq (T : Test; V : String; N : Test_Type) is Res : Boolean; begin Res := To_Object_Test (N) = To_Object_Test (N); T.Assert (Condition => Res, Message => Test_Name & ".'=' returned invalid value: " & Boolean'Image (Res) & " when we expected: true"); Res := To_Object_Test (N) = To_Object ("Something" & V); T.Assert (Condition => Res = False, Message => Test_Name & ".'=' returned invalid value: " & Boolean'Image (Res) & " where we expected: False"); end Test_Eq; procedure Test_Eq is new Test_Basic_Object (Test_Eq); -- ------------------------------ -- Test Util.Beans.Objects."=" -- ------------------------------ procedure Test_Perf (T : Test; V : String; N : Test_Type) is pragma Unreferenced (T, V); use Ada.Calendar; Start : Ada.Calendar.Time; Value : constant Util.Beans.Objects.Object := To_Object_Test (N); D : Duration; begin Start := Ada.Calendar.Clock; for I in 1 .. 1_000 loop declare V : Util.Beans.Objects.Object := Value; begin V := V + V; pragma Unreferenced (V); end; end loop; D := Ada.Calendar.Clock - Start; Ada.Text_IO.Put_Line ("Perf " & Test_Name & ": " & Duration'Image (D * 1000.0)); end Test_Perf; procedure Test_Perf is new Test_Basic_Object (Test_Perf); package Caller is new Util.Test_Caller (Test, "Beans.Objects." & Test_Name); procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is begin Caller.Add_Test (Suite, "Test Util.Beans.Objects.To_Object." & Test_Name, Test_To_Object'Access); Caller.Add_Test (Suite, "Test Util.Beans.Objects.To_String." & Test_Name, Test_To_Object'Access); Caller.Add_Test (Suite, "Test Util.Beans.Objects.'='." & Test_Name, Test_Eq'Access); Caller.Add_Test (Suite, "Test Util.Beans.Objects.'+'." & Test_Name, Test_Add'Access); Caller.Add_Test (Suite, "Test Util.Beans.Objects.'-'." & Test_Name, Test_Sub'Access); Caller.Add_Test (Suite, "Test Util.Beans.Objects.'<'." & Test_Name, Test_Lt_Gt'Access); Caller.Add_Test (Suite, "Test Util.Beans.Objects.'>'." & Test_Name, Test_Lt_Gt'Access); Caller.Add_Test (Suite, "Test Util.Beans.Objects.'<='." & Test_Name, Test_Le_Ge'Access); Caller.Add_Test (Suite, "Test Util.Beans.Objects.'>='." & Test_Name, Test_Le_Ge'Access); Caller.Add_Test (Suite, "Performance Util.Beans.Objects.'>'." & Test_Name, Test_Perf'Access); Caller.Add_Test (Suite, "Test Util.Beans.Objects.Hash." & Test_Name, Test_Hash'Access); end Add_Tests; end Util.Beans.Objects.Discrete_Tests;
----------------------------------------------------------------------- -- Util.Beans.Objects.Discrete_Tests - Generic simple test for discrete object types -- Copyright (C) 2009, 2010, 2011, 2018, 2021, 2022 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Containers; with Ada.Strings.Fixed; with Ada.Text_IO; with Ada.Calendar; with Ada.Characters.Conversions; with Util.Test_Caller; with Util.Beans.Objects.Hash; package body Util.Beans.Objects.Discrete_Tests is use Ada.Strings.Fixed; use Ada.Containers; procedure Test_Eq (T : Test; V : String; N : Test_Type); procedure Test_Conversion (T : Test; V : String; N : Test_Type); procedure Test_Lt_Gt (T : Test; V : String; N : Test_Type); procedure Test_Le_Ge (T : Test; V : String; N : Test_Type); procedure Test_Sub (T : Test; V : String; N : Test_Type); procedure Test_Add (T : Test; V : String; N : Test_Type); procedure Test_Perf (T : Test; V : String; N : Test_Type); procedure Test_Hash (T : in out Test); -- Generic test for To_Object and To_XXX types -- Several values are specified in the Test_Values string. generic with procedure Basic_Test (T : in Test; V : String; N : Test_Type); procedure Test_Basic_Object (T : in out Test); procedure Test_Basic_Object (T : in out Test) is pragma Unmodified (T); Pos, Next : Natural; begin Pos := Test_Values'First; while Pos <= Test_Values'Last loop Next := Index (Test_Values, ",", Pos); if Next < Pos then Next := Test_Values'Last + 1; end if; declare V : constant String := Test_Values (Pos .. Next - 1); N : constant Test_Type := Value (V); begin Basic_Test (T, V, N); end; Pos := Next + 1; end loop; end Test_Basic_Object; -- ------------------------------ -- Test Util.Beans.Objects.To_Object -- ------------------------------ procedure Test_Conversion (T : Test; V : String; N : Test_Type) is Value : Util.Beans.Objects.Object; begin Value := To_Object (V); T.Assert (Condition => To_Type (Value) = N, Message => Test_Name & " returned invalid value: " & To_String (Value) & " when we expected: " & V); T.Assert (Condition => V = To_String (Value), Message => Test_Name & ".To_String returned invalid value: " & To_String (Value) & " when we expected: " & V); declare Val : Ada.Strings.Unbounded.Unbounded_String; Value2 : Util.Beans.Objects.Object; begin Val := Ada.Strings.Unbounded.To_Unbounded_String (V); Value2 := To_Object (Val); T.Assert (Value2 = Value, "Invalid value"); T.Assert (Condition => To_Type (Value2) = N, Message => Test_Name & " returned invalid value: " & To_String (Value2) & " when we expected: " & V); end; declare Val : constant Wide_Wide_String := Ada.Characters.Conversions.To_Wide_Wide_String (V); Value2 : Util.Beans.Objects.Object; begin Value2 := To_Object (Val); T.Assert (Value2 = Value, "Invalid value"); T.Assert (Condition => To_Type (Value2) = N, Message => Test_Name & " returned invalid value: " & To_String (Value2) & " when we expected: " & V); end; end Test_Conversion; procedure Test_To_Object is new Test_Basic_Object (Basic_Test => Test_Conversion); -- ------------------------------ -- Test Util.Beans.Objects.Hash -- ------------------------------ procedure Test_Hash (T : in out Test) is pragma Unmodified (T); Pos, Next : Natural; Hash_Values : array (Test_Values'Range) of Hash_Type := (others => 0); Nb_Hash : Natural := 0; begin Pos := Test_Values'First; while Pos <= Test_Values'Last loop Next := Index (Test_Values, ",", Pos); if Next < Pos then Next := Test_Values'Last + 1; end if; declare V : constant String := Test_Values (Pos .. Next - 1); N : constant Test_Type := Value (V); Value : constant Util.Beans.Objects.Object := To_Object_Test (N); H : constant Hash_Type := Util.Beans.Objects.Hash (Value); Found : Boolean := False; begin for J in 1 .. Nb_Hash loop if Hash_Values (J) = H then Found := True; end if; end loop; if not Found then Nb_Hash := Nb_Hash + 1; Hash_Values (Nb_Hash) := H; end if; end; Pos := Next + 1; end loop; Ada.Text_IO.Put_Line ("Found " & Natural'Image (Nb_Hash) & " hash values"); T.Assert (Nb_Hash > 1, "Only one hash value found"); end Test_Hash; -- ------------------------------ -- Test Util.Beans.Objects."+" -- ------------------------------ procedure Test_Add (T : Test; V : String; N : Test_Type) is Value : Util.Beans.Objects.Object := To_Object_Test (N); begin Value := Value + To_Object_Test (N); T.Assert (Condition => To_Type (Value) = N + N, Message => Test_Name & " returned invalid value: " & To_String (Value) & " when we expected: " & V); end Test_Add; procedure Test_Add is new Test_Basic_Object (Test_Add); -- ------------------------------ -- Test Util.Beans.Objects."-" -- ------------------------------ procedure Test_Sub (T : Test; V : String; N : Test_Type) is pragma Unreferenced (V); Value : Util.Beans.Objects.Object; begin Value := To_Object_Test (N) - To_Object_Test (N); T.Assert (Condition => To_Type (Value) = N - N, Message => Test_Name & " returned invalid value: " & To_String (Value) & " when we expected: 0"); end Test_Sub; procedure Test_Sub is new Test_Basic_Object (Test_Sub); -- ------------------------------ -- Test Util.Beans.Objects."<" and Util.Beans.Objects.">" -- ------------------------------ procedure Test_Lt_Gt (T : Test; V : String; N : Test_Type) is Res : Boolean; Is_Neg : constant Boolean := Index (V, "-") = V'First; O : constant Util.Beans.Objects.Object := To_Object_Test (N); begin Res := To_Object_Test (N) < To_Object_Test (N); T.Assert (Condition => Res = False, Message => Test_Name & ".'<' returned invalid value: " & Boolean'Image (Res) & " when we expected: false"); Res := To_Object_Test (N) > To_Object_Test (N); T.Assert (Condition => Res = False, Message => Test_Name & ".'>' returned invalid value: " & Boolean'Image (Res) & " when we expected: false"); Res := To_Object_Test (N) + To_Object_Test (N) < To_Object_Test (N); T.Assert (Condition => Res = Is_Neg, Message => Test_Name & ".'<' returned invalid value: " & Boolean'Image (Res) & " when we expected: " & Boolean'Image (Is_Neg) & " with value: " & V & "Num=" & Long_Long_Integer'Image (To_Long_Long_Integer (O)) & " Sum=" & Long_Long_Integer'Image (To_Long_Long_Integer (O + O))); Res := To_Object_Test (N) > To_Object_Test (N) + To_Object_Test (N); T.Assert (Condition => Res = Is_Neg, Message => Test_Name & ".'>' returned invalid value: " & Boolean'Image (Res) & " when we expected: " & Boolean'Image (Is_Neg) & " with value: " & V); if V /= "0" and V /= "false" and V /= "true" then Res := To_Object_Test (N) < To_Object_Test (N) + To_Object_Test (N); T.Assert (Condition => Res = not Is_Neg, Message => Test_Name & ".'<' returned invalid value: " & Boolean'Image (Res) & " when we expected: " & Boolean'Image (not Is_Neg) & " with value: " & V); Res := To_Object_Test (N) + To_Object_Test (N) > To_Object_Test (N); T.Assert (Condition => Res = not Is_Neg, Message => Test_Name & ".'>' returned invalid value: " & Boolean'Image (Res) & " when we expected: " & Boolean'Image (not Is_Neg) & " with value: " & V); end if; end Test_Lt_Gt; -- ------------------------------ -- Test Util.Beans.Objects."<" and Util.Beans.Objects.">" -- ------------------------------ procedure Test_Le_Ge (T : Test; V : String; N : Test_Type) is Res : Boolean; Is_Neg : constant Boolean := Index (V, "-") = V'First; O : constant Util.Beans.Objects.Object := To_Object_Test (N); begin Res := To_Object_Test (N) <= To_Object_Test (N); T.Assert (Condition => Res, Message => Test_Name & ".'<=' returned invalid value: " & Boolean'Image (Res) & " when we expected: true"); Res := To_Object_Test (N) >= To_Object_Test (N); T.Assert (Condition => Res, Message => Test_Name & ".'>=' returned invalid value: " & Boolean'Image (Res) & " when we expected: true"); if To_Object_Test (N) + To_Object_Test (N) /= To_Object_Test (N) then Res := To_Object_Test (N) + To_Object_Test (N) <= To_Object_Test (N); T.Assert (Condition => Res = Is_Neg, Message => Test_Name & ".'<=' returned invalid value: " & Boolean'Image (Res) & " when we expected: " & Boolean'Image (Is_Neg) & " with value: " & V & "Num=" & Long_Long_Integer'Image (To_Long_Long_Integer (O)) & " Sum=" & Long_Long_Integer'Image (To_Long_Long_Integer (O + O))); Res := To_Object_Test (N) >= To_Object_Test (N) + To_Object_Test (N); T.Assert (Condition => Res = Is_Neg, Message => Test_Name & ".'>' returned invalid value: " & Boolean'Image (Res) & " when we expected: " & Boolean'Image (Is_Neg) & " with value: " & V); end if; if V /= "0" and V /= "false" and V /= "true" then Res := To_Object_Test (N) <= To_Object_Test (N) + To_Object_Test (N); T.Assert (Condition => Res = not Is_Neg, Message => Test_Name & ".'<' returned invalid value: " & Boolean'Image (Res) & " when we expected: " & Boolean'Image (not Is_Neg) & " with value: " & V); Res := To_Object_Test (N) + To_Object_Test (N) >= To_Object_Test (N); T.Assert (Condition => Res = not Is_Neg, Message => Test_Name & ".'>' returned invalid value: " & Boolean'Image (Res) & " when we expected: " & Boolean'Image (not Is_Neg) & " with value: " & V); end if; end Test_Le_Ge; procedure Test_Lt_Gt is new Test_Basic_Object (Test_Lt_Gt); procedure Test_Le_Ge is new Test_Basic_Object (Test_Le_Ge); -- ------------------------------ -- Test Util.Beans.Objects."=" -- ------------------------------ procedure Test_Eq (T : Test; V : String; N : Test_Type) is Res : Boolean; begin Res := To_Object_Test (N) = To_Object_Test (N); T.Assert (Condition => Res, Message => Test_Name & ".'=' returned invalid value: " & Boolean'Image (Res) & " when we expected: true"); Res := To_Object_Test (N) = To_Object ("Something" & V); T.Assert (Condition => Res = False, Message => Test_Name & ".'=' returned invalid value: " & Boolean'Image (Res) & " where we expected: False"); end Test_Eq; procedure Test_Eq is new Test_Basic_Object (Test_Eq); -- ------------------------------ -- Test Util.Beans.Objects."=" -- ------------------------------ procedure Test_Perf (T : Test; V : String; N : Test_Type) is pragma Unreferenced (T, V); use Ada.Calendar; Start : Ada.Calendar.Time; Value : constant Util.Beans.Objects.Object := To_Object_Test (N); D : Duration; begin Start := Ada.Calendar.Clock; for I in 1 .. 1_000 loop declare V : Util.Beans.Objects.Object := Value; begin V := V + V; pragma Unreferenced (V); end; end loop; D := Ada.Calendar.Clock - Start; Ada.Text_IO.Put_Line ("Perf " & Test_Name & ": " & Duration'Image (D * 1000.0)); end Test_Perf; procedure Test_Perf is new Test_Basic_Object (Test_Perf); package Caller is new Util.Test_Caller (Test, "Beans.Objects." & Test_Name); procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is begin Caller.Add_Test (Suite, "Test Util.Beans.Objects.To_Object." & Test_Name, Test_To_Object'Access); Caller.Add_Test (Suite, "Test Util.Beans.Objects.To_String." & Test_Name, Test_To_Object'Access); Caller.Add_Test (Suite, "Test Util.Beans.Objects.'='." & Test_Name, Test_Eq'Access); Caller.Add_Test (Suite, "Test Util.Beans.Objects.'+'." & Test_Name, Test_Add'Access); Caller.Add_Test (Suite, "Test Util.Beans.Objects.'-'." & Test_Name, Test_Sub'Access); Caller.Add_Test (Suite, "Test Util.Beans.Objects.'<'." & Test_Name, Test_Lt_Gt'Access); Caller.Add_Test (Suite, "Test Util.Beans.Objects.'>'." & Test_Name, Test_Lt_Gt'Access); Caller.Add_Test (Suite, "Test Util.Beans.Objects.'<='." & Test_Name, Test_Le_Ge'Access); Caller.Add_Test (Suite, "Test Util.Beans.Objects.'>='." & Test_Name, Test_Le_Ge'Access); Caller.Add_Test (Suite, "Performance Util.Beans.Objects.'>'." & Test_Name, Test_Perf'Access); Caller.Add_Test (Suite, "Test Util.Beans.Objects.Hash." & Test_Name, Test_Hash'Access); end Add_Tests; end Util.Beans.Objects.Discrete_Tests;
Add more tests on discrete Object types
Add more tests on discrete Object types
Ada
apache-2.0
stcarrez/ada-util,stcarrez/ada-util
b9a6d839939c049ea07cf94e02f3b7214a640a53
src/util-properties.ads
src/util-properties.ads
----------------------------------------------------------------------- -- properties -- Generic name/value property management -- Copyright (C) 2001, 2002, 2003, 2006, 2008, 2009, 2010, 2014, 2017 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Strings.Unbounded; with Ada.Finalization; with Ada.Text_IO; with Util.Beans.Objects; with Util.Beans.Basic; private with Util.Concurrent.Counters; private with Util.Beans.Objects.Maps; package Util.Properties is NO_PROPERTY : exception; use Ada.Strings.Unbounded; subtype Value is Ada.Strings.Unbounded.Unbounded_String; function "+" (S : String) return Value renames To_Unbounded_String; function "-" (S : Value) return String renames To_String; -- The manager holding the name/value pairs and providing the operations -- to get and set the properties. type Manager is new Ada.Finalization.Controlled and Util.Beans.Basic.Bean with private; type Manager_Access is access all Manager'Class; -- Get the value identified by the name. -- If the name cannot be found, the method should return the Null object. overriding function Get_Value (From : in Manager; Name : in String) return Util.Beans.Objects.Object; -- Set the value identified by the name. -- If the map contains the given name, the value changed. -- Otherwise name is added to the map and the value associated with it. overriding procedure Set_Value (From : in out Manager; Name : in String; Value : in Util.Beans.Objects.Object); -- Returns TRUE if the property exists. function Exists (Self : in Manager'Class; Name : in Value) return Boolean; -- Returns TRUE if the property exists. function Exists (Self : in Manager'Class; Name : in String) return Boolean; -- Returns the property value. Raises an exception if not found. function Get (Self : in Manager'Class; Name : in String) return String; -- Returns the property value. Raises an exception if not found. function Get (Self : in Manager'Class; Name : in String) return Value; -- Returns the property value. Raises an exception if not found. function Get (Self : in Manager'Class; Name : in Value) return Value; -- Returns the property value. Raises an exception if not found. function Get (Self : in Manager'Class; Name : in Value) return String; -- Returns the property value or Default if it does not exist. function Get (Self : in Manager'Class; Name : in String; Default : in String) return String; -- Set the value of the property. The property is created if it -- does not exists. procedure Set (Self : in out Manager'Class; Name : in String; Item : in String); -- Set the value of the property. The property is created if it -- does not exists. procedure Set (Self : in out Manager'Class; Name : in String; Item : in Value); -- Set the value of the property. The property is created if it -- does not exists. procedure Set (Self : in out Manager'Class; Name : in Unbounded_String; Item : in Value); -- Remove the property given its name. If the property does not -- exist, raises NO_PROPERTY exception. procedure Remove (Self : in out Manager'Class; Name : in String); -- Remove the property given its name. If the property does not -- exist, raises NO_PROPERTY exception. procedure Remove (Self : in out Manager'Class; Name : in Value); -- Iterate over the properties and execute the given procedure passing the -- property name and its value. procedure Iterate (Self : in Manager'Class; Process : access procedure (Name, Item : Value)); type Name_Array is array (Natural range <>) of Value; -- Return the name of the properties defined in the manager. -- When a prefix is specified, only the properties starting with -- the prefix are returned. function Get_Names (Self : in Manager; Prefix : in String := "") return Name_Array; -- Load the properties from the file input stream. The file must follow -- the definition of Java property files. When a prefix is specified, keep -- only the properties that starts with the prefix. When <b>Strip</b> is True, -- the prefix part is removed from the property name. procedure Load_Properties (Self : in out Manager'Class; File : in Ada.Text_IO.File_Type; Prefix : in String := ""; Strip : in Boolean := False); -- Load the properties from the file. The file must follow the -- definition of Java property files. When a prefix is specified, keep -- only the properties that starts with the prefix. When <b>Strip</b> is True, -- the prefix part is removed from the property name. -- Raises NAME_ERROR if the file does not exist. procedure Load_Properties (Self : in out Manager'Class; Path : in String; Prefix : in String := ""; Strip : in Boolean := False); -- Save the properties in the given file path. procedure Save_Properties (Self : in out Manager'Class; Path : in String; Prefix : in String := ""); -- Copy the properties from FROM which start with a given prefix. -- If the prefix is empty, all properties are copied. When <b>Strip</b> is True, -- the prefix part is removed from the property name. procedure Copy (Self : in out Manager'Class; From : in Manager'Class; Prefix : in String := ""; Strip : in Boolean := False); private -- Abstract interface for the implementation of Properties -- (this allows to decouples the implementation from the API) package Interface_P is type Manager is abstract limited new Util.Beans.Basic.Bean with record Count : Util.Concurrent.Counters.Counter; end record; type Manager_Access is access all Manager'Class; type Manager_Factory is access function return Manager_Access; -- Returns TRUE if the property exists. function Exists (Self : in Manager; Name : in String) return Boolean is abstract; -- Remove the property given its name. procedure Remove (Self : in out Manager; Name : in Value) is abstract; -- Iterate over the properties and execute the given procedure passing the -- property name and its value. procedure Iterate (Self : in Manager; Process : access procedure (Name, Item : Value)) is abstract; -- Deep copy of properties stored in 'From' to 'To'. function Create_Copy (Self : in Manager) return Manager_Access is abstract; function Get_Names (Self : in Manager; Prefix : in String) return Name_Array is abstract; end Interface_P; -- Create a property implementation if there is none yet. procedure Check_And_Create_Impl (Self : in out Manager); type Manager is new Ada.Finalization.Controlled and Util.Beans.Basic.Bean with record Impl : Interface_P.Manager_Access := null; end record; overriding procedure Adjust (Object : in out Manager); overriding procedure Finalize (Object : in out Manager); end Util.Properties;
----------------------------------------------------------------------- -- properties -- Generic name/value property management -- Copyright (C) 2001, 2002, 2003, 2006, 2008, 2009, 2010, 2014, 2017 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Strings.Unbounded; with Ada.Finalization; with Ada.Text_IO; with Util.Beans.Objects; with Util.Beans.Basic; with Util.Strings.Vectors; private with Util.Concurrent.Counters; private with Util.Beans.Objects.Maps; package Util.Properties is NO_PROPERTY : exception; use Ada.Strings.Unbounded; subtype Value is Ada.Strings.Unbounded.Unbounded_String; function "+" (S : String) return Value renames To_Unbounded_String; function "-" (S : Value) return String renames To_String; -- The manager holding the name/value pairs and providing the operations -- to get and set the properties. type Manager is new Ada.Finalization.Controlled and Util.Beans.Basic.Bean with private; type Manager_Access is access all Manager'Class; -- Get the value identified by the name. -- If the name cannot be found, the method should return the Null object. overriding function Get_Value (From : in Manager; Name : in String) return Util.Beans.Objects.Object; -- Set the value identified by the name. -- If the map contains the given name, the value changed. -- Otherwise name is added to the map and the value associated with it. overriding procedure Set_Value (From : in out Manager; Name : in String; Value : in Util.Beans.Objects.Object); -- Returns TRUE if the property exists. function Exists (Self : in Manager'Class; Name : in Value) return Boolean; -- Returns TRUE if the property exists. function Exists (Self : in Manager'Class; Name : in String) return Boolean; -- Returns the property value. Raises an exception if not found. function Get (Self : in Manager'Class; Name : in String) return String; -- Returns the property value. Raises an exception if not found. function Get (Self : in Manager'Class; Name : in String) return Value; -- Returns the property value. Raises an exception if not found. function Get (Self : in Manager'Class; Name : in Value) return Value; -- Returns the property value. Raises an exception if not found. function Get (Self : in Manager'Class; Name : in Value) return String; -- Returns the property value or Default if it does not exist. function Get (Self : in Manager'Class; Name : in String; Default : in String) return String; -- Set the value of the property. The property is created if it -- does not exists. procedure Set (Self : in out Manager'Class; Name : in String; Item : in String); -- Set the value of the property. The property is created if it -- does not exists. procedure Set (Self : in out Manager'Class; Name : in String; Item : in Value); -- Set the value of the property. The property is created if it -- does not exists. procedure Set (Self : in out Manager'Class; Name : in Unbounded_String; Item : in Value); -- Remove the property given its name. If the property does not -- exist, raises NO_PROPERTY exception. procedure Remove (Self : in out Manager'Class; Name : in String); -- Remove the property given its name. If the property does not -- exist, raises NO_PROPERTY exception. procedure Remove (Self : in out Manager'Class; Name : in Value); -- Iterate over the properties and execute the given procedure passing the -- property name and its value. procedure Iterate (Self : in Manager'Class; Process : access procedure (Name, Item : Value)); type Name_Array is array (Natural range <>) of Value; -- Return the name of the properties defined in the manager. -- When a prefix is specified, only the properties starting with -- the prefix are returned. function Get_Names (Self : in Manager; Prefix : in String := "") return Name_Array; -- Collect the name of the properties defined in the manager. -- When a prefix is specified, only the properties starting with the prefix are -- returned. procedure Get_Names (Self : in Manager; Into : in out Util.Strings.Vectors.Vector; Prefix : in String := ""); -- Load the properties from the file input stream. The file must follow -- the definition of Java property files. When a prefix is specified, keep -- only the properties that starts with the prefix. When <b>Strip</b> is True, -- the prefix part is removed from the property name. procedure Load_Properties (Self : in out Manager'Class; File : in Ada.Text_IO.File_Type; Prefix : in String := ""; Strip : in Boolean := False); -- Load the properties from the file. The file must follow the -- definition of Java property files. When a prefix is specified, keep -- only the properties that starts with the prefix. When <b>Strip</b> is True, -- the prefix part is removed from the property name. -- Raises NAME_ERROR if the file does not exist. procedure Load_Properties (Self : in out Manager'Class; Path : in String; Prefix : in String := ""; Strip : in Boolean := False); -- Save the properties in the given file path. procedure Save_Properties (Self : in out Manager'Class; Path : in String; Prefix : in String := ""); -- Copy the properties from FROM which start with a given prefix. -- If the prefix is empty, all properties are copied. When <b>Strip</b> is True, -- the prefix part is removed from the property name. procedure Copy (Self : in out Manager'Class; From : in Manager'Class; Prefix : in String := ""; Strip : in Boolean := False); private -- Abstract interface for the implementation of Properties -- (this allows to decouples the implementation from the API) package Interface_P is type Manager is abstract limited new Util.Beans.Basic.Bean with record Count : Util.Concurrent.Counters.Counter; end record; type Manager_Access is access all Manager'Class; -- Returns TRUE if the property exists. function Exists (Self : in Manager; Name : in String) return Boolean is abstract; -- Remove the property given its name. procedure Remove (Self : in out Manager; Name : in String) is abstract; -- Iterate over the properties and execute the given procedure passing the -- property name and its value. procedure Iterate (Self : in Manager; Process : access procedure (Name : in String; Item : in Util.Beans.Objects.Object)) is abstract; -- Deep copy of properties stored in 'From' to 'To'. function Create_Copy (Self : in Manager) return Manager_Access is abstract; end Interface_P; -- Create a property implementation if there is none yet. procedure Check_And_Create_Impl (Self : in out Manager); type Manager is new Ada.Finalization.Controlled and Util.Beans.Basic.Bean with record Impl : Interface_P.Manager_Access := null; end record; overriding procedure Adjust (Object : in out Manager); overriding procedure Finalize (Object : in out Manager); end Util.Properties;
Refactor the Properties implementation (step 3): - Declare a Get_Names procedure to collect the property names - Change the internal Remove procedure to use a String for Name parameter - Change the internal Iterate procedure to get the property value as Object
Refactor the Properties implementation (step 3): - Declare a Get_Names procedure to collect the property names - Change the internal Remove procedure to use a String for Name parameter - Change the internal Iterate procedure to get the property value as Object
Ada
apache-2.0
stcarrez/ada-util,stcarrez/ada-util
6c625ca10a331247f9aa570f9336e5d88899f1f6
src/util-events-timers.ads
src/util-events-timers.ads
----------------------------------------------------------------------- -- util-events-timers -- Timer list management -- Copyright (C) 2017 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Real_Time; private with Ada.Finalization; private with Util.Concurrent.Counters; -- == Timer Management == -- The <tt>Util.Events.Timers</tt> package provides a timer list that allows to have -- operations called on regular basis when a deadline has expired. It is very close to -- the <tt>Ada.Real_Time.Timing_Events</tt> package but it provides more flexibility -- by allowing to have several timer lists that run independently. Unlike the GNAT -- implementation, this timer list management does not use tasks at all. The timer list -- can therefore be used in a mono-task environment by the main process task. Furthermore -- you can control your own task priority by having your own task that uses the timer list. -- -- The timer list is created by an instance of <tt>Timer_List</tt>: -- -- Manager : Util.Events.Timers.Timer_List; -- -- The timer list is protected against concurrent accesses so that timing events can be -- setup by a task but the timer handler is executed by another task. -- -- === Timer Creation === -- A timer handler is defined by implementing the <tt>Timer</tt> interface with the -- <tt>Time_Handler</tt> procedure. A typical timer handler could be declared as follows: -- -- type Timeout is new Timer with null record; -- overriding procedure Time_Handler (T : in out Timeout); -- -- My_Timeout : aliased Timeout; -- -- The timer instance is represented by the <tt>Timer_Ref</tt> type that describes the handler -- to be called as well as the deadline time. The timer instance is initialized as follows: -- -- T : Util.Events.Timers.Timer_Ref; -- Manager.Set_Timer (T, My_Timeout'Access, Ada.Real_Time.Seconds (1)); -- -- === Timer Main Loop === -- Because the implementation does not impose any execution model, the timer management must -- be called regularly by some application's main loop. The <tt>Process</tt> procedure -- executes the timer handler that have ellapsed and it returns the deadline to wait for the -- next timer to execute. -- -- Deadline : Ada.Real_Time.Time; -- loop -- ... -- Manager.Process (Deadline); -- delay until Deadline; -- end loop; -- package Util.Events.Timers is type Timer_Ref is tagged private; -- The timer interface that must be implemented by applications. type Timer is limited interface; type Timer_Access is access all Timer'Class; -- The timer handler executed when the timer deadline has passed. procedure Time_Handler (T : in out Timer; Event : in out Timer_Ref'Class) is abstract; -- Repeat the timer. procedure Repeat (Event : in out Timer_Ref; In_Time : in Ada.Real_Time.Time_Span); -- Cancel the timer. procedure Cancel (Event : in out Timer_Ref); -- Check if the timer is ready to be executed. function Is_Scheduled (Event : in Timer_Ref) return Boolean; -- Returns the deadline time for the timer execution. -- Returns Time'Last if the timer is not scheduled. function Time_Of_Event (Event : in Timer_Ref) return Ada.Real_Time.Time; type Timer_List is tagged limited private; -- Set a timer to be called at the given time. procedure Set_Timer (List : in out Timer_List; Handler : in Timer_Access; Event : in out Timer_Ref'Class; At_Time : in Ada.Real_Time.Time); -- Process the timer handlers that have passed the deadline and return the next -- deadline. The <tt>Max_Count</tt> parameter allows to limit the number of timer handlers -- that are called by operation. The default is not limited. procedure Process (List : in out Timer_List; Timeout : out Ada.Real_Time.Time; Max_Count : in Natural := Natural'Last); private type Timer_Manager; type Timer_Manager_Access is access all Timer_Manager; type Timer_Node; type Timer_Node_Access is access all Timer_Node; type Timer_Ref is new Ada.Finalization.Controlled with record Value : Timer_Node_Access; end record; overriding procedure Adjust (Object : in out Timer_Ref); overriding procedure Finalize (Object : in out Timer_Ref); type Timer_Node is limited record Next : Timer_Node_Access; Prev : Timer_Node_Access; List : Timer_Manager_Access; Counter : Util.Concurrent.Counters.Counter; Handler : Timer_Access; Deadline : Ada.Real_Time.Time; end record; protected type Timer_Manager is -- Add a timer. procedure Add (Timer : in out Timer_Node_Access; Deadline : in Ada.Real_Time.Time); -- Cancel a timer. procedure Cancel (Timer : in out Timer_Node_Access); -- Find the next timer to be executed or return the next deadline. procedure Find_Next (Deadline : out Ada.Real_Time.Time; Timer : in out Timer_Ref); private List : Timer_Node_Access; end Timer_Manager; type Timer_List is new Ada.Finalization.Limited_Controlled with record Manager : aliased Timer_Manager; end record; overriding procedure Finalize (Object : in out Timer_List); end Util.Events.Timers;
----------------------------------------------------------------------- -- util-events-timers -- Timer list management -- Copyright (C) 2017 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Real_Time; private with Ada.Finalization; private with Util.Concurrent.Counters; -- == Timer Management == -- The <tt>Util.Events.Timers</tt> package provides a timer list that allows to have -- operations called on regular basis when a deadline has expired. It is very close to -- the <tt>Ada.Real_Time.Timing_Events</tt> package but it provides more flexibility -- by allowing to have several timer lists that run independently. Unlike the GNAT -- implementation, this timer list management does not use tasks at all. The timer list -- can therefore be used in a mono-task environment by the main process task. Furthermore -- you can control your own task priority by having your own task that uses the timer list. -- -- The timer list is created by an instance of <tt>Timer_List</tt>: -- -- Manager : Util.Events.Timers.Timer_List; -- -- The timer list is protected against concurrent accesses so that timing events can be -- setup by a task but the timer handler is executed by another task. -- -- === Timer Creation === -- A timer handler is defined by implementing the <tt>Timer</tt> interface with the -- <tt>Time_Handler</tt> procedure. A typical timer handler could be declared as follows: -- -- type Timeout is new Timer with null record; -- overriding procedure Time_Handler (T : in out Timeout); -- -- My_Timeout : aliased Timeout; -- -- The timer instance is represented by the <tt>Timer_Ref</tt> type that describes the handler -- to be called as well as the deadline time. The timer instance is initialized as follows: -- -- T : Util.Events.Timers.Timer_Ref; -- Manager.Set_Timer (T, My_Timeout'Access, Ada.Real_Time.Seconds (1)); -- -- === Timer Main Loop === -- Because the implementation does not impose any execution model, the timer management must -- be called regularly by some application's main loop. The <tt>Process</tt> procedure -- executes the timer handler that have ellapsed and it returns the deadline to wait for the -- next timer to execute. -- -- Deadline : Ada.Real_Time.Time; -- loop -- ... -- Manager.Process (Deadline); -- delay until Deadline; -- end loop; -- package Util.Events.Timers is type Timer_Ref is tagged private; -- The timer interface that must be implemented by applications. type Timer is limited interface; type Timer_Access is access all Timer'Class; -- The timer handler executed when the timer deadline has passed. procedure Time_Handler (T : in out Timer; Event : in out Timer_Ref'Class) is abstract; -- Repeat the timer. procedure Repeat (Event : in out Timer_Ref; In_Time : in Ada.Real_Time.Time_Span); -- Cancel the timer. procedure Cancel (Event : in out Timer_Ref); -- Check if the timer is ready to be executed. function Is_Scheduled (Event : in Timer_Ref) return Boolean; -- Returns the deadline time for the timer execution. -- Returns Time'Last if the timer is not scheduled. function Time_Of_Event (Event : in Timer_Ref) return Ada.Real_Time.Time; type Timer_List is tagged limited private; -- Set a timer to be called at the given time. procedure Set_Timer (List : in out Timer_List; Handler : in Timer_Access; Event : in out Timer_Ref'Class; At_Time : in Ada.Real_Time.Time); -- Process the timer handlers that have passed the deadline and return the next -- deadline. The <tt>Max_Count</tt> parameter allows to limit the number of timer handlers -- that are called by operation. The default is not limited. procedure Process (List : in out Timer_List; Timeout : out Ada.Real_Time.Time; Max_Count : in Natural := Natural'Last); private type Timer_Manager; type Timer_Manager_Access is access all Timer_Manager; type Timer_Node; type Timer_Node_Access is access all Timer_Node; type Timer_Ref is new Ada.Finalization.Controlled with record Value : Timer_Node_Access; end record; overriding procedure Adjust (Object : in out Timer_Ref); overriding procedure Finalize (Object : in out Timer_Ref); type Timer_Node is limited record Next : Timer_Node_Access; Prev : Timer_Node_Access; List : Timer_Manager_Access; Counter : Util.Concurrent.Counters.Counter; Handler : Timer_Access; Deadline : Ada.Real_Time.Time; end record; protected type Timer_Manager is -- Add a timer. procedure Add (Timer : in Timer_Node_Access; Deadline : in Ada.Real_Time.Time); -- Cancel a timer. procedure Cancel (Timer : in out Timer_Node_Access); -- Find the next timer to be executed or return the next deadline. procedure Find_Next (Deadline : out Ada.Real_Time.Time; Timer : in out Timer_Ref); private List : Timer_Node_Access; end Timer_Manager; type Timer_List is new Ada.Finalization.Limited_Controlled with record Manager : aliased Timer_Manager; end record; overriding procedure Finalize (Object : in out Timer_List); end Util.Events.Timers;
Change the Add protected procedure to use only 'in' parameters
Change the Add protected procedure to use only 'in' parameters
Ada
apache-2.0
stcarrez/ada-util,stcarrez/ada-util
aead48e27bdfe3584b16cfbb6280d7165d3f94e4
regtests/util-http-clients-tests.adb
regtests/util-http-clients-tests.adb
----------------------------------------------------------------------- -- util-http-clients-tests -- Unit tests for HTTP client -- Copyright (C) 2012, 2020 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Unchecked_Deallocation; with Util.Test_Caller; with Util.Strings.Transforms; with Util.Http.Tools; with Util.Strings; with Util.Log.Loggers; package body Util.Http.Clients.Tests is -- The logger Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("Util.Http.Clients.Tests"); package body Http_Tests is package Caller is new Util.Test_Caller (Http_Test, "Http-" & NAME); procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is begin Caller.Add_Test (Suite, "Test Util.Http.Clients." & NAME & ".Get", Test_Http_Get'Access); Caller.Add_Test (Suite, "Test Util.Http.Clients." & NAME & ".Post", Test_Http_Post'Access); Caller.Add_Test (Suite, "Test Util.Http.Clients." & NAME & ".Put", Test_Http_Put'Access); Caller.Add_Test (Suite, "Test Util.Http.Clients." & NAME & ".Delete", Test_Http_Delete'Access); Caller.Add_Test (Suite, "Test Util.Http.Clients." & NAME & ".Get (timeout)", Test_Http_Timeout'Access); end Add_Tests; overriding procedure Set_Up (T : in out Http_Test) is begin Test (T).Set_Up; Register; end Set_Up; end Http_Tests; overriding procedure Set_Up (T : in out Test) is begin Log.Info ("Starting test server"); T.Server := new Test_Server; T.Server.Start; end Set_Up; overriding procedure Tear_Down (T : in out Test) is procedure Free is new Ada.Unchecked_Deallocation (Object => Test_Server'Class, Name => Test_Server_Access); begin if T.Server /= null then Log.Info ("Stopping test server"); T.Server.Stop; Free (T.Server); T.Server := null; end if; end Tear_Down; -- ------------------------------ -- Process the line received by the server. -- ------------------------------ overriding procedure Process_Line (Into : in out Test_Server; Line : in Ada.Strings.Unbounded.Unbounded_String; Stream : in out Util.Streams.Texts.Reader_Stream'Class; Client : in out Util.Streams.Sockets.Socket_Stream'Class) is L : constant String := Ada.Strings.Unbounded.To_String (Line); Pos : Natural := Util.Strings.Index (L, ' '); begin if Pos > 0 and Into.Method = UNKNOWN then if L (L'First .. Pos - 1) = "GET" then Into.Method := GET; elsif L (L'First .. Pos - 1) = "POST" then Into.Method := POST; elsif L (L'First .. Pos - 1) = "PUT" then Into.Method := PUT; elsif L (L'First .. Pos - 1) = "DELETE" then Into.Method := DELETE; else Into.Method := UNKNOWN; end if; end if; Pos := Util.Strings.Index (L, ':'); if Pos > 0 then if L (L'First .. Pos) = "Content-Type:" then Into.Content_Type := Ada.Strings.Unbounded.To_Unbounded_String (L (Pos + 2 .. L'Last - 2)); elsif L (L'First .. Pos) = "Content-Length:" then Into.Length := Natural'Value (L (Pos + 1 .. L'Last - 2)); end if; end if; -- Don't answer if we check the timeout. if Into.Test_Timeout then return; end if; if L'Length = 2 and then Into.Length > 0 then for I in 1 .. Into.Length loop declare C : Character; begin Stream.Read (C); Ada.Strings.Unbounded.Append (Into.Result, C); end; end loop; declare Output : Util.Streams.Texts.Print_Stream; begin Output.Initialize (Client'Unchecked_Access); Output.Write ("HTTP/1.1 200 Found" & ASCII.CR & ASCII.LF); Output.Write ("Content-Length: 4" & ASCII.CR & ASCII.LF); Output.Write (ASCII.CR & ASCII.LF); Output.Write ("OK" & ASCII.CR & ASCII.LF); Output.Flush; end; elsif L'Length = 2 then declare Output : Util.Streams.Texts.Print_Stream; begin Output.Initialize (Client'Unchecked_Access); Output.Write ("HTTP/1.1 204 No Content" & ASCII.CR & ASCII.LF); Output.Write (ASCII.CR & ASCII.LF); Output.Flush; end; end if; Log.Info ("Received: {0}", L); end Process_Line; -- ------------------------------ -- Get the test server base URI. -- ------------------------------ function Get_Uri (T : in Test) return String is begin return "http://" & T.Server.Get_Host & ":" & Util.Strings.Image (T.Server.Get_Port); end Get_Uri; -- ------------------------------ -- Test the http Get operation. -- ------------------------------ procedure Test_Http_Get (T : in out Test) is Request : Client; Reply : Response; begin Request.Get ("http://www.google.com", Reply); Request.Set_Timeout (5.0); T.Assert (Reply.Get_Status = 200 or Reply.Get_Status = 302, "Get status is invalid: " & Natural'Image (Reply.Get_Status)); Util.Http.Tools.Save_Response (Util.Tests.Get_Test_Path ("http_get.txt"), Reply, True); -- Check the content. declare Content : constant String := Util.Strings.Transforms.To_Lower_Case (Reply.Get_Body); begin Util.Tests.Assert_Matches (T, ".*html.*", Content, "Invalid GET content"); end; T.Assert (Reply.Contains_Header ("Content-Type"), "Header Content-Type not found"); T.Assert (not Reply.Contains_Header ("Content-Type-Invalid-Missing"), "Some invalid header found"); -- Check one header. declare Content : constant String := Reply.Get_Header ("Content-Type"); begin T.Assert (Content'Length > 0, "Empty Content-Type header"); Util.Tests.Assert_Matches (T, ".*text/html.*", Content, "Invalid content type"); end; end Test_Http_Get; -- ------------------------------ -- Test the http POST operation. -- ------------------------------ procedure Test_Http_Post (T : in out Test) is Request : Client; Reply : Response; Uri : constant String := T.Get_Uri; begin Log.Info ("Post on " & Uri); T.Server.Method := UNKNOWN; Request.Post (Uri & "/post", "p1=1", Reply); T.Assert (T.Server.Method = POST, "Invalid method received by server"); Util.Tests.Assert_Equals (T, "application/x-www-form-urlencoded", T.Server.Content_Type, "Invalid content type received by server"); Util.Tests.Assert_Equals (T, "OK" & ASCII.CR & ASCII.LF, Reply.Get_Body, "Invalid response"); Util.Http.Tools.Save_Response (Util.Tests.Get_Test_Path ("http_post.txt"), Reply, True); end Test_Http_Post; -- ------------------------------ -- Test the http PUT operation. -- ------------------------------ procedure Test_Http_Put (T : in out Test) is Request : Client; Reply : Response; Uri : constant String := T.Get_Uri; begin Log.Info ("Put on " & Uri); T.Server.Method := UNKNOWN; Request.Add_Header ("Content-Type", "application/x-www-form-urlencoded"); Request.Set_Timeout (1.0); T.Assert (Request.Contains_Header ("Content-Type"), "Missing Content-Type"); Request.Put (Uri & "/put", "p1=1", Reply); T.Assert (T.Server.Method = PUT, "Invalid method received by server"); Util.Tests.Assert_Equals (T, "application/x-www-form-urlencoded", T.Server.Content_Type, "Invalid content type received by server"); Util.Tests.Assert_Equals (T, "OK" & ASCII.CR & ASCII.LF, Reply.Get_Body, "Invalid response"); Util.Http.Tools.Save_Response (Util.Tests.Get_Test_Path ("http_put.txt"), Reply, True); end Test_Http_Put; -- ------------------------------ -- Test the http DELETE operation. -- ------------------------------ procedure Test_Http_Delete (T : in out Test) is Request : Client; Reply : Response; Uri : constant String := T.Get_Uri; begin Log.Info ("Delete on " & Uri); T.Server.Method := UNKNOWN; Request.Add_Header ("Content-Type", "application/x-www-form-urlencoded"); Request.Set_Timeout (1.0); T.Assert (Request.Contains_Header ("Content-Type"), "Missing Content-Type"); Request.Delete (Uri & "/delete", Reply); T.Assert (T.Server.Method = DELETE, "Invalid method received by server"); Util.Tests.Assert_Equals (T, "application/x-www-form-urlencoded", T.Server.Content_Type, "Invalid content type received by server"); Util.Tests.Assert_Equals (T, "", Reply.Get_Body, "Invalid response"); Util.Tests.Assert_Equals (T, 204, Reply.Get_Status, "Invalid status response"); end Test_Http_Delete; -- ------------------------------ -- Test the http timeout. -- ------------------------------ procedure Test_Http_Timeout (T : in out Test) is Request : Client; Reply : Response; Uri : constant String := T.Get_Uri; begin Log.Info ("Timeout on " & Uri); T.Server.Test_Timeout := True; T.Server.Method := UNKNOWN; Request.Set_Timeout (0.5); begin Request.Get (Uri & "/timeout", Reply); T.Fail ("No Connection_Error exception raised"); exception when Connection_Error => null; end; end Test_Http_Timeout; end Util.Http.Clients.Tests;
----------------------------------------------------------------------- -- util-http-clients-tests -- Unit tests for HTTP client -- Copyright (C) 2012, 2020 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Unchecked_Deallocation; with Util.Test_Caller; with Util.Strings.Transforms; with Util.Http.Tools; with Util.Strings; with Util.Log.Loggers; package body Util.Http.Clients.Tests is -- The logger Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("Util.Http.Clients.Tests"); package body Http_Tests is package Caller is new Util.Test_Caller (Http_Test, "Http-" & NAME); procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is begin Caller.Add_Test (Suite, "Test Util.Http.Clients." & NAME & ".Get", Test_Http_Get'Access); Caller.Add_Test (Suite, "Test Util.Http.Clients." & NAME & ".Post", Test_Http_Post'Access); Caller.Add_Test (Suite, "Test Util.Http.Clients." & NAME & ".Put", Test_Http_Put'Access); Caller.Add_Test (Suite, "Test Util.Http.Clients." & NAME & ".Delete", Test_Http_Delete'Access); Caller.Add_Test (Suite, "Test Util.Http.Clients." & NAME & ".Options", Test_Http_Options'Access); Caller.Add_Test (Suite, "Test Util.Http.Clients." & NAME & ".Get (timeout)", Test_Http_Timeout'Access); end Add_Tests; overriding procedure Set_Up (T : in out Http_Test) is begin Test (T).Set_Up; Register; end Set_Up; end Http_Tests; overriding procedure Set_Up (T : in out Test) is begin Log.Info ("Starting test server"); T.Server := new Test_Server; T.Server.Start; end Set_Up; overriding procedure Tear_Down (T : in out Test) is procedure Free is new Ada.Unchecked_Deallocation (Object => Test_Server'Class, Name => Test_Server_Access); begin if T.Server /= null then Log.Info ("Stopping test server"); T.Server.Stop; Free (T.Server); T.Server := null; end if; end Tear_Down; -- ------------------------------ -- Process the line received by the server. -- ------------------------------ overriding procedure Process_Line (Into : in out Test_Server; Line : in Ada.Strings.Unbounded.Unbounded_String; Stream : in out Util.Streams.Texts.Reader_Stream'Class; Client : in out Util.Streams.Sockets.Socket_Stream'Class) is L : constant String := Ada.Strings.Unbounded.To_String (Line); Pos : Natural := Util.Strings.Index (L, ' '); begin if Pos > 0 and Into.Method = UNKNOWN then if L (L'First .. Pos - 1) = "GET" then Into.Method := GET; elsif L (L'First .. Pos - 1) = "POST" then Into.Method := POST; elsif L (L'First .. Pos - 1) = "PUT" then Into.Method := PUT; elsif L (L'First .. Pos - 1) = "DELETE" then Into.Method := DELETE; elsif L (L'First .. Pos - 1) = "OPTIONS" then Into.Method := OPTIONS; else Into.Method := UNKNOWN; end if; end if; Pos := Util.Strings.Index (L, ':'); if Pos > 0 then if L (L'First .. Pos) = "Content-Type:" then Into.Content_Type := Ada.Strings.Unbounded.To_Unbounded_String (L (Pos + 2 .. L'Last - 2)); elsif L (L'First .. Pos) = "Content-Length:" then Into.Length := Natural'Value (L (Pos + 1 .. L'Last - 2)); end if; end if; -- Don't answer if we check the timeout. if Into.Test_Timeout then return; end if; if L'Length = 2 and then Into.Length > 0 then for I in 1 .. Into.Length loop declare C : Character; begin Stream.Read (C); Ada.Strings.Unbounded.Append (Into.Result, C); end; end loop; declare Output : Util.Streams.Texts.Print_Stream; begin Output.Initialize (Client'Unchecked_Access); Output.Write ("HTTP/1.1 200 Found" & ASCII.CR & ASCII.LF); Output.Write ("Content-Length: 4" & ASCII.CR & ASCII.LF); Output.Write (ASCII.CR & ASCII.LF); Output.Write ("OK" & ASCII.CR & ASCII.LF); Output.Flush; end; elsif L'Length = 2 then declare Output : Util.Streams.Texts.Print_Stream; begin Output.Initialize (Client'Unchecked_Access); Output.Write ("HTTP/1.1 204 No Content" & ASCII.CR & ASCII.LF); Output.Write (ASCII.CR & ASCII.LF); Output.Flush; end; end if; Log.Info ("Received: {0}", L); end Process_Line; -- ------------------------------ -- Get the test server base URI. -- ------------------------------ function Get_Uri (T : in Test) return String is begin return "http://" & T.Server.Get_Host & ":" & Util.Strings.Image (T.Server.Get_Port); end Get_Uri; -- ------------------------------ -- Test the http Get operation. -- ------------------------------ procedure Test_Http_Get (T : in out Test) is Request : Client; Reply : Response; begin Request.Get ("http://www.google.com", Reply); Request.Set_Timeout (5.0); T.Assert (Reply.Get_Status = 200 or Reply.Get_Status = 302, "Get status is invalid: " & Natural'Image (Reply.Get_Status)); Util.Http.Tools.Save_Response (Util.Tests.Get_Test_Path ("http_get.txt"), Reply, True); -- Check the content. declare Content : constant String := Util.Strings.Transforms.To_Lower_Case (Reply.Get_Body); begin Util.Tests.Assert_Matches (T, ".*html.*", Content, "Invalid GET content"); end; T.Assert (Reply.Contains_Header ("Content-Type"), "Header Content-Type not found"); T.Assert (not Reply.Contains_Header ("Content-Type-Invalid-Missing"), "Some invalid header found"); -- Check one header. declare Content : constant String := Reply.Get_Header ("Content-Type"); begin T.Assert (Content'Length > 0, "Empty Content-Type header"); Util.Tests.Assert_Matches (T, ".*text/html.*", Content, "Invalid content type"); end; end Test_Http_Get; -- ------------------------------ -- Test the http POST operation. -- ------------------------------ procedure Test_Http_Post (T : in out Test) is Request : Client; Reply : Response; Uri : constant String := T.Get_Uri; begin Log.Info ("Post on " & Uri); T.Server.Method := UNKNOWN; Request.Post (Uri & "/post", "p1=1", Reply); T.Assert (T.Server.Method = POST, "Invalid method received by server"); Util.Tests.Assert_Equals (T, "application/x-www-form-urlencoded", T.Server.Content_Type, "Invalid content type received by server"); Util.Tests.Assert_Equals (T, "OK" & ASCII.CR & ASCII.LF, Reply.Get_Body, "Invalid response"); Util.Http.Tools.Save_Response (Util.Tests.Get_Test_Path ("http_post.txt"), Reply, True); end Test_Http_Post; -- ------------------------------ -- Test the http PUT operation. -- ------------------------------ procedure Test_Http_Put (T : in out Test) is Request : Client; Reply : Response; Uri : constant String := T.Get_Uri; begin Log.Info ("Put on " & Uri); T.Server.Method := UNKNOWN; Request.Add_Header ("Content-Type", "application/x-www-form-urlencoded"); Request.Set_Timeout (1.0); T.Assert (Request.Contains_Header ("Content-Type"), "Missing Content-Type"); Request.Put (Uri & "/put", "p1=1", Reply); T.Assert (T.Server.Method = PUT, "Invalid method received by server"); Util.Tests.Assert_Equals (T, "application/x-www-form-urlencoded", T.Server.Content_Type, "Invalid content type received by server"); Util.Tests.Assert_Equals (T, "OK" & ASCII.CR & ASCII.LF, Reply.Get_Body, "Invalid response"); Util.Http.Tools.Save_Response (Util.Tests.Get_Test_Path ("http_put.txt"), Reply, True); end Test_Http_Put; -- ------------------------------ -- Test the http DELETE operation. -- ------------------------------ procedure Test_Http_Delete (T : in out Test) is Request : Client; Reply : Response; Uri : constant String := T.Get_Uri; begin Log.Info ("Delete on " & Uri); T.Server.Method := UNKNOWN; Request.Add_Header ("Content-Type", "application/x-www-form-urlencoded"); Request.Set_Timeout (1.0); T.Assert (Request.Contains_Header ("Content-Type"), "Missing Content-Type"); Request.Delete (Uri & "/delete", Reply); T.Assert (T.Server.Method = DELETE, "Invalid method received by server"); Util.Tests.Assert_Equals (T, "application/x-www-form-urlencoded", T.Server.Content_Type, "Invalid content type received by server"); Util.Tests.Assert_Equals (T, "", Reply.Get_Body, "Invalid response"); Util.Tests.Assert_Equals (T, 204, Reply.Get_Status, "Invalid status response"); end Test_Http_Delete; -- ------------------------------ -- Test the http OPTIONS operation. -- ------------------------------ procedure Test_Http_Options (T : in out Test) is Request : Client; Reply : Response; Uri : constant String := T.Get_Uri; begin Log.Info ("Delete on " & Uri); T.Server.Method := UNKNOWN; Request.Add_Header ("Content-Type", "application/x-www-form-urlencoded"); Request.Set_Timeout (1.0); T.Assert (Request.Contains_Header ("Content-Type"), "Missing Content-Type"); Request.Options (Uri & "/options", Reply); T.Assert (T.Server.Method = OPTIONS, "Invalid method received by server"); Util.Tests.Assert_Equals (T, "application/x-www-form-urlencoded", T.Server.Content_Type, "Invalid content type received by server"); Util.Tests.Assert_Equals (T, "", Reply.Get_Body, "Invalid response"); Util.Tests.Assert_Equals (T, 204, Reply.Get_Status, "Invalid status response"); end Test_Http_Options; -- ------------------------------ -- Test the http timeout. -- ------------------------------ procedure Test_Http_Timeout (T : in out Test) is Request : Client; Reply : Response; Uri : constant String := T.Get_Uri; begin Log.Info ("Timeout on " & Uri); T.Server.Test_Timeout := True; T.Server.Method := UNKNOWN; Request.Set_Timeout (0.5); begin Request.Get (Uri & "/timeout", Reply); T.Fail ("No Connection_Error exception raised"); exception when Connection_Error => null; end; end Test_Http_Timeout; end Util.Http.Clients.Tests;
Implement Test_Http_Options and register the test for execution
Implement Test_Http_Options and register the test for execution
Ada
apache-2.0
stcarrez/ada-util,stcarrez/ada-util
8ad4aae98aa025f202af421531232ad688b8241d
src/security-permissions.ads
src/security-permissions.ads
----------------------------------------------------------------------- -- security-permissions -- Definition of permissions -- Copyright (C) 2010, 2011, 2012 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- -- The <b>Security.Permissions</b> package defines the different permissions that can be -- checked by the access control manager. package Security.Permissions is Invalid_Name : exception; type Permission_Index is new Natural; -- Get the permission index associated with the name. function Get_Permission_Index (Name : in String) return Permission_Index; -- Get the last permission index registered in the global permission map. function Get_Last_Permission_Index return Permission_Index; -- Add the permission name and allocate a unique permission index. procedure Add_Permission (Name : in String; Index : out Permission_Index); -- The permission root class. type Permission (Id : Permission_Index) is tagged limited null record; -- Each permission is represented by a <b>Permission_Type</b> number to provide a fast -- and efficient permission check. type Permission_Type is new Natural range 0 .. 63; -- The <b>Permission_Map</b> represents a set of permissions which are granted to a user. -- Each permission is represented by a boolean in the map. The implementation is limited -- to 64 permissions. type Permission_Map is array (Permission_Type'Range) of Boolean; pragma Pack (Permission_Map); generic Name : String; package Permission_ACL is function Permission return Permission_Index; pragma Inline_Always (Permission); end Permission_ACL; end Security.Permissions;
----------------------------------------------------------------------- -- security-permissions -- Definition of permissions -- Copyright (C) 2010, 2011, 2012 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- -- The <b>Security.Permissions</b> package defines the different permissions that can be -- checked by the access control manager. package Security.Permissions is Invalid_Name : exception; type Permission_Index is new Natural; -- Get the permission index associated with the name. function Get_Permission_Index (Name : in String) return Permission_Index; -- Get the last permission index registered in the global permission map. function Get_Last_Permission_Index return Permission_Index; -- Add the permission name and allocate a unique permission index. procedure Add_Permission (Name : in String; Index : out Permission_Index); -- The permission root class. -- Each permission is represented by a <b>Permission_Index</b> number to provide a fast -- and efficient permission check. type Permission (Id : Permission_Index) is tagged limited null record; generic Name : String; package Permission_ACL is function Permission return Permission_Index; pragma Inline_Always (Permission); end Permission_ACL; end Security.Permissions;
Remove Permission_Type and Permission_Map
Remove Permission_Type and Permission_Map
Ada
apache-2.0
stcarrez/ada-security
4d85afe37f93da6933999e2857dbc06e9a414683
src/util-properties-json.adb
src/util-properties-json.adb
----------------------------------------------------------------------- -- util-properties-json -- read json files into properties -- Copyright (C) 2013 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Serialize.IO.JSON; with Util.Stacks; with Util.Beans.Objects; package body Util.Properties.JSON is type Natural_Access is access all Natural; package Length_Stack is new Util.Stacks (Element_Type => Natural, Element_Type_Access => Natural_Access); type Parser is new Util.Serialize.IO.JSON.Parser with record Base_Name : Ada.Strings.Unbounded.Unbounded_String; Lengths : Length_Stack.Stack; Separator : Ada.Strings.Unbounded.Unbounded_String; Separator_Length : Natural; end record; -- Start a new object associated with the given name. This is called when -- the '{' is reached. The reader must be updated so that the next -- <b>Set_Member</b> procedure will associate the name/value pair on the -- new object. overriding procedure Start_Object (Handler : in out Parser; Name : in String); -- Finish an object associated with the given name. The reader must be -- updated to be associated with the previous object. overriding procedure Finish_Object (Handler : in out Parser; Name : in String); -- ----------------------- -- Start a new object associated with the given name. This is called when -- the '{' is reached. The reader must be updated so that the next -- <b>Set_Member</b> procedure will associate the name/value pair on the -- new object. -- ----------------------- overriding procedure Start_Object (Handler : in out Parser; Name : in String) is begin if Name'Length > 0 then Ada.Strings.Unbounded.Append (Handler.Base_Name, Name); Ada.Strings.Unbounded.Append (Handler.Base_Name, Handler.Separator); Length_Stack.Push (Handler.Lengths); Length_Stack.Current (Handler.Lengths).all := Name'Length + Handler.Separator_Length; end if; end Start_Object; -- ----------------------- -- Finish an object associated with the given name. The reader must be -- updated to be associated with the previous object. -- ----------------------- overriding procedure Finish_Object (Handler : in out Parser; Name : in String) is Len : constant Natural := Ada.Strings.Unbounded.Length (Handler.Base_Name); begin if Name'Length > 0 then Ada.Strings.Unbounded.Delete (Handler.Base_Name, Len - Name'Length - Handler.Separator_Length + 1, Len); end if; end Finish_Object; -- ----------------------- -- Parse the JSON content and put the flattened content in the property manager. -- ----------------------- procedure Parse_JSON (Manager : in out Util.Properties.Manager'Class; Content : in String; Flatten_Separator : in String := ".") is type Local_Parser is new Parser with null record; -- Set the name/value pair on the current object. For each active mapping, -- find whether a rule matches our name and execute it. overriding procedure Set_Member (Handler : in out Local_Parser; Name : in String; Value : in Util.Beans.Objects.Object; Attribute : in Boolean := False); -- ----------------------- -- Set the name/value pair on the current object. For each active mapping, -- find whether a rule matches our name and execute it. -- ----------------------- overriding procedure Set_Member (Handler : in out Local_Parser; Name : in String; Value : in Util.Beans.Objects.Object; Attribute : in Boolean := False) is pragma Unreferenced (Attribute); begin Manager.Set (Ada.Strings.Unbounded.To_String (Handler.Base_Name) & Name, Util.Beans.Objects.To_String (Value)); end Set_Member; P : Local_Parser; begin P.Separator := Ada.Strings.Unbounded.To_Unbounded_String (Flatten_Separator); P.Separator_Length := Flatten_Separator'Length; P.Parse_String (Content); end Parse_JSON; -- ----------------------- -- Read the JSON file into the property manager. -- The JSON content is flatten into Flatten the JSON content and add the properties. -- ----------------------- procedure Read_JSON (Manager : in out Util.Properties.Manager'Class; Path : in String; Flatten_Separator : in String := ".") is type Local_Parser is new Parser with null record; -- Set the name/value pair on the current object. For each active mapping, -- find whether a rule matches our name and execute it. overriding procedure Set_Member (Handler : in out Local_Parser; Name : in String; Value : in Util.Beans.Objects.Object; Attribute : in Boolean := False); -- ----------------------- -- Set the name/value pair on the current object. For each active mapping, -- find whether a rule matches our name and execute it. -- ----------------------- overriding procedure Set_Member (Handler : in out Local_Parser; Name : in String; Value : in Util.Beans.Objects.Object; Attribute : in Boolean := False) is pragma Unreferenced (Attribute); begin Manager.Set (Ada.Strings.Unbounded.To_String (Handler.Base_Name) & Name, Util.Beans.Objects.To_String (Value)); end Set_Member; P : Local_Parser; begin P.Separator := Ada.Strings.Unbounded.To_Unbounded_String (Flatten_Separator); P.Separator_Length := Flatten_Separator'Length; P.Parse (Path); end Read_JSON; end Util.Properties.JSON;
----------------------------------------------------------------------- -- util-properties-json -- read json files into properties -- Copyright (C) 2013 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Serialize.IO.JSON; with Util.Stacks; with Util.Beans.Objects; package body Util.Properties.JSON is type Natural_Access is access all Natural; package Length_Stack is new Util.Stacks (Element_Type => Natural, Element_Type_Access => Natural_Access); type Parser is new Util.Serialize.IO.JSON.Parser with record Base_Name : Ada.Strings.Unbounded.Unbounded_String; Lengths : Length_Stack.Stack; Separator : Ada.Strings.Unbounded.Unbounded_String; Separator_Length : Natural; end record; -- Start a new object associated with the given name. This is called when -- the '{' is reached. The reader must be updated so that the next -- <b>Set_Member</b> procedure will associate the name/value pair on the -- new object. overriding procedure Start_Object (Handler : in out Parser; Name : in String); -- Finish an object associated with the given name. The reader must be -- updated to be associated with the previous object. overriding procedure Finish_Object (Handler : in out Parser; Name : in String); -- ----------------------- -- Start a new object associated with the given name. This is called when -- the '{' is reached. The reader must be updated so that the next -- <b>Set_Member</b> procedure will associate the name/value pair on the -- new object. -- ----------------------- overriding procedure Start_Object (Handler : in out Parser; Name : in String) is begin if Name'Length > 0 then Ada.Strings.Unbounded.Append (Handler.Base_Name, Name); Ada.Strings.Unbounded.Append (Handler.Base_Name, Handler.Separator); Length_Stack.Push (Handler.Lengths); Length_Stack.Current (Handler.Lengths).all := Name'Length + Handler.Separator_Length; end if; end Start_Object; -- ----------------------- -- Finish an object associated with the given name. The reader must be -- updated to be associated with the previous object. -- ----------------------- overriding procedure Finish_Object (Handler : in out Parser; Name : in String) is Len : constant Natural := Ada.Strings.Unbounded.Length (Handler.Base_Name); begin if Name'Length > 0 then Ada.Strings.Unbounded.Delete (Handler.Base_Name, Len - Name'Length - Handler.Separator_Length + 1, Len); end if; end Finish_Object; -- ----------------------- -- Parse the JSON content and put the flattened content in the property manager. -- ----------------------- procedure Parse_JSON (Manager : in out Util.Properties.Manager'Class; Content : in String; Flatten_Separator : in String := ".") is type Local_Parser is new Parser with null record; -- Set the name/value pair on the current object. For each active mapping, -- find whether a rule matches our name and execute it. overriding procedure Set_Member (Handler : in out Local_Parser; Name : in String; Value : in Util.Beans.Objects.Object; Attribute : in Boolean := False); -- ----------------------- -- Set the name/value pair on the current object. For each active mapping, -- find whether a rule matches our name and execute it. -- ----------------------- overriding procedure Set_Member (Handler : in out Local_Parser; Name : in String; Value : in Util.Beans.Objects.Object; Attribute : in Boolean := False) is pragma Unreferenced (Attribute); begin Manager.Set (Ada.Strings.Unbounded.To_String (Handler.Base_Name) & Name, Util.Beans.Objects.To_String (Value)); end Set_Member; P : Local_Parser; begin P.Separator := Ada.Strings.Unbounded.To_Unbounded_String (Flatten_Separator); P.Separator_Length := Flatten_Separator'Length; P.Parse_String (Content); if P.Has_Error then raise Util.Serialize.IO.Parse_Error; end if; end Parse_JSON; -- ----------------------- -- Read the JSON file into the property manager. -- The JSON content is flatten into Flatten the JSON content and add the properties. -- ----------------------- procedure Read_JSON (Manager : in out Util.Properties.Manager'Class; Path : in String; Flatten_Separator : in String := ".") is type Local_Parser is new Parser with null record; -- Set the name/value pair on the current object. For each active mapping, -- find whether a rule matches our name and execute it. overriding procedure Set_Member (Handler : in out Local_Parser; Name : in String; Value : in Util.Beans.Objects.Object; Attribute : in Boolean := False); -- ----------------------- -- Set the name/value pair on the current object. For each active mapping, -- find whether a rule matches our name and execute it. -- ----------------------- overriding procedure Set_Member (Handler : in out Local_Parser; Name : in String; Value : in Util.Beans.Objects.Object; Attribute : in Boolean := False) is pragma Unreferenced (Attribute); begin Manager.Set (Ada.Strings.Unbounded.To_String (Handler.Base_Name) & Name, Util.Beans.Objects.To_String (Value)); end Set_Member; P : Local_Parser; begin P.Separator := Ada.Strings.Unbounded.To_Unbounded_String (Flatten_Separator); P.Separator_Length := Flatten_Separator'Length; P.Parse (Path); if P.Has_Error then raise Util.Serialize.IO.Parse_Error; end if; end Read_JSON; end Util.Properties.JSON;
Raise a Parse_Error exception if there is an error while parsing the JSON content
Raise a Parse_Error exception if there is an error while parsing the JSON content
Ada
apache-2.0
Letractively/ada-util,Letractively/ada-util,flottokarotto/ada-util,flottokarotto/ada-util
092e6ae6630832ce19ecf817f085b99f056163d0
awa/plugins/awa-workspaces/src/awa-workspaces-modules.adb
awa/plugins/awa-workspaces/src/awa-workspaces-modules.adb
----------------------------------------------------------------------- -- awa-workspaces-module -- Module workspaces -- Copyright (C) 2011, 2012, 2013 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Calendar; with AWA.Users.Models; with AWA.Modules.Beans; with AWA.Permissions.Services; with ADO.SQL; with Util.Log.Loggers; with AWA.Users.Modules; with AWA.Workspaces.Beans; package body AWA.Workspaces.Modules is package ASC renames AWA.Services.Contexts; Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("Awa.Workspaces.Module"); package Register is new AWA.Modules.Beans (Module => Workspace_Module, Module_Access => Workspace_Module_Access); -- ------------------------------ -- Initialize the workspaces module. -- ------------------------------ overriding procedure Initialize (Plugin : in out Workspace_Module; App : in AWA.Modules.Application_Access; Props : in ASF.Applications.Config) is begin Log.Info ("Initializing the workspaces module"); -- Register here any bean class, servlet, filter. Register.Register (Plugin => Plugin, Name => "AWA.Workspaces.Beans.Workspaces_Bean", Handler => AWA.Workspaces.Beans.Create_Workspaces_Bean'Access); AWA.Modules.Module (Plugin).Initialize (App, Props); Plugin.User_Manager := AWA.Users.Modules.Get_User_Manager; -- Add here the creation of manager instances. end Initialize; -- ------------------------------ -- Get the current workspace associated with the current user. -- If the user has not workspace, create one. -- ------------------------------ procedure Get_Workspace (Session : in out ADO.Sessions.Master_Session; Context : in AWA.Services.Contexts.Service_Context_Access; Workspace : out AWA.Workspaces.Models.Workspace_Ref) is User : constant AWA.Users.Models.User_Ref := Context.Get_User; WS : AWA.Workspaces.Models.Workspace_Ref; Query : ADO.SQL.Query; Found : Boolean; begin if User.Is_Null then Log.Error ("There is no current user. The workspace cannot be identified"); Workspace := AWA.Workspaces.Models.Null_Workspace; return; end if; -- Find the workspace associated with the current user. Query.Add_Param (User.Get_Id); Query.Set_Filter ("o.owner_id = ?"); WS.Find (Session, Query, Found); if Found then Workspace := WS; return; end if; -- Create a workspace for this user. WS.Set_Owner (User); WS.Set_Create_Date (Ada.Calendar.Clock); WS.Save (Session); -- And give full control of the workspace for this user AWA.Permissions.Services.Add_Permission (Session => Session, User => User.Get_Id, Entity => WS); Workspace := WS; end Get_Workspace; -- ------------------------------ -- Send the invitation to the user. -- ------------------------------ procedure Send_Invitation (Module : in Workspace_Module; Invitation : in out AWA.Workspaces.Models.Invitation_Ref'Class) is Ctx : constant ASC.Service_Context_Access := AWA.Services.Contexts.Current; DB : ADO.Sessions.Master_Session := AWA.Services.Contexts.Get_Master_Session (Ctx); User : constant AWA.Users.Models.User_Ref := Ctx.Get_User; WS : AWA.Workspaces.Models.Workspace_Ref; Query : ADO.SQL.Query; Found : Boolean; Key : AWA.Users.Models.Access_Key_Ref; begin Log.Info ("Sending invitation to {0}", String '(Invitation.Get_Email)); Ctx.Start; if User.Is_Null then Log.Error ("There is no current user. The workspace cannot be identified"); return; end if; -- Find the workspace associated with the current user. Query.Add_Param (User.Get_Id); Query.Set_Filter ("o.owner_id = ?"); WS.Find (DB, Query, Found); if not Found then return; end if; Key := AWA.Users.Models.Access_Key_Ref (Invitation.Get_Access_Key); -- Key.Set_Key_Value Key.Save (DB); Invitation.Set_Inviter (User); Invitation.Set_Workspace (WS); Invitation.Set_Create_Date (Ada.Calendar.Clock); Invitation.Save (DB); Ctx.Commit; end Send_Invitation; end AWA.Workspaces.Modules;
----------------------------------------------------------------------- -- awa-workspaces-module -- Module workspaces -- Copyright (C) 2011, 2012, 2013 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Calendar; with AWA.Users.Models; with AWA.Modules.Beans; with AWA.Permissions.Services; with ADO.SQL; with Util.Log.Loggers; with AWA.Users.Modules; with AWA.Workspaces.Beans; package body AWA.Workspaces.Modules is package ASC renames AWA.Services.Contexts; Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("Awa.Workspaces.Module"); package Register is new AWA.Modules.Beans (Module => Workspace_Module, Module_Access => Workspace_Module_Access); -- ------------------------------ -- Initialize the workspaces module. -- ------------------------------ overriding procedure Initialize (Plugin : in out Workspace_Module; App : in AWA.Modules.Application_Access; Props : in ASF.Applications.Config) is begin Log.Info ("Initializing the workspaces module"); -- Register here any bean class, servlet, filter. Register.Register (Plugin => Plugin, Name => "AWA.Workspaces.Beans.Workspaces_Bean", Handler => AWA.Workspaces.Beans.Create_Workspaces_Bean'Access); AWA.Modules.Module (Plugin).Initialize (App, Props); Plugin.User_Manager := AWA.Users.Modules.Get_User_Manager; -- Add here the creation of manager instances. end Initialize; -- ------------------------------ -- Get the current workspace associated with the current user. -- If the user has not workspace, create one. -- ------------------------------ procedure Get_Workspace (Session : in out ADO.Sessions.Master_Session; Context : in AWA.Services.Contexts.Service_Context_Access; Workspace : out AWA.Workspaces.Models.Workspace_Ref) is User : constant AWA.Users.Models.User_Ref := Context.Get_User; WS : AWA.Workspaces.Models.Workspace_Ref; Query : ADO.SQL.Query; Found : Boolean; begin if User.Is_Null then Log.Error ("There is no current user. The workspace cannot be identified"); Workspace := AWA.Workspaces.Models.Null_Workspace; return; end if; -- Find the workspace associated with the current user. Query.Add_Param (User.Get_Id); Query.Set_Filter ("o.owner_id = ?"); WS.Find (Session, Query, Found); if Found then Workspace := WS; return; end if; -- Create a workspace for this user. WS.Set_Owner (User); WS.Set_Create_Date (Ada.Calendar.Clock); WS.Save (Session); -- And give full control of the workspace for this user AWA.Permissions.Services.Add_Permission (Session => Session, User => User.Get_Id, Entity => WS); Workspace := WS; end Get_Workspace; -- ------------------------------ -- Send the invitation to the user. -- ------------------------------ procedure Send_Invitation (Module : in Workspace_Module; Invitation : in out AWA.Workspaces.Models.Invitation_Ref'Class) is Ctx : constant ASC.Service_Context_Access := AWA.Services.Contexts.Current; DB : ADO.Sessions.Master_Session := AWA.Services.Contexts.Get_Master_Session (Ctx); User : constant AWA.Users.Models.User_Ref := Ctx.Get_User; WS : AWA.Workspaces.Models.Workspace_Ref; Query : ADO.SQL.Query; Found : Boolean; Key : AWA.Users.Models.Access_Key_Ref; begin Log.Info ("Sending invitation to {0}", String '(Invitation.Get_Email)); Ctx.Start; if User.Is_Null then Log.Error ("There is no current user. The workspace cannot be identified"); return; end if; -- Find the workspace associated with the current user. Query.Add_Param (User.Get_Id); Query.Set_Filter ("o.owner_id = ?"); WS.Find (DB, Query, Found); if not Found then return; end if; Key := AWA.Users.Models.Access_Key_Ref (Invitation.Get_Access_Key); Module.User_Manager.Create_Access_Key (User, Key, 365 * 86400.0, DB); Key.Save (DB); Invitation.Set_Inviter (User); Invitation.Set_Workspace (WS); Invitation.Set_Create_Date (Ada.Calendar.Clock); Invitation.Save (DB); Ctx.Commit; end Send_Invitation; end AWA.Workspaces.Modules;
Create the invitation access key
Create the invitation access key
Ada
apache-2.0
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
8e929f76e0e21e950d32c54921cd98365a626675
awa/plugins/awa-workspaces/src/awa-workspaces-modules.ads
awa/plugins/awa-workspaces/src/awa-workspaces-modules.ads
----------------------------------------------------------------------- -- awa-workspaces-module -- Module workspaces -- Copyright (C) 2011, 2012, 2017 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with ADO.Sessions; with ASF.Applications; with AWA.Modules; with AWA.Services.Contexts; with AWA.Workspaces.Models; with AWA.Users.Services; with AWA.Users.Models; with AWA.Events; -- == Events == -- The *workspaces* module provides several events that are posted when some action are performed. -- -- === invite-user === -- This event is posted when an invitation is created for a user. The event can be used to -- send the associated invitation email to the invitee. The event contains the following -- attributes: -- -- key -- email -- name -- message -- inviter -- -- === accept-invitation === -- This event is posted when an invitation is accepted by a user. package AWA.Workspaces.Modules is Not_Found : exception; -- The name under which the module is registered. NAME : constant String := "workspaces"; package Invite_User_Event is new AWA.Events.Definition (Name => "invite-user"); package Accept_Invitation_Event is new AWA.Events.Definition (Name => "accept-invitation"); -- ------------------------------ -- Module workspaces -- ------------------------------ type Workspace_Module is new AWA.Modules.Module with private; type Workspace_Module_Access is access all Workspace_Module'Class; -- Initialize the workspaces module. overriding procedure Initialize (Plugin : in out Workspace_Module; App : in AWA.Modules.Application_Access; Props : in ASF.Applications.Config); -- Get the current workspace associated with the current user. -- If the user has not workspace, create one. procedure Get_Workspace (Session : in out ADO.Sessions.Master_Session; Context : in AWA.Services.Contexts.Service_Context_Access; Workspace : out AWA.Workspaces.Models.Workspace_Ref); -- Load the invitation from the access key and verify that the key is still valid. procedure Load_Invitation (Module : in Workspace_Module; Key : in String; Invitation : in out AWA.Workspaces.Models.Invitation_Ref'Class; Inviter : in out AWA.Users.Models.User_Ref); -- Accept the invitation identified by the access key. procedure Accept_Invitation (Module : in Workspace_Module; Key : in String); -- Send the invitation to the user. procedure Send_Invitation (Module : in Workspace_Module; Invitation : in out AWA.Workspaces.Models.Invitation_Ref'Class); -- Delete the member from the workspace. Remove the invitation if there is one. procedure Delete_Member (Module : in Workspace_Module; Member_Id : in ADO.Identifier); private type Workspace_Module is new AWA.Modules.Module with record User_Manager : AWA.Users.Services.User_Service_Access; end record; end AWA.Workspaces.Modules;
----------------------------------------------------------------------- -- awa-workspaces-module -- Module workspaces -- Copyright (C) 2011, 2012, 2017 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with ADO.Objects; with ADO.Sessions; with Security.Permissions; with ASF.Applications; with AWA.Modules; with AWA.Services.Contexts; with AWA.Workspaces.Models; with AWA.Users.Services; with AWA.Users.Models; with AWA.Events; private with Ada.Strings.Unbounded; -- == Events == -- The *workspaces* module provides several events that are posted when some action are performed. -- -- === invite-user === -- This event is posted when an invitation is created for a user. The event can be used to -- send the associated invitation email to the invitee. The event contains the following -- attributes: -- -- key -- email -- name -- message -- inviter -- -- === accept-invitation === -- This event is posted when an invitation is accepted by a user. package AWA.Workspaces.Modules is subtype Permission_Index_Array is Security.Permissions.Permission_Index_Array; Not_Found : exception; -- The name under which the module is registered. NAME : constant String := "workspaces"; -- The configuration parameter that defines the list of permissions to grant -- to a user when his workspace is created. PARAM_PERMISSIONS_LIST : constant String := "permissions_list"; package Invite_User_Event is new AWA.Events.Definition (Name => "invite-user"); package Accept_Invitation_Event is new AWA.Events.Definition (Name => "accept-invitation"); -- ------------------------------ -- Module workspaces -- ------------------------------ type Workspace_Module is new AWA.Modules.Module with private; type Workspace_Module_Access is access all Workspace_Module'Class; -- Initialize the workspaces module. overriding procedure Initialize (Plugin : in out Workspace_Module; App : in AWA.Modules.Application_Access; Props : in ASF.Applications.Config); -- Configures the module after its initialization and after having read its XML configuration. overriding procedure Configure (Plugin : in out Workspace_Module; Props : in ASF.Applications.Config); -- Get the list of permissions for the workspace owner. function Get_Owner_Permissions (Manager : in Workspace_Module) return Permission_Index_Array; -- Get the workspace module. function Get_Workspace_Module return Workspace_Module_Access; -- Get the current workspace associated with the current user. -- If the user has not workspace, create one. procedure Get_Workspace (Session : in out ADO.Sessions.Master_Session; Context : in AWA.Services.Contexts.Service_Context_Access; Workspace : out AWA.Workspaces.Models.Workspace_Ref); -- Load the invitation from the access key and verify that the key is still valid. procedure Load_Invitation (Module : in Workspace_Module; Key : in String; Invitation : in out AWA.Workspaces.Models.Invitation_Ref'Class; Inviter : in out AWA.Users.Models.User_Ref); -- Accept the invitation identified by the access key. procedure Accept_Invitation (Module : in Workspace_Module; Key : in String); -- Send the invitation to the user. procedure Send_Invitation (Module : in Workspace_Module; Invitation : in out AWA.Workspaces.Models.Invitation_Ref'Class); -- Delete the member from the workspace. Remove the invitation if there is one. procedure Delete_Member (Module : in Workspace_Module; Member_Id : in ADO.Identifier); -- Add a list of permissions for all the users of the workspace that have the appropriate -- role. Workspace members will be able to access the given database entity for the -- specified list of permissions. procedure Add_Permission (Session : in out ADO.Sessions.Master_Session; User : in ADO.Identifier; Entity : in ADO.Objects.Object_Ref'Class; Workspace : in ADO.Identifier; List : in Security.Permissions.Permission_Index_Array); private type Workspace_Module is new AWA.Modules.Module with record User_Manager : AWA.Users.Services.User_Service_Access; -- The list of permissions to grant to a user who creates the workspace. Owner_Permissions : Ada.Strings.Unbounded.Unbounded_String; end record; end AWA.Workspaces.Modules;
Refactor the permission - Declare the PARAM_PERMISSIONS_LIST constant - Override the Configure procedure - Declare the Get_Owner_Permissions function - Declare Get_WorkspaceModule - Declare Add_Permission procedure
Refactor the permission - Declare the PARAM_PERMISSIONS_LIST constant - Override the Configure procedure - Declare the Get_Owner_Permissions function - Declare Get_WorkspaceModule - Declare Add_Permission procedure
Ada
apache-2.0
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
3d718279a7c74d9417854a8212684f81b2d254bb
src/asf-components-widgets-likes.adb
src/asf-components-widgets-likes.adb
----------------------------------------------------------------------- -- components-widgets-likes -- Social Likes Components -- Copyright (C) 2013, 2014, 2015 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Locales; with Util.Beans.Objects; with Util.Strings.Tokenizers; -- GNAT bug, the with clause is necessary to call Get_Global on the application. pragma Warnings (Off, "*is not referenced"); with ASF.Applications.Main; pragma Warnings (On, "*is not referenced"); with ASF.Requests; with ASF.Contexts.Writer; package body ASF.Components.Widgets.Likes is FB_LAYOUT_ATTR : aliased constant String := "data-layout"; FB_SHOW_FACES_ATTR : aliased constant String := "data-show-faces"; FB_WIDTH_ATTR : aliased constant String := "data-width"; FB_ACTION_ATTR : aliased constant String := "data-action"; FB_FONT_ATTR : aliased constant String := "data-font"; FB_COlORSCHEME_ATTR : aliased constant String := "data-colorscheme"; FB_REF_ATTR : aliased constant String := "data-ref"; FB_KIDS_ATTR : aliased constant String := "data-kid_directed_site"; FB_SEND_ATTR : aliased constant String := "data-send"; TW_VIA_ATTR : aliased constant String := "data-via"; TW_COUNT_ATTR : aliased constant String := "data-count"; TW_SIZE_ATTR : aliased constant String := "data-size"; TW_COUNTURL_ATTR : aliased constant String := "data-counturl"; TW_TEXT_ATTR : aliased constant String := "data-text"; TW_RELATED_ATTR : aliased constant String := "data-related"; TW_LANG_ATTR : aliased constant String := "data-lang"; TW_HASHTAGS_ATTR : aliased constant String := "data-hashtags"; G_ANNOTATION_ATTR : aliased constant String := "data-annotation"; G_WIDTH_ATTR : aliased constant String := "data-width"; FACEBOOK_ATTRIBUTE_NAMES : Util.Strings.String_Set.Set; FACEBOOK_SCRIPT_ATTRIBUTE : constant String := "asf.widgets.facebook.script"; GOOGLE_ATTRIBUTE_NAMES : Util.Strings.String_Set.Set; GOOGLE_SCRIPT_ATTRIBUTE : constant String := "asf.widgets.google.script"; TWITTER_ATTRIBUTE_NAMES : Util.Strings.String_Set.Set; TWITTER_SCRIPT_ATTRIBUTE : constant String := "asf.widgets.twitter.script"; type Like_Generator_Binding is record Name : Util.Strings.Name_Access; Generator : Like_Generator_Access; end record; type Like_Generator_Array is array (1 .. MAX_LIKE_GENERATOR) of Like_Generator_Binding; FB_NAME : aliased constant String := "facebook"; FB_GENERATOR : aliased Facebook_Like_Generator; G_NAME : aliased constant String := "google+"; G_GENERATOR : aliased Google_Like_Generator; TWITTER_NAME : aliased constant String := "twitter"; TWITTER_GENERATOR : aliased Twitter_Like_Generator; Generators : Like_Generator_Array := (1 => (FB_NAME'Access, FB_GENERATOR'Access), 2 => (G_NAME'Access, G_GENERATOR'Access), 3 => (TWITTER_NAME'Access, TWITTER_GENERATOR'Access), others => (null, null)); -- ------------------------------ -- Render the facebook like button according to the component attributes. -- ------------------------------ overriding procedure Render_Like (Generator : in Facebook_Like_Generator; UI : in UILike'Class; Href : in String; Context : in out ASF.Contexts.Faces.Faces_Context'Class) is pragma Unreferenced (Generator); Writer : constant Contexts.Writer.Response_Writer_Access := Context.Get_Response_Writer; Request : constant ASF.Requests.Request_Access := Context.Get_Request; begin if not Context.Is_Ajax_Request and then Util.Beans.Objects.Is_Null (Request.Get_Attribute (FACEBOOK_SCRIPT_ATTRIBUTE)) then Request.Set_Attribute (FACEBOOK_SCRIPT_ATTRIBUTE, Util.Beans.Objects.To_Object (True)); Writer.Queue_Script ("(function(d, s, id) { var js, fjs = d.getElementsByTagName(s)[0];" & "if (d.getElementById(id)) return;" & "js = d.createElement(s); js.id = id;js.async=true;" & "js.src = ""//connect.facebook.net/"); Writer.Queue_Script (Util.Locales.To_String (Context.Get_Locale)); Writer.Queue_Script ("/all.js#xfbml=1&;appId="); declare App_Id : constant String := Context.Get_Application.Get_Config (P_Facebook_App_Id.P); begin if App_Id'Length = 0 then UI.Log_Error ("The facebook client application id is empty"); UI.Log_Error ("Please, configure the '{0}' property " & "in the application", P_Facebook_App_Id.PARAM_NAME); else Writer.Queue_Script (App_Id); end if; end; Writer.Queue_Script (""";fjs.parentNode.insertBefore(js, fjs);" & "}(document, 'script', 'facebook-jssdk'));"); Writer.Start_Element ("div"); Writer.Write_Attribute ("id", "fb-root"); Writer.End_Element ("div"); end if; Writer.Start_Element ("div"); Writer.Write_Attribute ("class", "fb-like"); Writer.Write_Attribute ("data-href", Href); UI.Render_Attributes (Context, FACEBOOK_ATTRIBUTE_NAMES, Writer); Writer.End_Element ("div"); end Render_Like; -- ------------------------------ -- Google like generator -- ------------------------------ overriding procedure Render_Like (Generator : in Google_Like_Generator; UI : in UILike'Class; Href : in String; Context : in out ASF.Contexts.Faces.Faces_Context'Class) is pragma Unreferenced (Generator); Writer : constant Contexts.Writer.Response_Writer_Access := Context.Get_Response_Writer; Request : constant ASF.Requests.Request_Access := Context.Get_Request; begin if not Context.Is_Ajax_Request and then Util.Beans.Objects.Is_Null (Request.Get_Attribute (GOOGLE_SCRIPT_ATTRIBUTE)) then Request.Set_Attribute (GOOGLE_SCRIPT_ATTRIBUTE, Util.Beans.Objects.To_Object (True)); Writer.Queue_Include_Script ("https://apis.google.com/js/plusone.js"); end if; Writer.Start_Element ("div"); Writer.Write_Attribute ("class", "g-plusone"); Writer.Write_Attribute ("data-href", Href); UI.Render_Attributes (Context, GOOGLE_ATTRIBUTE_NAMES, Writer); Writer.End_Element ("div"); end Render_Like; -- ------------------------------ -- Tweeter like generator -- ------------------------------ overriding procedure Render_Like (Generator : in Twitter_Like_Generator; UI : in UILike'Class; Href : in String; Context : in out ASF.Contexts.Faces.Faces_Context'Class) is pragma Unreferenced (Generator); Writer : constant Contexts.Writer.Response_Writer_Access := Context.Get_Response_Writer; Request : constant ASF.Requests.Request_Access := Context.Get_Request; Lang : constant String := Util.Locales.Get_ISO3_Language (Context.Get_Locale); begin if not Context.Is_Ajax_Request and then Util.Beans.Objects.Is_Null (Request.Get_Attribute (TWITTER_SCRIPT_ATTRIBUTE)) then Request.Set_Attribute (TWITTER_SCRIPT_ATTRIBUTE, Util.Beans.Objects.To_Object (True)); Writer.Queue_Script ("!function(d,s,id){var js,fjs=d.getElementsByTagName(s)[0]," & "p=/^http:/.test(d.location)?'http':'https';" & "if(!d.getElementById(id)){js=d.createElement(s);js.id=id;" & "js.src=p+'://platform.twitter.com/widgets.js';" & "fjs.parentNode.insertBefore(js,fjs);}}" & "(document, 'script', 'twitter-wjs');"); end if; Writer.Start_Element ("a"); Writer.Write_Attribute ("href", "https://twitter.com/share"); Writer.Write_Attribute ("class", "twitter-share-button"); Writer.Write_Attribute ("data-url", Href); Writer.Write_Attribute ("data-lang", Lang); UI.Render_Attributes (Context, TWITTER_ATTRIBUTE_NAMES, Writer); Writer.Write_Text ("Tweet"); Writer.End_Element ("a"); end Render_Like; -- ------------------------------ -- Get the link to submit in the like action. -- ------------------------------ function Get_Link (UI : in UILike; Context : in ASF.Contexts.Faces.Faces_Context'Class) return String is Href : constant String := UI.Get_Attribute ("href", Context, ""); begin if Href'Length > 0 then return Href; else return Context.Get_Request.Get_Request_URI; end if; end Get_Link; -- ------------------------------ -- Render an image with the source link created from an email address to the Gravatars service. -- ------------------------------ overriding procedure Encode_Begin (UI : in UILike; Context : in out ASF.Contexts.Faces.Faces_Context'Class) is begin if UI.Is_Rendered (Context) then declare Writer : constant Contexts.Writer.Response_Writer_Access := Context.Get_Response_Writer; Kind : constant String := UI.Get_Attribute ("type", Context, ""); Href : constant String := UILike'Class (UI).Get_Link (Context); Style : constant String := UI.Get_Attribute ("style", Context, ""); Class : constant String := UI.Get_Attribute ("styleClass", Context, ""); procedure Render (Name : in String; Done : out Boolean); procedure Render (Name : in String; Done : out Boolean) is use type Util.Strings.Name_Access; begin Done := False; for I in Generators'Range loop exit when Generators (I).Name = null; if Generators (I).Name.all = Name then Writer.Start_Element ("div"); if Style'Length > 0 then Writer.Write_Attribute ("style", Style); end if; if Class'Length > 0 then Writer.Write_Attribute ("class", Class); end if; Generators (I).Generator.Render_Like (UI, Href, Context); Writer.End_Element ("div"); return; end if; end loop; UI.Log_Error ("Like type {0} is not recognized", Name); end Render; begin if Kind'Length = 0 then UI.Log_Error ("The like type is empty."); else Util.Strings.Tokenizers.Iterate_Tokens (Content => Kind, Pattern => ",", Process => Render'Access); end if; end; end if; end Encode_Begin; -- ------------------------------ -- Register the like generator under the given name. -- ------------------------------ procedure Register_Like (Name : in Util.Strings.Name_Access; Generator : in Like_Generator_Access) is use type Util.Strings.Name_Access; begin for I in Generators'Range loop if Generators (I).Name = null then Generators (I).Name := Name; Generators (I).Generator := Generator; return; end if; end loop; end Register_Like; begin FACEBOOK_ATTRIBUTE_NAMES.Insert (FB_LAYOUT_ATTR'Access); FACEBOOK_ATTRIBUTE_NAMES.Insert (FB_SHOW_FACES_ATTR'Access); FACEBOOK_ATTRIBUTE_NAMES.Insert (FB_WIDTH_ATTR'Access); FACEBOOK_ATTRIBUTE_NAMES.Insert (FB_ACTION_ATTR'Access); FACEBOOK_ATTRIBUTE_NAMES.Insert (FB_FONT_ATTR'Access); FACEBOOK_ATTRIBUTE_NAMES.Insert (FB_COlORSCHEME_ATTR'Access); FACEBOOK_ATTRIBUTE_NAMES.Insert (FB_REF_ATTR'Access); FACEBOOK_ATTRIBUTE_NAMES.Insert (FB_KIDS_ATTR'Access); FACEBOOK_ATTRIBUTE_NAMES.Insert (FB_SEND_ATTR'Access); TWITTER_ATTRIBUTE_NAMES.Insert (TW_SIZE_ATTR'Access); TWITTER_ATTRIBUTE_NAMES.Insert (TW_COUNT_ATTR'Access); TWITTER_ATTRIBUTE_NAMES.Insert (TW_VIA_ATTR'Access); TWITTER_ATTRIBUTE_NAMES.Insert (TW_COUNTURL_ATTR'Access); TWITTER_ATTRIBUTE_NAMES.Insert (TW_TEXT_ATTR'Access); TWITTER_ATTRIBUTE_NAMES.Insert (TW_RELATED_ATTR'Access); TWITTER_ATTRIBUTE_NAMES.Insert (TW_LANG_ATTR'Access); TWITTER_ATTRIBUTE_NAMES.Insert (TW_HASHTAGS_ATTR'Access); GOOGLE_ATTRIBUTE_NAMES.Insert (G_ANNOTATION_ATTR'Access); GOOGLE_ATTRIBUTE_NAMES.Insert (G_WIDTH_ATTR'Access); end ASF.Components.Widgets.Likes;
----------------------------------------------------------------------- -- components-widgets-likes -- Social Likes Components -- Copyright (C) 2013, 2014, 2015, 2019 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Locales; with Util.Beans.Objects; with Util.Strings.Tokenizers; -- GNAT bug, the with clause is necessary to call Get_Global on the application. pragma Warnings (Off, "*is not referenced"); with ASF.Applications.Main; pragma Warnings (On, "*is not referenced"); with ASF.Requests; with ASF.Contexts.Writer; package body ASF.Components.Widgets.Likes is FB_LAYOUT_ATTR : aliased constant String := "data-layout"; FB_SHOW_FACES_ATTR : aliased constant String := "data-show-faces"; FB_WIDTH_ATTR : aliased constant String := "data-width"; FB_ACTION_ATTR : aliased constant String := "data-action"; FB_FONT_ATTR : aliased constant String := "data-font"; FB_COlORSCHEME_ATTR : aliased constant String := "data-colorscheme"; FB_REF_ATTR : aliased constant String := "data-ref"; FB_KIDS_ATTR : aliased constant String := "data-kid_directed_site"; FB_SEND_ATTR : aliased constant String := "data-send"; TW_VIA_ATTR : aliased constant String := "data-via"; TW_COUNT_ATTR : aliased constant String := "data-count"; TW_SIZE_ATTR : aliased constant String := "data-size"; TW_COUNTURL_ATTR : aliased constant String := "data-counturl"; TW_TEXT_ATTR : aliased constant String := "data-text"; TW_RELATED_ATTR : aliased constant String := "data-related"; TW_LANG_ATTR : aliased constant String := "data-lang"; TW_HASHTAGS_ATTR : aliased constant String := "data-hashtags"; FACEBOOK_ATTRIBUTE_NAMES : Util.Strings.String_Set.Set; FACEBOOK_SCRIPT_ATTRIBUTE : constant String := "asf.widgets.facebook.script"; TWITTER_ATTRIBUTE_NAMES : Util.Strings.String_Set.Set; TWITTER_SCRIPT_ATTRIBUTE : constant String := "asf.widgets.twitter.script"; type Like_Generator_Binding is record Name : Util.Strings.Name_Access; Generator : Like_Generator_Access; end record; type Like_Generator_Array is array (1 .. MAX_LIKE_GENERATOR) of Like_Generator_Binding; FB_NAME : aliased constant String := "facebook"; FB_GENERATOR : aliased Facebook_Like_Generator; TWITTER_NAME : aliased constant String := "twitter"; TWITTER_GENERATOR : aliased Twitter_Like_Generator; Generators : Like_Generator_Array := (1 => (FB_NAME'Access, FB_GENERATOR'Access), 2 => (TWITTER_NAME'Access, TWITTER_GENERATOR'Access), others => (null, null)); -- ------------------------------ -- Render the facebook like button according to the component attributes. -- ------------------------------ overriding procedure Render_Like (Generator : in Facebook_Like_Generator; UI : in UILike'Class; Href : in String; Context : in out ASF.Contexts.Faces.Faces_Context'Class) is pragma Unreferenced (Generator); Writer : constant Contexts.Writer.Response_Writer_Access := Context.Get_Response_Writer; Request : constant ASF.Requests.Request_Access := Context.Get_Request; begin if not Context.Is_Ajax_Request and then Util.Beans.Objects.Is_Null (Request.Get_Attribute (FACEBOOK_SCRIPT_ATTRIBUTE)) then Request.Set_Attribute (FACEBOOK_SCRIPT_ATTRIBUTE, Util.Beans.Objects.To_Object (True)); Writer.Queue_Script ("(function(d, s, id) { var js, fjs = d.getElementsByTagName(s)[0];" & "if (d.getElementById(id)) return;" & "js = d.createElement(s); js.id = id;js.async=true;" & "js.src = ""//connect.facebook.net/"); Writer.Queue_Script (Util.Locales.To_String (Context.Get_Locale)); Writer.Queue_Script ("/all.js#xfbml=1&;appId="); declare App_Id : constant String := Context.Get_Application.Get_Config (P_Facebook_App_Id.P); begin if App_Id'Length = 0 then UI.Log_Error ("The facebook client application id is empty"); UI.Log_Error ("Please, configure the '{0}' property " & "in the application", P_Facebook_App_Id.PARAM_NAME); else Writer.Queue_Script (App_Id); end if; end; Writer.Queue_Script (""";fjs.parentNode.insertBefore(js, fjs);" & "}(document, 'script', 'facebook-jssdk'));"); Writer.Start_Element ("div"); Writer.Write_Attribute ("id", "fb-root"); Writer.End_Element ("div"); end if; Writer.Start_Element ("div"); Writer.Write_Attribute ("class", "fb-like"); Writer.Write_Attribute ("data-href", Href); UI.Render_Attributes (Context, FACEBOOK_ATTRIBUTE_NAMES, Writer); Writer.End_Element ("div"); end Render_Like; -- ------------------------------ -- Tweeter like generator -- ------------------------------ overriding procedure Render_Like (Generator : in Twitter_Like_Generator; UI : in UILike'Class; Href : in String; Context : in out ASF.Contexts.Faces.Faces_Context'Class) is pragma Unreferenced (Generator); Writer : constant Contexts.Writer.Response_Writer_Access := Context.Get_Response_Writer; Request : constant ASF.Requests.Request_Access := Context.Get_Request; Lang : constant String := Util.Locales.Get_ISO3_Language (Context.Get_Locale); begin if not Context.Is_Ajax_Request and then Util.Beans.Objects.Is_Null (Request.Get_Attribute (TWITTER_SCRIPT_ATTRIBUTE)) then Request.Set_Attribute (TWITTER_SCRIPT_ATTRIBUTE, Util.Beans.Objects.To_Object (True)); Writer.Queue_Script ("!function(d,s,id){var js,fjs=d.getElementsByTagName(s)[0]," & "p=/^http:/.test(d.location)?'http':'https';" & "if(!d.getElementById(id)){js=d.createElement(s);js.id=id;" & "js.src=p+'://platform.twitter.com/widgets.js';" & "fjs.parentNode.insertBefore(js,fjs);}}" & "(document, 'script', 'twitter-wjs');"); end if; Writer.Start_Element ("a"); Writer.Write_Attribute ("href", "https://twitter.com/share"); Writer.Write_Attribute ("class", "twitter-share-button"); Writer.Write_Attribute ("data-url", Href); Writer.Write_Attribute ("data-lang", Lang); UI.Render_Attributes (Context, TWITTER_ATTRIBUTE_NAMES, Writer); Writer.Write_Text ("Tweet"); Writer.End_Element ("a"); end Render_Like; -- ------------------------------ -- Get the link to submit in the like action. -- ------------------------------ function Get_Link (UI : in UILike; Context : in ASF.Contexts.Faces.Faces_Context'Class) return String is Href : constant String := UI.Get_Attribute ("href", Context, ""); begin if Href'Length > 0 then return Href; else return Context.Get_Request.Get_Request_URI; end if; end Get_Link; -- ------------------------------ -- Render an image with the source link created from an email address to the Gravatars service. -- ------------------------------ overriding procedure Encode_Begin (UI : in UILike; Context : in out ASF.Contexts.Faces.Faces_Context'Class) is begin if UI.Is_Rendered (Context) then declare Writer : constant Contexts.Writer.Response_Writer_Access := Context.Get_Response_Writer; Kind : constant String := UI.Get_Attribute ("type", Context, ""); Href : constant String := UILike'Class (UI).Get_Link (Context); Style : constant String := UI.Get_Attribute ("style", Context, ""); Class : constant String := UI.Get_Attribute ("styleClass", Context, ""); procedure Render (Name : in String; Done : out Boolean); procedure Render (Name : in String; Done : out Boolean) is use type Util.Strings.Name_Access; begin Done := False; for I in Generators'Range loop exit when Generators (I).Name = null; if Generators (I).Name.all = Name then Writer.Start_Element ("div"); if Style'Length > 0 then Writer.Write_Attribute ("style", Style); end if; if Class'Length > 0 then Writer.Write_Attribute ("class", Class); end if; Generators (I).Generator.Render_Like (UI, Href, Context); Writer.End_Element ("div"); return; end if; end loop; UI.Log_Error ("Like type {0} is not recognized", Name); end Render; begin if Kind'Length = 0 then UI.Log_Error ("The like type is empty."); else Util.Strings.Tokenizers.Iterate_Tokens (Content => Kind, Pattern => ",", Process => Render'Access); end if; end; end if; end Encode_Begin; -- ------------------------------ -- Register the like generator under the given name. -- ------------------------------ procedure Register_Like (Name : in Util.Strings.Name_Access; Generator : in Like_Generator_Access) is use type Util.Strings.Name_Access; begin for I in Generators'Range loop if Generators (I).Name = null then Generators (I).Name := Name; Generators (I).Generator := Generator; return; end if; end loop; end Register_Like; begin FACEBOOK_ATTRIBUTE_NAMES.Insert (FB_LAYOUT_ATTR'Access); FACEBOOK_ATTRIBUTE_NAMES.Insert (FB_SHOW_FACES_ATTR'Access); FACEBOOK_ATTRIBUTE_NAMES.Insert (FB_WIDTH_ATTR'Access); FACEBOOK_ATTRIBUTE_NAMES.Insert (FB_ACTION_ATTR'Access); FACEBOOK_ATTRIBUTE_NAMES.Insert (FB_FONT_ATTR'Access); FACEBOOK_ATTRIBUTE_NAMES.Insert (FB_COlORSCHEME_ATTR'Access); FACEBOOK_ATTRIBUTE_NAMES.Insert (FB_REF_ATTR'Access); FACEBOOK_ATTRIBUTE_NAMES.Insert (FB_KIDS_ATTR'Access); FACEBOOK_ATTRIBUTE_NAMES.Insert (FB_SEND_ATTR'Access); TWITTER_ATTRIBUTE_NAMES.Insert (TW_SIZE_ATTR'Access); TWITTER_ATTRIBUTE_NAMES.Insert (TW_COUNT_ATTR'Access); TWITTER_ATTRIBUTE_NAMES.Insert (TW_VIA_ATTR'Access); TWITTER_ATTRIBUTE_NAMES.Insert (TW_COUNTURL_ATTR'Access); TWITTER_ATTRIBUTE_NAMES.Insert (TW_TEXT_ATTR'Access); TWITTER_ATTRIBUTE_NAMES.Insert (TW_RELATED_ATTR'Access); TWITTER_ATTRIBUTE_NAMES.Insert (TW_LANG_ATTR'Access); TWITTER_ATTRIBUTE_NAMES.Insert (TW_HASHTAGS_ATTR'Access); end ASF.Components.Widgets.Likes;
Remove Google+ like because they killed their service
Remove Google+ like because they killed their service
Ada
apache-2.0
stcarrez/ada-asf,stcarrez/ada-asf,stcarrez/ada-asf
893bc8747c801837f9d86e136a6d29c6fce6b903
testutil/ahven/ahven-xml_runner.adb
testutil/ahven/ahven-xml_runner.adb
-- -- Copyright (c) 2007-2009 Tero Koskinen <[email protected]> -- -- Permission to use, copy, modify, and distribute this software for any -- purpose with or without fee is hereby granted, provided that the above -- copyright notice and this permission notice appear in all copies. -- -- THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES -- WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF -- MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR -- ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES -- WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN -- ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF -- OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. -- with Ada.Text_IO; with Ada.Strings; with Ada.Strings.Fixed; with Ada.Strings.Maps; with Ahven.Runner; with Ahven_Compat; with Ahven.AStrings; package body Ahven.XML_Runner is use Ada.Text_IO; use Ada.Strings.Fixed; use Ada.Strings.Maps; use Ahven.Results; use Ahven.Framework; use Ahven.AStrings; function Filter_String (Str : String) return String; function Filter_String (Str : String; Map : Character_Mapping) return String; procedure Print_Test_Pass (File : File_Type; Parent_Test : String; Info : Result_Info); procedure Print_Test_Failure (File : File_Type; Parent_Test : String; Info : Result_Info); procedure Print_Test_Error (File : File_Type; Parent_Test : String; Info : Result_Info); procedure Print_Test_Case (Collection : Result_Collection; Dir : String); procedure Print_Log_File (File : File_Type; Filename : String); procedure Print_Attribute (File : File_Type; Attr : String; Value : String); procedure Start_Testcase_Tag (File : File_Type; Parent : String; Name : String; Execution_Time : String); procedure End_Testcase_Tag (File : File_Type); function Create_Name (Dir : String; Name : String) return String; function Filter_String (Str : String) return String is Result : String (Str'First .. Str'First + 6 * Str'Length); Pos : Natural := Str'First; begin for I in Str'Range loop if Str (I) = ''' then Result (Pos .. Pos + 6 - 1) := "&apos;"; Pos := Pos + 6; elsif Str (I) = '<' then Result (Pos .. Pos + 4 - 1) := "&lt;"; Pos := Pos + 4; elsif Str (I) = '>' then Result (Pos .. Pos + 4 - 1) := "&gt;"; Pos := Pos + 4; elsif Str (I) = '&' then Result (Pos .. Pos + 5 - 1) := "&amp;"; Pos := Pos + 5; elsif Str (I) = '"' then Result (Pos) := '''; Pos := Pos + 1; else Result (Pos) := Str (I); Pos := Pos + 1; end if; end loop; return Result (Result'First .. Pos - 1); end Filter_String; function Filter_String (Str : String; Map : Character_Mapping) return String is begin return Translate (Source => Str, Mapping => Map); end Filter_String; procedure Print_Attribute (File : File_Type; Attr : String; Value : String) is begin Put (File, Attr & "=" & '"' & Value & '"'); end Print_Attribute; procedure Start_Testcase_Tag (File : File_Type; Parent : String; Name : String; Execution_Time : String) is begin Put (File, "<testcase "); Print_Attribute (File, "classname", Filter_String (Parent)); Put (File, " "); Print_Attribute (File, "name", Filter_String (Name)); Put (File, " "); Print_Attribute (File, "time", Filter_String (Execution_Time)); Put_Line (File, ">"); end Start_Testcase_Tag; procedure End_Testcase_Tag (File : File_Type) is begin Put_Line (File, "</testcase>"); end End_Testcase_Tag; function Create_Name (Dir : String; Name : String) return String is function Filename (Test : String) return String is Map : Ada.Strings.Maps.Character_Mapping; begin Map := To_Mapping (From => " '/\<>:|?*()" & '"', To => "-___________" & '_'); return "TEST-" & Filter_String (Test, Map) & ".xml"; end Filename; begin if Dir'Length > 0 then return Dir & Ahven_Compat.Directory_Separator & Filename (Name); else return Filename (Name); end if; end Create_Name; procedure Print_Test_Pass (File : File_Type; Parent_Test : String; Info : Result_Info) is Exec_Time : constant String := Trim (Duration'Image (Get_Execution_Time (Info)), Ada.Strings.Both); begin Start_Testcase_Tag (File => File, Parent => Parent_Test, Name => Get_Routine_Name (Info), Execution_Time => Exec_Time); if Length (Get_Output_File (Info)) > 0 then Put (File, "<system-out>"); Print_Log_File (File, To_String (Get_Output_File (Info))); Put_Line (File, "</system-out>"); end if; End_Testcase_Tag (File); end Print_Test_Pass; procedure Print_Test_Skipped (File : File_Type; Parent_Test : String; Info : Result_Info) is Exec_Time : constant String := Trim (Duration'Image (Get_Execution_Time (Info)), Ada.Strings.Both); begin Start_Testcase_Tag (File => File, Parent => Parent_Test, Name => Get_Routine_Name (Info), Execution_Time => Exec_Time); Put (File, "<skipped "); Print_Attribute (File, "message", Filter_String (Trim (Get_Message (Info), Ada.Strings.Both))); Put (File, ">"); Put_Line (File, Filter_String (Get_Message (Info))); Put_Line (File, "</skipped>"); End_Testcase_Tag (File); end Print_Test_Skipped; procedure Print_Test_Failure (File : File_Type; Parent_Test : String; Info : Result_Info) is Exec_Time : constant String := Trim (Duration'Image (Get_Execution_Time (Info)), Ada.Strings.Both); begin Start_Testcase_Tag (File => File, Parent => Parent_Test, Name => Get_Routine_Name (Info), Execution_Time => Exec_Time); Put (File, "<failure "); Print_Attribute (File, "type", Filter_String (Trim (Get_Message (Info), Ada.Strings.Both))); Put (File, ">"); Put_Line (File, Filter_String (Get_Message (Info))); Put_Line (File, "</failure>"); if Length (Get_Output_File (Info)) > 0 then Put (File, "<system-out>"); Print_Log_File (File, To_String (Get_Output_File (Info))); Put_Line (File, "</system-out>"); end if; End_Testcase_Tag (File); end Print_Test_Failure; procedure Print_Test_Error (File : File_Type; Parent_Test : String; Info : Result_Info) is Exec_Time : constant String := Trim (Duration'Image (Get_Execution_Time (Info)), Ada.Strings.Both); begin Start_Testcase_Tag (File => File, Parent => Parent_Test, Name => Get_Routine_Name (Info), Execution_Time => Exec_Time); Put (File, "<error "); Print_Attribute (File, "type", Filter_String (Trim (Get_Message (Info), Ada.Strings.Both))); Put (File, ">"); Put_Line (File, Filter_String (Get_Message (Info))); Put_Line (File, "</error>"); if Length (Get_Output_File (Info)) > 0 then Put (File, "<system-out>"); Print_Log_File (File, To_String (Get_Output_File (Info))); Put_Line (File, "</system-out>"); end if; End_Testcase_Tag (File); end Print_Test_Error; procedure Print_Test_Case (Collection : Result_Collection; Dir : String) is procedure Print (Output : File_Type; Result : Result_Collection); -- Internal procedure to print the testcase into given file. function Img (Value : Natural) return String is begin return Trim (Natural'Image (Value), Ada.Strings.Both); end Img; procedure Print (Output : File_Type; Result : Result_Collection) is Position : Result_Info_Cursor; begin Put_Line (Output, "<?xml version=" & '"' & "1.0" & '"' & " encoding=" & '"' & "iso-8859-1" & '"' & "?>"); Put (Output, "<testsuite "); Print_Attribute (Output, "errors", Img (Error_Count (Result))); Put (Output, " "); Print_Attribute (Output, "failures", Img (Failure_Count (Result))); Put (Output, " "); Print_Attribute (Output, "skips", Img (Skipped_Count (Result))); Put (Output, " "); Print_Attribute (Output, "tests", Img (Test_Count (Result))); Put (Output, " "); Print_Attribute (Output, "time", Trim (Duration'Image (Get_Execution_Time (Result)), Ada.Strings.Both)); Put (Output, " "); Print_Attribute (Output, "name", To_String (Get_Test_Name (Result))); Put_Line (Output, ">"); Position := First_Error (Result); Error_Loop: loop exit Error_Loop when not Is_Valid (Position); Print_Test_Error (Output, To_String (Get_Test_Name (Result)), Data (Position)); Position := Next (Position); end loop Error_Loop; Position := First_Failure (Result); Failure_Loop: loop exit Failure_Loop when not Is_Valid (Position); Print_Test_Failure (Output, To_String (Get_Test_Name (Result)), Data (Position)); Position := Next (Position); end loop Failure_Loop; Position := First_Pass (Result); Pass_Loop: loop exit Pass_Loop when not Is_Valid (Position); Print_Test_Pass (Output, To_String (Get_Test_Name (Result)), Data (Position)); Position := Next (Position); end loop Pass_Loop; Position := First_Skipped (Result); Skip_Loop: loop exit Skip_Loop when not Is_Valid (Position); Print_Test_Skipped (Output, To_String (Get_Test_Name (Result)), Data (Position)); Position := Next (Position); end loop Skip_Loop; Put_Line (Output, "</testsuite>"); end Print; File : File_Type; begin if Dir = "-" then Print (Standard_Output, Collection); else Create (File => File, Mode => Ada.Text_IO.Out_File, Name => Create_Name (Dir, To_String (Get_Test_Name (Collection)))); Print (File, Collection); Ada.Text_IO.Close (File); end if; end Print_Test_Case; procedure Report_Results (Result : Result_Collection; Dir : String) is Position : Result_Collection_Cursor; begin Position := First_Child (Result); loop exit when not Is_Valid (Position); if Child_Depth (Data (Position).all) = 0 then Print_Test_Case (Data (Position).all, Dir); else Report_Results (Data (Position).all, Dir); -- Handle the test cases in this collection if Direct_Test_Count (Result) > 0 then Print_Test_Case (Result, Dir); end if; end if; Position := Next (Position); end loop; end Report_Results; -- Print the log by placing the data inside CDATA block. procedure Print_Log_File (File : File_Type; Filename : String) is type CData_End_State is (NONE, FIRST_BRACKET, SECOND_BRACKET); function State_Change (Old_State : CData_End_State) return CData_End_State; Handle : File_Type; Char : Character := ' '; First : Boolean := True; -- We need to escape ]]>, this variable tracks -- the characters, so we know when to do the escaping. CData_Ending : CData_End_State := NONE; function State_Change (Old_State : CData_End_State) return CData_End_State is New_State : CData_End_State := NONE; -- By default New_State will be NONE, so there is -- no need to set it inside when blocks. begin case Old_State is when NONE => if Char = ']' then New_State := FIRST_BRACKET; end if; when FIRST_BRACKET => if Char = ']' then New_State := SECOND_BRACKET; end if; when SECOND_BRACKET => if Char = '>' then Put (File, " "); end if; end case; return New_State; end State_Change; begin Open (Handle, In_File, Filename); loop exit when End_Of_File (Handle); Get (Handle, Char); if First then Put (File, "<![CDATA["); First := False; end if; CData_Ending := State_Change (CData_Ending); Put (File, Char); if End_Of_Line (Handle) then New_Line (File); end if; end loop; Close (Handle); if not First then Put_Line (File, "]]>"); end if; end Print_Log_File; procedure Do_Report (Test_Results : Results.Result_Collection; Args : Parameters.Parameter_Info) is begin Report_Results (Test_Results, Parameters.Result_Dir (Args)); end Do_Report; procedure Run (Suite : in out Framework.Test_Suite'Class) is begin Runner.Run_Suite (Suite, Do_Report'Access); end Run; procedure Run (Suite : Framework.Test_Suite_Access) is begin Run (Suite.all); end Run; end Ahven.XML_Runner;
-- -- Copyright (c) 2007-2009 Tero Koskinen <[email protected]> -- -- Permission to use, copy, modify, and distribute this software for any -- purpose with or without fee is hereby granted, provided that the above -- copyright notice and this permission notice appear in all copies. -- -- THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES -- WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF -- MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR -- ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES -- WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN -- ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF -- OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. -- with Ada.Text_IO; with Ada.Strings; with Ada.Strings.Fixed; with Ada.Strings.Maps; with Ada.IO_Exceptions; with Ahven.Runner; with Ahven_Compat; with Ahven.AStrings; package body Ahven.XML_Runner is use Ada.Text_IO; use Ada.Strings.Fixed; use Ada.Strings.Maps; use Ahven.Results; use Ahven.Framework; use Ahven.AStrings; function Filter_String (Str : String) return String; function Filter_String (Str : String; Map : Character_Mapping) return String; procedure Print_Test_Pass (File : File_Type; Parent_Test : String; Info : Result_Info); procedure Print_Test_Failure (File : File_Type; Parent_Test : String; Info : Result_Info); procedure Print_Test_Error (File : File_Type; Parent_Test : String; Info : Result_Info); procedure Print_Test_Case (Collection : Result_Collection; Dir : String); procedure Print_Log_File (File : File_Type; Filename : String); procedure Print_Attribute (File : File_Type; Attr : String; Value : String); procedure Start_Testcase_Tag (File : File_Type; Parent : String; Name : String; Execution_Time : String); procedure End_Testcase_Tag (File : File_Type); function Create_Name (Dir : String; Name : String) return String; function Filter_String (Str : String) return String is Result : String (Str'First .. Str'First + 6 * Str'Length); Pos : Natural := Str'First; begin for I in Str'Range loop if Str (I) = ''' then Result (Pos .. Pos + 6 - 1) := "&apos;"; Pos := Pos + 6; elsif Str (I) = '<' then Result (Pos .. Pos + 4 - 1) := "&lt;"; Pos := Pos + 4; elsif Str (I) = '>' then Result (Pos .. Pos + 4 - 1) := "&gt;"; Pos := Pos + 4; elsif Str (I) = '&' then Result (Pos .. Pos + 5 - 1) := "&amp;"; Pos := Pos + 5; elsif Str (I) = '"' then Result (Pos) := '''; Pos := Pos + 1; else Result (Pos) := Str (I); Pos := Pos + 1; end if; end loop; return Result (Result'First .. Pos - 1); end Filter_String; function Filter_String (Str : String; Map : Character_Mapping) return String is begin return Translate (Source => Str, Mapping => Map); end Filter_String; procedure Print_Attribute (File : File_Type; Attr : String; Value : String) is begin Put (File, Attr & "=" & '"' & Value & '"'); end Print_Attribute; procedure Start_Testcase_Tag (File : File_Type; Parent : String; Name : String; Execution_Time : String) is begin Put (File, "<testcase "); Print_Attribute (File, "classname", Filter_String (Parent)); Put (File, " "); Print_Attribute (File, "name", Filter_String (Name)); Put (File, " "); Print_Attribute (File, "time", Filter_String (Execution_Time)); Put_Line (File, ">"); end Start_Testcase_Tag; procedure End_Testcase_Tag (File : File_Type) is begin Put_Line (File, "</testcase>"); end End_Testcase_Tag; function Create_Name (Dir : String; Name : String) return String is function Filename (Test : String) return String is Map : Ada.Strings.Maps.Character_Mapping; begin Map := To_Mapping (From => " '/\<>:|?*()" & '"', To => "-___________" & '_'); return "TEST-" & Filter_String (Test, Map) & ".xml"; end Filename; begin if Dir'Length > 0 then return Dir & Ahven_Compat.Directory_Separator & Filename (Name); else return Filename (Name); end if; end Create_Name; procedure Print_Test_Pass (File : File_Type; Parent_Test : String; Info : Result_Info) is Exec_Time : constant String := Trim (Duration'Image (Get_Execution_Time (Info)), Ada.Strings.Both); begin Start_Testcase_Tag (File => File, Parent => Parent_Test, Name => Get_Routine_Name (Info), Execution_Time => Exec_Time); if Length (Get_Output_File (Info)) > 0 then Put (File, "<system-out>"); Print_Log_File (File, To_String (Get_Output_File (Info))); Put_Line (File, "</system-out>"); end if; End_Testcase_Tag (File); end Print_Test_Pass; procedure Print_Test_Skipped (File : File_Type; Parent_Test : String; Info : Result_Info) is Exec_Time : constant String := Trim (Duration'Image (Get_Execution_Time (Info)), Ada.Strings.Both); begin Start_Testcase_Tag (File => File, Parent => Parent_Test, Name => Get_Routine_Name (Info), Execution_Time => Exec_Time); Put (File, "<skipped "); Print_Attribute (File, "message", Filter_String (Trim (Get_Message (Info), Ada.Strings.Both))); Put (File, ">"); Put_Line (File, Filter_String (Get_Message (Info))); Put_Line (File, "</skipped>"); End_Testcase_Tag (File); end Print_Test_Skipped; procedure Print_Test_Failure (File : File_Type; Parent_Test : String; Info : Result_Info) is Exec_Time : constant String := Trim (Duration'Image (Get_Execution_Time (Info)), Ada.Strings.Both); begin Start_Testcase_Tag (File => File, Parent => Parent_Test, Name => Get_Routine_Name (Info), Execution_Time => Exec_Time); Put (File, "<failure "); Print_Attribute (File, "type", Filter_String (Trim (Get_Message (Info), Ada.Strings.Both))); Put (File, ">"); Put_Line (File, Filter_String (Get_Message (Info))); Put_Line (File, "</failure>"); if Length (Get_Output_File (Info)) > 0 then Put (File, "<system-out>"); Print_Log_File (File, To_String (Get_Output_File (Info))); Put_Line (File, "</system-out>"); end if; End_Testcase_Tag (File); end Print_Test_Failure; procedure Print_Test_Error (File : File_Type; Parent_Test : String; Info : Result_Info) is Exec_Time : constant String := Trim (Duration'Image (Get_Execution_Time (Info)), Ada.Strings.Both); begin Start_Testcase_Tag (File => File, Parent => Parent_Test, Name => Get_Routine_Name (Info), Execution_Time => Exec_Time); Put (File, "<error "); Print_Attribute (File, "type", Filter_String (Trim (Get_Message (Info), Ada.Strings.Both))); Put (File, ">"); Put_Line (File, Filter_String (Get_Message (Info))); Put_Line (File, "</error>"); if Length (Get_Output_File (Info)) > 0 then Put (File, "<system-out>"); Print_Log_File (File, To_String (Get_Output_File (Info))); Put_Line (File, "</system-out>"); end if; End_Testcase_Tag (File); end Print_Test_Error; procedure Print_Test_Case (Collection : Result_Collection; Dir : String) is procedure Print (Output : File_Type; Result : Result_Collection); -- Internal procedure to print the testcase into given file. function Img (Value : Natural) return String is begin return Trim (Natural'Image (Value), Ada.Strings.Both); end Img; procedure Print (Output : File_Type; Result : Result_Collection) is Position : Result_Info_Cursor; begin Put_Line (Output, "<?xml version=" & '"' & "1.0" & '"' & " encoding=" & '"' & "iso-8859-1" & '"' & "?>"); Put (Output, "<testsuite "); Print_Attribute (Output, "errors", Img (Error_Count (Result))); Put (Output, " "); Print_Attribute (Output, "failures", Img (Failure_Count (Result))); Put (Output, " "); Print_Attribute (Output, "skips", Img (Skipped_Count (Result))); Put (Output, " "); Print_Attribute (Output, "tests", Img (Test_Count (Result))); Put (Output, " "); Print_Attribute (Output, "time", Trim (Duration'Image (Get_Execution_Time (Result)), Ada.Strings.Both)); Put (Output, " "); Print_Attribute (Output, "name", To_String (Get_Test_Name (Result))); Put_Line (Output, ">"); Position := First_Error (Result); Error_Loop: loop exit Error_Loop when not Is_Valid (Position); Print_Test_Error (Output, To_String (Get_Test_Name (Result)), Data (Position)); Position := Next (Position); end loop Error_Loop; Position := First_Failure (Result); Failure_Loop: loop exit Failure_Loop when not Is_Valid (Position); Print_Test_Failure (Output, To_String (Get_Test_Name (Result)), Data (Position)); Position := Next (Position); end loop Failure_Loop; Position := First_Pass (Result); Pass_Loop: loop exit Pass_Loop when not Is_Valid (Position); Print_Test_Pass (Output, To_String (Get_Test_Name (Result)), Data (Position)); Position := Next (Position); end loop Pass_Loop; Position := First_Skipped (Result); Skip_Loop: loop exit Skip_Loop when not Is_Valid (Position); Print_Test_Skipped (Output, To_String (Get_Test_Name (Result)), Data (Position)); Position := Next (Position); end loop Skip_Loop; Put_Line (Output, "</testsuite>"); end Print; File : File_Type; begin if Dir = "-" then Print (Standard_Output, Collection); else Create (File => File, Mode => Ada.Text_IO.Out_File, Name => Create_Name (Dir, To_String (Get_Test_Name (Collection)))); Print (File, Collection); Ada.Text_IO.Close (File); end if; end Print_Test_Case; procedure Report_Results (Result : Result_Collection; Dir : String) is Position : Result_Collection_Cursor; begin Position := First_Child (Result); loop exit when not Is_Valid (Position); if Child_Depth (Data (Position).all) = 0 then Print_Test_Case (Data (Position).all, Dir); else Report_Results (Data (Position).all, Dir); -- Handle the test cases in this collection if Direct_Test_Count (Result) > 0 then Print_Test_Case (Result, Dir); end if; end if; Position := Next (Position); end loop; end Report_Results; -- Print the log by placing the data inside CDATA block. procedure Print_Log_File (File : File_Type; Filename : String) is type CData_End_State is (NONE, FIRST_BRACKET, SECOND_BRACKET); function State_Change (Old_State : CData_End_State) return CData_End_State; Handle : File_Type; Char : Character := ' '; First : Boolean := True; -- We need to escape ]]>, this variable tracks -- the characters, so we know when to do the escaping. CData_Ending : CData_End_State := NONE; function State_Change (Old_State : CData_End_State) return CData_End_State is New_State : CData_End_State := NONE; -- By default New_State will be NONE, so there is -- no need to set it inside when blocks. begin case Old_State is when NONE => if Char = ']' then New_State := FIRST_BRACKET; end if; when FIRST_BRACKET => if Char = ']' then New_State := SECOND_BRACKET; end if; when SECOND_BRACKET => if Char = '>' then Put (File, " "); end if; end case; return New_State; end State_Change; begin Open (Handle, In_File, Filename); begin loop exit when End_Of_File (Handle); Get (Handle, Char); if First then Put (File, "<![CDATA["); First := False; end if; CData_Ending := State_Change (CData_Ending); Put (File, Char); if End_Of_Line (Handle) then New_Line (File); end if; end loop; -- The End_Error exception is sometimes raised. exception when Ada.IO_Exceptions.End_Error => null; end; Close (Handle); if not First then Put_Line (File, "]]>"); end if; end Print_Log_File; procedure Do_Report (Test_Results : Results.Result_Collection; Args : Parameters.Parameter_Info) is begin Report_Results (Test_Results, Parameters.Result_Dir (Args)); end Do_Report; procedure Run (Suite : in out Framework.Test_Suite'Class) is begin Runner.Run_Suite (Suite, Do_Report'Access); end Run; procedure Run (Suite : Framework.Test_Suite_Access) is begin Run (Suite.all); end Run; end Ahven.XML_Runner;
Handle the End_Error exception which can be raised while reading a file
Handle the End_Error exception which can be raised while reading a file
Ada
apache-2.0
flottokarotto/ada-util,Letractively/ada-util,flottokarotto/ada-util,Letractively/ada-util
54a052a319cb65e99704be80a687ced2367e5c3b
src/base/properties/util-properties-bundles.adb
src/base/properties/util-properties-bundles.adb
----------------------------------------------------------------------- -- util-properties-bundles -- Generic name/value property management -- Copyright (C) 2001 - 2018 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Unchecked_Deallocation; with Ada.Unchecked_Conversion; with Ada.Directories; with Ada.Containers.Vectors; with Ada.Strings.Fixed; with Util.Log.Loggers; with Util.Files; package body Util.Properties.Bundles is Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("Util.Properties.Bundles"); procedure Free is new Ada.Unchecked_Deallocation (Manager'Class, Bundle_Manager_Access); -- Implementation of the Bundle -- (this allows to decouples the implementation from the API) package Interface_P is type Manager is new Util.Properties.Interface_P.Manager with private; -- Get the value identified by the name. -- If the name cannot be found, the method should return the Null object. overriding function Get_Value (From : in Manager; Name : in String) return Util.Beans.Objects.Object; -- Set the value identified by the name. -- If the map contains the given name, the value changed. -- Otherwise name is added to the map and the value associated with it. overriding procedure Set_Value (From : in out Manager; Name : in String; Value : in Util.Beans.Objects.Object); -- Returns TRUE if the property exists. overriding function Exists (Self : in Manager; Name : in String) return Boolean; -- Remove the property given its name. overriding procedure Remove (Self : in out Manager; Name : in String); -- Iterate over the properties and execute the given procedure passing the -- property name and its value. overriding procedure Iterate (Self : in Manager; Process : access procedure (Name : in String; Item : in Util.Beans.Objects.Object)); procedure Load_Properties (Self : in out Manager; File : in String); -- Deep copy of properties stored in 'From' to 'To'. function Create_Copy (Self : in Manager) return Util.Properties.Interface_P.Manager_Access; procedure Add_Bundle (Self : in out Manager; Props : in Util.Properties.Manager_Access); private package PropertyList is new Ada.Containers.Vectors (Element_Type => Util.Properties.Manager_Access, Index_Type => Natural, "=" => "="); type Manager is new Util.Properties.Interface_P.Manager with record List : PropertyList.Vector; Props : aliased Util.Properties.Manager; end record; end Interface_P; procedure Add_Bundle (Self : in out Manager; Props : in Manager_Access) is begin Interface_P.Manager'Class (Self.Impl.all).Add_Bundle (Props); end Add_Bundle; procedure Initialize (Object : in out Manager) is use Util.Properties.Interface_P; begin Object.Impl := new Util.Properties.Bundles.Interface_P.Manager; Util.Concurrent.Counters.Increment (Object.Impl.Count); end Initialize; procedure Adjust (Object : in out Manager) is use Util.Properties.Interface_P; begin if Object.Impl = null then Object.Impl := new Util.Properties.Bundles.Interface_P.Manager; end if; Util.Concurrent.Counters.Increment (Object.Impl.Count); end Adjust; -- ------------------------------ -- Initialize the bundle factory and specify where the property files are stored. -- ------------------------------ procedure Initialize (Factory : in out Loader; Path : in String) is begin Log.Info ("Initialize bundle factory to load from {0}", Path); Factory.Path := To_Unbounded_String (Path); end Initialize; -- ------------------------------ -- Load the bundle with the given name and for the given locale name. -- ------------------------------ procedure Load_Bundle (Factory : in out Loader; Name : in String; Locale : in String; Bundle : out Manager'Class) is Found : Boolean := False; begin Log.Info ("Load bundle {0} for language {1}", Name, Locale); Find_Bundle (Factory, Name, Locale, Bundle, Found); if not Found then Load_Bundle (Factory, Name, Found); if not Found then Log.Error ("Bundle {0} not found", Name); raise NO_BUNDLE with "No bundle '" & Name & "'"; end if; Find_Bundle (Factory, Name, Locale, Bundle, Found); if not Found then Log.Error ("Bundle {0} not found", Name); raise NO_BUNDLE with "No bundle '" & Name & "'"; end if; end if; end Load_Bundle; -- ------------------------------ -- Find the bundle with the given name and for the given locale name. -- ------------------------------ procedure Find_Bundle (Factory : in out Loader; Name : in String; Locale : in String; Bundle : out Manager'Class; Found : out Boolean) is use Ada.Strings; Loc_Name : constant String := '_' & Locale; Last_Pos : Integer := Loc_Name'Last; begin Log.Debug ("Looking for bundle {0} and language {1}", Name, Locale); Found := False; Factory.Lock.Read; declare Pos : Bundle_Map.Cursor; begin while Last_Pos + 1 >= Loc_Name'First loop declare Bundle_Name : aliased constant String := Name & Loc_Name (Loc_Name'First .. Last_Pos); begin Log.Debug ("Searching for {0}", Bundle_Name); Pos := Factory.Bundles.Find (Bundle_Name'Unrestricted_Access); if Bundle_Map.Has_Element (Pos) then Bundle.Finalize; Bundle.Impl := Bundle_Map.Element (Pos).Impl; Util.Concurrent.Counters.Increment (Bundle.Impl.Count); Found := True; exit; end if; end; if Last_Pos > Loc_Name'First then Last_Pos := Fixed.Index (Loc_Name, "_", Last_Pos - 1, Backward) - 1; else Last_Pos := Last_Pos - 1; end if; end loop; exception when others => Factory.Lock.Release_Read; raise; end; Factory.Lock.Release_Read; end Find_Bundle; -- ------------------------------ -- Load the bundle with the given name and for the given locale name. -- ------------------------------ procedure Load_Bundle (Factory : in out Loader; Name : in String; Found : out Boolean) is use Ada.Directories; use Ada.Strings; use Util.Strings; use Ada.Containers; use Util.Strings.String_Set; use Bundle_Map; procedure Process_File (Name : in String; File_Path : in String; Done : out Boolean); Path : constant String := To_String (Factory.Path); Pattern : constant String := Name & "*.properties"; Names : Util.Strings.String_Set.Set; procedure Process_File (Name : in String; File_Path : in String; Done : out Boolean) is subtype Cursor is Bundle_Map.Cursor; Base_Name : aliased constant String := Name (Name'First .. Name'Last - 11); Pos : constant Cursor := Factory.Bundles.Find (Base_Name'Unchecked_Access); Bundle_Name : Name_Access; Bundle : Bundle_Manager_Access; begin Log.Info ("Loading file {0}", File_Path); if Bundle_Map.Has_Element (Pos) then Bundle := Bundle_Map.Element (Pos); else Bundle := new Manager; Bundle_Name := new String '(Base_Name); Factory.Bundles.Include (Key => Bundle_Name, New_Item => Bundle); Names.Insert (Bundle_Name); end if; Interface_P.Manager'Class (Bundle.Impl.all).Load_Properties (File_Path); Found := True; Done := False; end Process_File; begin Log.Info ("Reading bundle {1} in directory {0}", Path, Name); Found := False; Factory.Lock.Write; begin Util.Files.Iterate_Files_Path (Pattern => Pattern, Path => Path, Process => Process_File'Access, Going => Ada.Strings.Backward); -- Link the property files to implement the localization default rules. while Names.Length > 0 loop declare Name_Pos : String_Set.Cursor := Names.First; Bundle_Name : constant Name_Access := String_Set.Element (Name_Pos); Idx : Natural := Fixed.Index (Bundle_Name.all, "_", Backward); Bundle_Pos : constant Bundle_Map.Cursor := Factory.Bundles.Find (Bundle_Name); Bundle : constant Bundle_Manager_Access := Element (Bundle_Pos); begin Names.Delete (Name_Pos); -- Associate the property bundle to the first existing parent -- Ex: message_fr_CA -> message_fr -- message_fr_CA -> message while Idx > 0 loop declare Name : aliased constant String := Bundle_Name (Bundle_Name'First .. Idx - 1); Pos : constant Bundle_Map.Cursor := Factory.Bundles.Find (Name'Unchecked_Access); begin if Bundle_Map.Has_Element (Pos) then Bundle.Add_Bundle (Bundle_Map.Element (Pos).all'Access); Idx := 0; else Idx := Fixed.Index (Bundle_Name.all, "_", Idx - 1, Backward); end if; end; end loop; end; end loop; exception when others => Factory.Lock.Release_Write; raise; end; Factory.Lock.Release_Write; exception when Name_Error => Log.Error ("Cannot read directory: {0}", Path); end Load_Bundle; -- Implementation of the Bundle -- (this allows to decouples the implementation from the API) package body Interface_P is use PropertyList; -- Get the value identified by the name. -- If the name cannot be found, the method should return the Null object. overriding function Get_Value (From : in Manager; Name : in String) return Util.Beans.Objects.Object is Result : Util.Beans.Objects.Object := From.Props.Get_Value (Name); begin if Util.Beans.Objects.Is_Null (Result) then declare Iter : Cursor := From.List.First; begin while Has_Element (Iter) loop Result := Element (Iter).all.Get_Value (Name); exit when not Util.Beans.Objects.Is_Null (Result); Iter := Next (Iter); end loop; end; end if; return Result; end Get_Value; -- Set the value identified by the name. -- If the map contains the given name, the value changed. -- Otherwise name is added to the map and the value associated with it. overriding procedure Set_Value (From : in out Manager; Name : in String; Value : in Util.Beans.Objects.Object) is begin raise NOT_WRITEABLE with "Bundle is readonly"; end Set_Value; -- ------------------------------ -- Returns TRUE if the property exists. -- ------------------------------ function Exists (Self : in Manager; Name : in String) return Boolean is Iter : Cursor := Self.List.First; begin if Self.Props.Exists (Name) then return True; end if; while Has_Element (Iter) loop if Element (Iter).Exists (Name) then return True; end if; Iter := Next (Iter); end loop; return False; end Exists; procedure Load_Properties (Self : in out Manager; File : in String) is begin Self.Props.Load_Properties (File); end Load_Properties; -- ------------------------------ -- Remove the property given its name. -- ------------------------------ procedure Remove (Self : in out Manager; Name : in String) is begin raise NOT_WRITEABLE with "Bundle is readonly"; end Remove; -- Iterate over the properties and execute the given procedure passing the -- property name and its value. procedure Iterate (Self : in Manager; Process : access procedure (Name : in String; Item : in Util.Beans.Objects.Object)) is begin raise Program_Error with "Iterate is not implemented on Bundle"; end Iterate; -- ------------------------------ -- Deep copy of properties stored in 'From' to 'To'. -- ------------------------------ function Create_Copy (Self : in Manager) return Util.Properties.Interface_P.Manager_Access is pragma Unreferenced (Self); begin return null; end Create_Copy; procedure Add_Bundle (Self : in out Manager; Props : in Util.Properties.Manager_Access) is begin Self.List.Append (Props); end Add_Bundle; end Interface_P; -- ------------------------------ -- Clear the bundle cache -- ------------------------------ procedure Clear_Cache (Factory : in out Loader) is use Util.Strings; use Bundle_Map; function To_String_Access is new Ada.Unchecked_Conversion (Source => Util.Strings.Name_Access, Target => Ada.Strings.Unbounded.String_Access); begin Log.Info ("Clearing bundle cache"); Factory.Lock.Write; loop declare Pos : Bundle_Map.Cursor := Factory.Bundles.First; Name : Ada.Strings.Unbounded.String_Access; Node : Bundle_Manager_Access; begin exit when not Has_Element (Pos); Node := Element (Pos); Name := To_String_Access (Key (Pos)); Factory.Bundles.Delete (Pos); Free (Node); Free (Name); end; end loop; Factory.Lock.Release_Write; end Clear_Cache; -- ------------------------------ -- Finalize the bundle loader and clear the cache -- ------------------------------ procedure Finalize (Factory : in out Loader) is begin Clear_Cache (Factory); end Finalize; end Util.Properties.Bundles;
----------------------------------------------------------------------- -- util-properties-bundles -- Generic name/value property management -- Copyright (C) 2001 - 2020 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Unchecked_Deallocation; with Ada.Unchecked_Conversion; with Ada.Directories; with Ada.Containers.Vectors; with Ada.Strings.Fixed; with Util.Log.Loggers; with Util.Files; with Util.Concurrent.Counters; package body Util.Properties.Bundles is Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("Util.Properties.Bundles"); use Implementation; procedure Free is new Ada.Unchecked_Deallocation (Manager'Class, Bundle_Manager_Access); -- Implementation of the Bundle -- (this allows to decouples the implementation from the API) package Interface_P is package PropertyList is new Ada.Containers.Vectors (Element_Type => Util.Properties.Manager_Access, Index_Type => Natural, "=" => "="); type Manager is limited new Util.Properties.Implementation.Manager with record List : PropertyList.Vector; Props : aliased Util.Properties.Manager; Count : Util.Concurrent.Counters.Counter := Util.Concurrent.Counters.ONE; Shared : Boolean := False; end record; -- Get the value identified by the name. -- If the name cannot be found, the method should return the Null object. overriding function Get_Value (From : in Manager; Name : in String) return Util.Beans.Objects.Object; -- Set the value identified by the name. -- If the map contains the given name, the value changed. -- Otherwise name is added to the map and the value associated with it. overriding procedure Set_Value (From : in out Manager; Name : in String; Value : in Util.Beans.Objects.Object); -- Returns TRUE if the property exists. overriding function Exists (Self : in Manager; Name : in String) return Boolean; -- Remove the property given its name. overriding procedure Remove (Self : in out Manager; Name : in String); -- Iterate over the properties and execute the given procedure passing the -- property name and its value. overriding procedure Iterate (Self : in Manager; Process : access procedure (Name : in String; Item : in Util.Beans.Objects.Object)); procedure Load_Properties (Self : in out Manager; File : in String); -- Deep copy of properties stored in 'From' to 'To'. overriding function Create_Copy (Self : in Manager) return Util.Properties.Implementation.Manager_Access; procedure Add_Bundle (Self : in out Manager; Props : in Util.Properties.Manager_Access); package Shared_Implementation is new Implementation.Shared_Implementation (Manager); subtype Shared_Manager is Shared_Implementation.Manager; function Allocate_Property return Implementation.Shared_Manager_Access is (new Shared_Manager); -- Create a property implementation if there is none yet. procedure Check_And_Create_Impl is new Implementation.Create (Allocator => Allocate_Property); end Interface_P; procedure Add_Bundle (Self : in out Manager; Props : in Manager_Access) is begin Interface_P.Manager'Class (Self.Impl.all).Add_Bundle (Props); end Add_Bundle; procedure Initialize (Object : in out Manager) is begin Interface_P.Check_And_Create_Impl (Object); end Initialize; procedure Adjust (Object : in out Manager) is begin Interface_P.Check_And_Create_Impl (Object); Object.Impl.Adjust; end Adjust; -- ------------------------------ -- Initialize the bundle factory and specify where the property files are stored. -- ------------------------------ procedure Initialize (Factory : in out Loader; Path : in String) is begin Log.Info ("Initialize bundle factory to load from {0}", Path); Factory.Path := To_Unbounded_String (Path); end Initialize; -- ------------------------------ -- Load the bundle with the given name and for the given locale name. -- ------------------------------ procedure Load_Bundle (Factory : in out Loader; Name : in String; Locale : in String; Bundle : out Manager'Class) is Found : Boolean := False; begin Log.Info ("Load bundle {0} for language {1}", Name, Locale); Find_Bundle (Factory, Name, Locale, Bundle, Found); if not Found then Load_Bundle (Factory, Name, Found); if not Found then Log.Error ("Bundle {0} not found", Name); raise NO_BUNDLE with "No bundle '" & Name & "'"; end if; Find_Bundle (Factory, Name, Locale, Bundle, Found); if not Found then Log.Error ("Bundle {0} not found", Name); raise NO_BUNDLE with "No bundle '" & Name & "'"; end if; end if; end Load_Bundle; -- ------------------------------ -- Find the bundle with the given name and for the given locale name. -- ------------------------------ procedure Find_Bundle (Factory : in out Loader; Name : in String; Locale : in String; Bundle : out Manager'Class; Found : out Boolean) is use Ada.Strings; Loc_Name : constant String := '_' & Locale; Last_Pos : Integer := Loc_Name'Last; begin Log.Debug ("Looking for bundle {0} and language {1}", Name, Locale); Found := False; Factory.Lock.Read; declare Pos : Bundle_Map.Cursor; begin while Last_Pos + 1 >= Loc_Name'First loop declare Bundle_Name : aliased constant String := Name & Loc_Name (Loc_Name'First .. Last_Pos); begin Log.Debug ("Searching for {0}", Bundle_Name); Pos := Factory.Bundles.Find (Bundle_Name'Unrestricted_Access); if Bundle_Map.Has_Element (Pos) then Bundle.Finalize; Bundle.Impl := Bundle_Map.Element (Pos).Impl; Bundle.Impl.Adjust; Found := True; exit; end if; end; if Last_Pos > Loc_Name'First then Last_Pos := Fixed.Index (Loc_Name, "_", Last_Pos - 1, Backward) - 1; else Last_Pos := Last_Pos - 1; end if; end loop; exception when others => Factory.Lock.Release_Read; raise; end; Factory.Lock.Release_Read; end Find_Bundle; -- ------------------------------ -- Load the bundle with the given name and for the given locale name. -- ------------------------------ procedure Load_Bundle (Factory : in out Loader; Name : in String; Found : out Boolean) is use Ada.Directories; use Ada.Strings; use Util.Strings; use Ada.Containers; use Util.Strings.String_Set; use Bundle_Map; procedure Process_File (Name : in String; File_Path : in String; Done : out Boolean); Path : constant String := To_String (Factory.Path); Pattern : constant String := Name & "*.properties"; Names : Util.Strings.String_Set.Set; procedure Process_File (Name : in String; File_Path : in String; Done : out Boolean) is subtype Cursor is Bundle_Map.Cursor; Base_Name : aliased constant String := Name (Name'First .. Name'Last - 11); Pos : constant Cursor := Factory.Bundles.Find (Base_Name'Unchecked_Access); Bundle_Name : Name_Access; Bundle : Bundle_Manager_Access; begin Log.Info ("Loading file {0}", File_Path); if Bundle_Map.Has_Element (Pos) then Bundle := Bundle_Map.Element (Pos); else Bundle := new Manager; Bundle_Name := new String '(Base_Name); Factory.Bundles.Include (Key => Bundle_Name, New_Item => Bundle); Names.Insert (Bundle_Name); end if; Interface_P.Manager'Class (Bundle.Impl.all).Load_Properties (File_Path); Found := True; Done := False; end Process_File; begin Log.Info ("Reading bundle {1} in directory {0}", Path, Name); Found := False; Factory.Lock.Write; begin Util.Files.Iterate_Files_Path (Pattern => Pattern, Path => Path, Process => Process_File'Access, Going => Ada.Strings.Backward); -- Link the property files to implement the localization default rules. while Names.Length > 0 loop declare Name_Pos : String_Set.Cursor := Names.First; Bundle_Name : constant Name_Access := String_Set.Element (Name_Pos); Idx : Natural := Fixed.Index (Bundle_Name.all, "_", Backward); Bundle_Pos : constant Bundle_Map.Cursor := Factory.Bundles.Find (Bundle_Name); Bundle : constant Bundle_Manager_Access := Element (Bundle_Pos); begin Names.Delete (Name_Pos); -- Associate the property bundle to the first existing parent -- Ex: message_fr_CA -> message_fr -- message_fr_CA -> message while Idx > 0 loop declare Name : aliased constant String := Bundle_Name (Bundle_Name'First .. Idx - 1); Pos : constant Bundle_Map.Cursor := Factory.Bundles.Find (Name'Unchecked_Access); begin if Bundle_Map.Has_Element (Pos) then Bundle.Add_Bundle (Bundle_Map.Element (Pos).all'Access); Idx := 0; else Idx := Fixed.Index (Bundle_Name.all, "_", Idx - 1, Backward); end if; end; end loop; end; end loop; exception when others => Factory.Lock.Release_Write; raise; end; Factory.Lock.Release_Write; exception when Name_Error => Log.Error ("Cannot read directory: {0}", Path); end Load_Bundle; -- Implementation of the Bundle -- (this allows to decouples the implementation from the API) package body Interface_P is use PropertyList; -- Get the value identified by the name. -- If the name cannot be found, the method should return the Null object. overriding function Get_Value (From : in Manager; Name : in String) return Util.Beans.Objects.Object is Result : Util.Beans.Objects.Object := From.Props.Get_Value (Name); begin if Util.Beans.Objects.Is_Null (Result) then declare Iter : Cursor := From.List.First; begin while Has_Element (Iter) loop Result := Element (Iter).all.Get_Value (Name); exit when not Util.Beans.Objects.Is_Null (Result); Iter := Next (Iter); end loop; end; end if; return Result; end Get_Value; -- Set the value identified by the name. -- If the map contains the given name, the value changed. -- Otherwise name is added to the map and the value associated with it. overriding procedure Set_Value (From : in out Manager; Name : in String; Value : in Util.Beans.Objects.Object) is begin raise NOT_WRITEABLE with "Bundle is readonly"; end Set_Value; -- ------------------------------ -- Returns TRUE if the property exists. -- ------------------------------ function Exists (Self : in Manager; Name : in String) return Boolean is Iter : Cursor := Self.List.First; begin if Self.Props.Exists (Name) then return True; end if; while Has_Element (Iter) loop if Element (Iter).Exists (Name) then return True; end if; Iter := Next (Iter); end loop; return False; end Exists; procedure Load_Properties (Self : in out Manager; File : in String) is begin Self.Props.Load_Properties (File); end Load_Properties; -- ------------------------------ -- Remove the property given its name. -- ------------------------------ procedure Remove (Self : in out Manager; Name : in String) is begin raise NOT_WRITEABLE with "Bundle is readonly"; end Remove; -- Iterate over the properties and execute the given procedure passing the -- property name and its value. procedure Iterate (Self : in Manager; Process : access procedure (Name : in String; Item : in Util.Beans.Objects.Object)) is begin raise Program_Error with "Iterate is not implemented on Bundle"; end Iterate; -- ------------------------------ -- Deep copy of properties stored in 'From' to 'To'. -- ------------------------------ overriding function Create_Copy (Self : in Manager) return Util.Properties.Implementation.Manager_Access is pragma Unreferenced (Self); begin return null; end Create_Copy; procedure Add_Bundle (Self : in out Manager; Props : in Util.Properties.Manager_Access) is begin Self.List.Append (Props); end Add_Bundle; end Interface_P; -- ------------------------------ -- Clear the bundle cache -- ------------------------------ procedure Clear_Cache (Factory : in out Loader) is use Util.Strings; use Bundle_Map; function To_String_Access is new Ada.Unchecked_Conversion (Source => Util.Strings.Name_Access, Target => Ada.Strings.Unbounded.String_Access); begin Log.Info ("Clearing bundle cache"); Factory.Lock.Write; loop declare Pos : Bundle_Map.Cursor := Factory.Bundles.First; Name : Ada.Strings.Unbounded.String_Access; Node : Bundle_Manager_Access; begin exit when not Has_Element (Pos); Node := Element (Pos); Name := To_String_Access (Key (Pos)); Factory.Bundles.Delete (Pos); Free (Node); Free (Name); end; end loop; Factory.Lock.Release_Write; end Clear_Cache; -- ------------------------------ -- Finalize the bundle loader and clear the cache -- ------------------------------ procedure Finalize (Factory : in out Loader) is begin Clear_Cache (Factory); end Finalize; end Util.Properties.Bundles;
Update the implementation to use the new public Util.Properties.Implementation package
Update the implementation to use the new public Util.Properties.Implementation package
Ada
apache-2.0
stcarrez/ada-util,stcarrez/ada-util
e2b1af64ed6b20f861be68b8c4874a8807839a66
regtests/el-expressions-tests.adb
regtests/el-expressions-tests.adb
----------------------------------------------------------------------- -- EL testsuite - EL Testsuite -- Copyright (C) 2009, 2010 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with AUnit.Test_Caller; with AUnit.Assertions; with EL.Expressions; with Test_Bean; package body EL.Expressions.Tests is use Test_Bean; use EL.Expressions; use AUnit.Assertions; use AUnit.Test_Fixtures; procedure Check_Error (T : in out Test'Class; Expr : in String); -- Check that evaluating an expression raises an exception procedure Check_Error (T : in out Test'Class; Expr : in String) is E : Expression; begin E := Create_Expression (Context => T.Context, Expr => Expr); pragma Unreferenced (E); Assert (Condition => False, Message => "Evaludation of '" & Expr & "' should raise an exception"); exception when Invalid_Expression => null; end Check_Error; -- Check that evaluating an expression returns the expected result -- (to keep the test simple, results are only checked using strings) procedure Check (T : in out Test; Expr : in String; Expect : in String) is E : constant Expression := Create_Expression (Context => T.Context, Expr => Expr); V : constant Object := E.Get_Value (Context => T.Context); begin Assert (Condition => To_String (V) = Expect, Message => "Evaluate '" & Expr & "' returned '" & To_String (V) & "' when we expect '" & Expect & "'"); declare E2 : constant Expression := E.Reduce_Expression (Context => T.Context); V2 : constant Object := E2.Get_Value (Context => T.Context); begin Assert (To_String (V2) = Expect, "Reduce produced incorrect result: " & To_String (V2)); end; end Check; -- Test evaluation of expression using a bean procedure Test_Bean_Evaluation (T : in out Test) is P : constant Person_Access := Create_Person ("Joe", "Black", 42); begin T.Context.Set_Variable ("user", P); Check (T, "#{user.firstName}", "Joe"); Check (T, "#{user.lastName}", "Black"); Check (T, "#{user.age}", " 42"); Check (T, "#{user.date}", To_String (To_Object (P.Date))); Check (T, "#{user.weight}", To_String (To_Object (P.Weight))); P.Age := P.Age + 1; Check (T, "#{user.age}", " 43"); Check (T, "#{user.firstName & ' ' & user.lastName}", "Joe Black"); Check (T, "Joe is#{user.age} year#{user.age > 0 ? 's' : ''} old", "Joe is 43 years old"); end Test_Bean_Evaluation; -- Test evaluation of expression using a bean procedure Test_Parse_Error (T : in out Test) is begin Check_Error (T, "#{1 +}"); Check_Error (T, "#{12(}"); Check_Error (T, "#{foo(1)}"); Check_Error (T, "#{1+2+'abc}"); Check_Error (T, "#{1+""}"); Check_Error (T, "#{12"); Check_Error (T, "${1"); Check_Error (T, "test #{'}"); end Test_Parse_Error; package Caller is new AUnit.Test_Caller (Test); procedure Add_Tests (Suite : AUnit.Test_Suites.Access_Test_Suite) is begin -- Test_Bean verifies several methods. Register several times -- to enumerate what is tested. Suite.Add_Test (Caller.Create ("Test EL.Contexts.Set_Variable", Test_Bean_Evaluation'Access)); Suite.Add_Test (Caller.Create ("Test EL.Beans.Get_Value", Test_Bean_Evaluation'Access)); Suite.Add_Test (Caller.Create ("Test EL.Expressions.Create_Expression", Test_Bean_Evaluation'Access)); Suite.Add_Test (Caller.Create ("Test EL.Expressions.Get_Value", Test_Bean_Evaluation'Access)); Suite.Add_Test (Caller.Create ("Test EL.Expressions.Create_Expression (Parse Error)", Test_Parse_Error'Access)); end Add_Tests; end EL.Expressions.Tests;
----------------------------------------------------------------------- -- EL testsuite - EL Testsuite -- Copyright (C) 2009, 2010 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with AUnit.Test_Caller; with AUnit.Assertions; with EL.Expressions; with Test_Bean; package body EL.Expressions.Tests is use Test_Bean; use EL.Expressions; use AUnit.Assertions; use AUnit.Test_Fixtures; procedure Check_Error (T : in out Test'Class; Expr : in String); -- Check that evaluating an expression raises an exception procedure Check_Error (T : in out Test'Class; Expr : in String) is E : Expression; begin E := Create_Expression (Context => T.Context, Expr => Expr); pragma Unreferenced (E); Assert (Condition => False, Message => "Evaludation of '" & Expr & "' should raise an exception"); exception when Invalid_Expression => null; end Check_Error; -- Check that evaluating an expression returns the expected result -- (to keep the test simple, results are only checked using strings) procedure Check (T : in out Test; Expr : in String; Expect : in String) is E : constant Expression := Create_Expression (Context => T.Context, Expr => Expr); V : constant Object := E.Get_Value (Context => T.Context); begin Assert (Condition => To_String (V) = Expect, Message => "Evaluate '" & Expr & "' returned '" & To_String (V) & "' when we expect '" & Expect & "'"); declare E2 : constant Expression := E.Reduce_Expression (Context => T.Context); V2 : constant Object := E2.Get_Value (Context => T.Context); begin Assert (To_String (V2) = Expect, "Reduce produced incorrect result: " & To_String (V2)); end; end Check; -- Test evaluation of expression using a bean procedure Test_Bean_Evaluation (T : in out Test) is P : constant Person_Access := Create_Person ("Joe", "Black", 42); begin T.Context.Set_Variable ("user", P); Check (T, "#{empty user}", "FALSE"); Check (T, "#{not empty user}", "TRUE"); Check (T, "#{user.firstName}", "Joe"); Check (T, "#{user.lastName}", "Black"); Check (T, "#{user.age}", " 42"); Check (T, "#{user.date}", To_String (To_Object (P.Date))); Check (T, "#{user.weight}", To_String (To_Object (P.Weight))); P.Age := P.Age + 1; Check (T, "#{user.age}", " 43"); Check (T, "#{user.firstName & ' ' & user.lastName}", "Joe Black"); Check (T, "Joe is#{user.age} year#{user.age > 0 ? 's' : ''} old", "Joe is 43 years old"); end Test_Bean_Evaluation; -- Test evaluation of expression using a bean procedure Test_Parse_Error (T : in out Test) is begin Check_Error (T, "#{1 +}"); Check_Error (T, "#{12(}"); Check_Error (T, "#{foo(1)}"); Check_Error (T, "#{1+2+'abc}"); Check_Error (T, "#{1+""}"); Check_Error (T, "#{12"); Check_Error (T, "${1"); Check_Error (T, "test #{'}"); end Test_Parse_Error; package Caller is new AUnit.Test_Caller (Test); procedure Add_Tests (Suite : AUnit.Test_Suites.Access_Test_Suite) is begin -- Test_Bean verifies several methods. Register several times -- to enumerate what is tested. Suite.Add_Test (Caller.Create ("Test EL.Contexts.Set_Variable", Test_Bean_Evaluation'Access)); Suite.Add_Test (Caller.Create ("Test EL.Beans.Get_Value", Test_Bean_Evaluation'Access)); Suite.Add_Test (Caller.Create ("Test EL.Expressions.Create_Expression", Test_Bean_Evaluation'Access)); Suite.Add_Test (Caller.Create ("Test EL.Expressions.Get_Value", Test_Bean_Evaluation'Access)); Suite.Add_Test (Caller.Create ("Test EL.Expressions.Create_Expression (Parse Error)", Test_Parse_Error'Access)); end Add_Tests; end EL.Expressions.Tests;
Add test for empty operator
Add test for empty operator
Ada
apache-2.0
Letractively/ada-el
87f868718f135b4ebe3a639e6c700ed519579b70
regtests/util-processes-tests.adb
regtests/util-processes-tests.adb
----------------------------------------------------------------------- -- util-processes-tests - Test for processes -- Copyright (C) 2011, 2012 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Log.Loggers; with Util.Test_Caller; with Util.Files; with Util.Streams.Pipes; with Util.Streams.Buffered; with Util.Streams.Texts; package body Util.Processes.Tests is use Util.Log; -- The logger Log : constant Loggers.Logger := Loggers.Create ("Util.Processes.Tests"); package Caller is new Util.Test_Caller (Test, "Processes"); procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is begin Caller.Add_Test (Suite, "Test Util.Processes.Is_Running", Test_No_Process'Access); Caller.Add_Test (Suite, "Test Util.Processes.Spawn/Wait/Get_Exit_Status", Test_Spawn'Access); Caller.Add_Test (Suite, "Test Util.Processes.Spawn(READ pipe)", Test_Output_Pipe'Access); Caller.Add_Test (Suite, "Test Util.Processes.Spawn(WRITE pipe)", Test_Input_Pipe'Access); Caller.Add_Test (Suite, "Test Util.Processes.Spawn(OUTPUT redirect)", Test_Output_Redirect'Access); Caller.Add_Test (Suite, "Test Util.Streams.Pipes.Open/Read/Close (Multi spawn)", Test_Multi_Spawn'Access); end Add_Tests; -- ------------------------------ -- Tests when the process is not launched -- ------------------------------ procedure Test_No_Process (T : in out Test) is P : Process; begin T.Assert (not P.Is_Running, "Process should not be running"); T.Assert (P.Get_Pid < 0, "Invalid process id"); end Test_No_Process; -- ------------------------------ -- Test executing a process -- ------------------------------ procedure Test_Spawn (T : in out Test) is P : Process; begin -- Launch the test process => exit code 2 P.Spawn ("bin/util_test_process"); T.Assert (P.Is_Running, "Process is running"); P.Wait; T.Assert (not P.Is_Running, "Process has stopped"); T.Assert (P.Get_Pid > 0, "Invalid process id"); Util.Tests.Assert_Equals (T, 2, P.Get_Exit_Status, "Invalid exit status"); -- Launch the test process => exit code 0 P.Spawn ("bin/util_test_process 0 write b c d e f"); T.Assert (P.Is_Running, "Process is running"); P.Wait; T.Assert (not P.Is_Running, "Process has stopped"); T.Assert (P.Get_Pid > 0, "Invalid process id"); Util.Tests.Assert_Equals (T, 0, P.Get_Exit_Status, "Invalid exit status"); end Test_Spawn; -- ------------------------------ -- Test output pipe redirection: read the process standard output -- ------------------------------ procedure Test_Output_Pipe (T : in out Test) is P : aliased Util.Streams.Pipes.Pipe_Stream; begin P.Open ("bin/util_test_process 0 write b c d e f test_marker"); declare Buffer : Util.Streams.Buffered.Buffered_Stream; Content : Ada.Strings.Unbounded.Unbounded_String; begin Buffer.Initialize (null, P'Unchecked_Access, 19); Buffer.Read (Content); P.Close; Util.Tests.Assert_Matches (T, "b\s+c\s+d\s+e\s+f\s+test_marker\s+", Content, "Invalid content"); end; T.Assert (not P.Is_Running, "Process has stopped"); Util.Tests.Assert_Equals (T, 0, P.Get_Exit_Status, "Invalid exit status"); end Test_Output_Pipe; -- ------------------------------ -- Test input pipe redirection: write the process standard input -- At the same time, read the process standard output. -- ------------------------------ procedure Test_Input_Pipe (T : in out Test) is P : aliased Util.Streams.Pipes.Pipe_Stream; begin P.Open ("bin/util_test_process 0 read -", READ_WRITE); declare Buffer : Util.Streams.Buffered.Buffered_Stream; Content : Ada.Strings.Unbounded.Unbounded_String; Print : Util.Streams.Texts.Print_Stream; begin -- Write on the process input stream. Print.Initialize (P'Unchecked_Access); Print.Write ("Write test on the input pipe"); Print.Close; -- Read the output. Buffer.Initialize (null, P'Unchecked_Access, 19); Buffer.Read (Content); -- Wait for the process to finish. P.Close; Util.Tests.Assert_Matches (T, "Write test on the input pipe-\s", Content, "Invalid content"); end; T.Assert (not P.Is_Running, "Process has stopped"); Util.Tests.Assert_Equals (T, 0, P.Get_Exit_Status, "Invalid exit status"); end Test_Input_Pipe; -- ------------------------------ -- Test launching several processes through pipes in several threads. -- ------------------------------ procedure Test_Multi_Spawn (T : in out Test) is Task_Count : constant Natural := 8; Count_By_Task : constant Natural := 10; type State_Array is array (1 .. Task_Count) of Boolean; States : State_Array; begin declare task type Worker is entry Start (Count : in Natural); entry Result (Status : out Boolean); end Worker; task body Worker is Cnt : Natural; State : Boolean := True; begin accept Start (Count : in Natural) do Cnt := Count; end Start; declare type Pipe_Array is array (1 .. Cnt) of aliased Util.Streams.Pipes.Pipe_Stream; Pipes : Pipe_Array; begin -- Launch the processes. -- They will print their arguments on stdout, one by one on each line. -- The expected exit status is the first argument. for I in 1 .. Cnt loop Pipes (I).Open ("bin/util_test_process 0 write b c d e f test_marker"); end loop; -- Read their output for I in 1 .. Cnt loop declare Buffer : Util.Streams.Buffered.Buffered_Stream; Content : Ada.Strings.Unbounded.Unbounded_String; begin Buffer.Initialize (null, Pipes (I)'Unchecked_Access, 19); Buffer.Read (Content); Pipes (I).Close; -- Check status and output. State := State and Pipes (I).Get_Exit_Status = 0; State := State and Ada.Strings.Unbounded.Index (Content, "test_marker") > 0; end; end loop; exception when E : others => Log.Error ("Exception raised", E); State := False; end; accept Result (Status : out Boolean) do Status := State; end Result; end Worker; type Worker_Array is array (1 .. Task_Count) of Worker; Tasks : Worker_Array; begin for I in Tasks'Range loop Tasks (I).Start (Count_By_Task); end loop; -- Get the results (do not raise any assertion here because we have to call -- 'Result' to ensure the thread terminates. for I in Tasks'Range loop Tasks (I).Result (States (I)); end loop; -- Leaving the Worker task scope means we are waiting for our tasks to finish. end; for I in States'Range loop T.Assert (States (I), "Task " & Natural'Image (I) & " failed"); end loop; end Test_Multi_Spawn; -- ------------------------------ -- Test output file redirection. -- ------------------------------ procedure Test_Output_Redirect (T : in out Test) is P : Process; Path : String := Util.Tests.Get_Test_Path ("proc-output.txt"); Content : Ada.Strings.Unbounded.Unbounded_String; begin Util.Processes.Set_Output_Stream (P, Path); Util.Processes.Spawn (P, "bin/util_test_process 0 write b c d e f test_marker"); Util.Processes.Wait (P); T.Assert (not P.Is_Running, "Process has stopped"); Util.Tests.Assert_Equals (T, 0, P.Get_Exit_Status, "Process failed"); Util.Files.Read_File (Path, Content); Util.Tests.Assert_Matches (T, ".*test_marker", Content, "Invalid content"); Util.Processes.Set_Output_Stream (P, Path, True); Util.Processes.Spawn (P, "bin/util_test_process 0 write appended_text"); Util.Processes.Wait (P); Content := Ada.Strings.Unbounded.Null_Unbounded_String; Util.Files.Read_File (Path, Content); Util.Tests.Assert_Matches (T, ".*appended_text", Content, "Invalid content"); Util.Tests.Assert_Matches (T, ".*test_marker.*", Content, "Invalid content"); end Test_Output_Redirect; end Util.Processes.Tests;
----------------------------------------------------------------------- -- util-processes-tests - Test for processes -- Copyright (C) 2011, 2012 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Log.Loggers; with Util.Test_Caller; with Util.Files; with Util.Streams.Pipes; with Util.Streams.Buffered; with Util.Streams.Texts; package body Util.Processes.Tests is use Util.Log; -- The logger Log : constant Loggers.Logger := Loggers.Create ("Util.Processes.Tests"); package Caller is new Util.Test_Caller (Test, "Processes"); procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is begin Caller.Add_Test (Suite, "Test Util.Processes.Is_Running", Test_No_Process'Access); Caller.Add_Test (Suite, "Test Util.Processes.Spawn/Wait/Get_Exit_Status", Test_Spawn'Access); Caller.Add_Test (Suite, "Test Util.Processes.Spawn(READ pipe)", Test_Output_Pipe'Access); Caller.Add_Test (Suite, "Test Util.Processes.Spawn(WRITE pipe)", Test_Input_Pipe'Access); Caller.Add_Test (Suite, "Test Util.Processes.Spawn(OUTPUT redirect)", Test_Output_Redirect'Access); Caller.Add_Test (Suite, "Test Util.Streams.Pipes.Open/Read/Close (Multi spawn)", Test_Multi_Spawn'Access); end Add_Tests; -- ------------------------------ -- Tests when the process is not launched -- ------------------------------ procedure Test_No_Process (T : in out Test) is P : Process; begin T.Assert (not P.Is_Running, "Process should not be running"); T.Assert (P.Get_Pid < 0, "Invalid process id"); end Test_No_Process; -- ------------------------------ -- Test executing a process -- ------------------------------ procedure Test_Spawn (T : in out Test) is P : Process; begin -- Launch the test process => exit code 2 P.Spawn ("bin/util_test_process"); T.Assert (P.Is_Running, "Process is running"); P.Wait; T.Assert (not P.Is_Running, "Process has stopped"); T.Assert (P.Get_Pid > 0, "Invalid process id"); Util.Tests.Assert_Equals (T, 2, P.Get_Exit_Status, "Invalid exit status"); -- Launch the test process => exit code 0 P.Spawn ("bin/util_test_process 0 write b c d e f"); T.Assert (P.Is_Running, "Process is running"); P.Wait; T.Assert (not P.Is_Running, "Process has stopped"); T.Assert (P.Get_Pid > 0, "Invalid process id"); Util.Tests.Assert_Equals (T, 0, P.Get_Exit_Status, "Invalid exit status"); end Test_Spawn; -- ------------------------------ -- Test output pipe redirection: read the process standard output -- ------------------------------ procedure Test_Output_Pipe (T : in out Test) is P : aliased Util.Streams.Pipes.Pipe_Stream; begin P.Open ("bin/util_test_process 0 write b c d e f test_marker"); declare Buffer : Util.Streams.Buffered.Buffered_Stream; Content : Ada.Strings.Unbounded.Unbounded_String; begin Buffer.Initialize (null, P'Unchecked_Access, 19); Buffer.Read (Content); P.Close; Util.Tests.Assert_Matches (T, "b\s+c\s+d\s+e\s+f\s+test_marker\s+", Content, "Invalid content"); end; T.Assert (not P.Is_Running, "Process has stopped"); Util.Tests.Assert_Equals (T, 0, P.Get_Exit_Status, "Invalid exit status"); end Test_Output_Pipe; -- ------------------------------ -- Test input pipe redirection: write the process standard input -- At the same time, read the process standard output. -- ------------------------------ procedure Test_Input_Pipe (T : in out Test) is P : aliased Util.Streams.Pipes.Pipe_Stream; begin P.Open ("bin/util_test_process 0 read -", READ_WRITE); declare Buffer : Util.Streams.Buffered.Buffered_Stream; Content : Ada.Strings.Unbounded.Unbounded_String; Print : Util.Streams.Texts.Print_Stream; begin -- Write on the process input stream. Print.Initialize (P'Unchecked_Access); Print.Write ("Write test on the input pipe"); Print.Close; -- Read the output. Buffer.Initialize (null, P'Unchecked_Access, 19); Buffer.Read (Content); -- Wait for the process to finish. P.Close; Util.Tests.Assert_Matches (T, "Write test on the input pipe-\s", Content, "Invalid content"); end; T.Assert (not P.Is_Running, "Process has stopped"); Util.Tests.Assert_Equals (T, 0, P.Get_Exit_Status, "Invalid exit status"); end Test_Input_Pipe; -- ------------------------------ -- Test launching several processes through pipes in several threads. -- ------------------------------ procedure Test_Multi_Spawn (T : in out Test) is Task_Count : constant Natural := 8; Count_By_Task : constant Natural := 10; type State_Array is array (1 .. Task_Count) of Boolean; States : State_Array; begin declare task type Worker is entry Start (Count : in Natural); entry Result (Status : out Boolean); end Worker; task body Worker is Cnt : Natural; State : Boolean := True; begin accept Start (Count : in Natural) do Cnt := Count; end Start; declare type Pipe_Array is array (1 .. Cnt) of aliased Util.Streams.Pipes.Pipe_Stream; Pipes : Pipe_Array; begin -- Launch the processes. -- They will print their arguments on stdout, one by one on each line. -- The expected exit status is the first argument. for I in 1 .. Cnt loop Pipes (I).Open ("bin/util_test_process 0 write b c d e f test_marker"); end loop; -- Read their output for I in 1 .. Cnt loop declare Buffer : Util.Streams.Buffered.Buffered_Stream; Content : Ada.Strings.Unbounded.Unbounded_String; begin Buffer.Initialize (null, Pipes (I)'Unchecked_Access, 19); Buffer.Read (Content); Pipes (I).Close; -- Check status and output. State := State and Pipes (I).Get_Exit_Status = 0; State := State and Ada.Strings.Unbounded.Index (Content, "test_marker") > 0; end; end loop; exception when E : others => Log.Error ("Exception raised", E); State := False; end; accept Result (Status : out Boolean) do Status := State; end Result; end Worker; type Worker_Array is array (1 .. Task_Count) of Worker; Tasks : Worker_Array; begin for I in Tasks'Range loop Tasks (I).Start (Count_By_Task); end loop; -- Get the results (do not raise any assertion here because we have to call -- 'Result' to ensure the thread terminates. for I in Tasks'Range loop Tasks (I).Result (States (I)); end loop; -- Leaving the Worker task scope means we are waiting for our tasks to finish. end; for I in States'Range loop T.Assert (States (I), "Task " & Natural'Image (I) & " failed"); end loop; end Test_Multi_Spawn; -- ------------------------------ -- Test output file redirection. -- ------------------------------ procedure Test_Output_Redirect (T : in out Test) is P : Process; Path : constant String := Util.Tests.Get_Test_Path ("proc-output.txt"); Content : Ada.Strings.Unbounded.Unbounded_String; begin Util.Processes.Set_Output_Stream (P, Path); Util.Processes.Spawn (P, "bin/util_test_process 0 write b c d e f test_marker"); Util.Processes.Wait (P); T.Assert (not P.Is_Running, "Process has stopped"); Util.Tests.Assert_Equals (T, 0, P.Get_Exit_Status, "Process failed"); Util.Files.Read_File (Path, Content); Util.Tests.Assert_Matches (T, ".*test_marker", Content, "Invalid content"); Util.Processes.Set_Output_Stream (P, Path, True); Util.Processes.Spawn (P, "bin/util_test_process 0 write appended_text"); Util.Processes.Wait (P); Content := Ada.Strings.Unbounded.Null_Unbounded_String; Util.Files.Read_File (Path, Content); Util.Tests.Assert_Matches (T, ".*appended_text", Content, "Invalid content"); Util.Tests.Assert_Matches (T, ".*test_marker.*", Content, "Invalid content"); end Test_Output_Redirect; end Util.Processes.Tests;
Fix compilation warning
Fix compilation warning
Ada
apache-2.0
flottokarotto/ada-util,Letractively/ada-util,Letractively/ada-util,flottokarotto/ada-util
f7eb38003cde269b0c36398662810ffde2b146cb
src/gen-model-xmi.ads
src/gen-model-xmi.ads
----------------------------------------------------------------------- -- gen-model-xmi -- UML-XMI model -- Copyright (C) 2012 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Containers.Hashed_Maps; with Ada.Strings.Unbounded; with Ada.Strings.Unbounded.Hash; with Ada.Containers.Vectors; with Util.Beans.Objects; with Gen.Model.Tables; package Gen.Model.XMI is use Ada.Strings.Unbounded; type Element_Type is (XMI_UNKNOWN, XMI_PACKAGE, XMI_CLASS, XMI_ASSOCIATION, XMI_ASSOCIATION_END, XMI_ATTRIBUTE, XMI_OPERATION, XMI_ENUMERATION, XMI_ENUMERATION_LITERAL, XMI_TAGGED_VALUE, XMI_TAG_DEFINITION, XMI_DATA_TYPE, XMI_STEREOTYPE, XMI_COMMENT); -- Defines the visibility of an element (a package, class, attribute, operation). type Visibility_Type is (VISIBILITY_PUBLIC, VISIBILITY_PACKAGE, VISIBILITY_PROTECTED, VISIBILITY_PRIVATE); -- Defines whether an attribute or association changes. type Changeability_Type is (CHANGEABILITY_INSERT, CHANGEABILITY_CHANGEABLE, CHANGEABILITY_FROZEN); type Model_Element; type Tagged_Value_Element; type Model_Element_Access is access all Model_Element'Class; type Tagged_Value_Element_Access is access all Tagged_Value_Element'Class; -- Define a list of model elements. package Model_Vectors is new Ada.Containers.Vectors (Index_Type => Positive, Element_Type => Model_Element_Access); subtype Model_Vector is Model_Vectors.Vector; subtype Model_Cursor is Model_Vectors.Cursor; -- Define a map to search an element from its XMI ID. package Model_Map is new Ada.Containers.Hashed_Maps (Key_Type => Unbounded_String, Element_Type => Model_Element_Access, Hash => Ada.Strings.Unbounded.Hash, Equivalent_Keys => "="); subtype Model_Map_Cursor is Model_Map.Cursor; type Model_Map_Access is access all Model_Map.Map; -- Returns true if the table cursor contains a valid table function Has_Element (Position : in Model_Map_Cursor) return Boolean renames Model_Map.Has_Element; -- Returns the table definition. function Element (Position : in Model_Map_Cursor) return Model_Element_Access renames Model_Map.Element; -- Move the iterator to the next table definition. procedure Next (Position : in out Model_Map_Cursor) renames Model_Map.Next; -- Iterate on the model element of the type <tt>On</tt> and execute the <tt>Process</tt> -- procedure. procedure Iterate (Model : in Model_Map.Map; On : in Element_Type; Process : not null access procedure (Id : in Unbounded_String; Node : in Model_Element_Access)); -- Generic procedure to iterate over the XMI elements of a vector -- and having the entity name <b>name</b>. generic type T (<>) is limited private; procedure Iterate_Elements (Closure : in out T; List : in Model_Vector; Process : not null access procedure (Closure : in out T; Node : in Model_Element_Access)); -- Map of UML models indexed on the model name. package UML_Model_Map is new Ada.Containers.Hashed_Maps (Key_Type => Unbounded_String, Element_Type => Model_Map.Map, Hash => Ada.Strings.Unbounded.Hash, Equivalent_Keys => "=", "=" => Model_Map."="); subtype UML_Model is UML_Model_Map.Map; type Search_Type is (BY_NAME, BY_ID); -- Find the model element with the given XMI id. -- Returns null if the model element is not found. function Find (Model : in Model_Map.Map; Key : in String; Mode : in Search_Type := BY_ID) return Model_Element_Access; -- Find the model element within all loaded UML models. -- Returns null if the model element is not found. function Find (Model : in UML_Model; Current : in Model_Map.Map; Id : in Ada.Strings.Unbounded.Unbounded_String) return Model_Element_Access; -- Dump the XMI model elements. procedure Dump (Map : in Model_Map.Map); -- Reconcile all the UML model elements by resolving all the references to UML elements. procedure Reconcile (Model : in out UML_Model; Debug : in Boolean := False); -- ------------------------------ -- Model Element -- ------------------------------ type Model_Element (Model : Model_Map_Access) is abstract new Definition with record -- Element XMI id. XMI_Id : Ada.Strings.Unbounded.Unbounded_String; -- List of tagged values for the element. Tagged_Values : Model_Vector; -- Elements contained. Elements : Model_Vector; -- Stereotypes associated with the element. Stereotypes : Model_Vector; -- The parent model element; Parent : Model_Element_Access; end record; -- Get the element type. function Get_Type (Node : in Model_Element) return Element_Type is abstract; -- Reconcile the element by resolving the references to other elements in the model. procedure Reconcile (Node : in out Model_Element; Model : in UML_Model); -- Find the element with the given name. If the name is a qualified name, navigate -- down the package/class to find the appropriate element. -- Returns null if the element was not found. function Find (Node : in Model_Element; Name : in String) return Model_Element_Access; -- Set the model name. procedure Set_Name (Node : in out Model_Element; Value : in Util.Beans.Objects.Object); -- Set the model XMI unique id. procedure Set_XMI_Id (Node : in out Model_Element; Value : in Util.Beans.Objects.Object); -- Find the tag value element with the given name. -- Returns null if there is no such tag. function Find_Tag_Value (Node : in Model_Element; Name : in String) return Tagged_Value_Element_Access; -- Get the documentation and comment associated with the model element. -- Returns the empty string if there is no comment. function Get_Comment (Node : in Model_Element) return String; -- Get the full qualified name for the element. function Get_Qualified_Name (Node : in Model_Element) return String; -- Find from the model file identified by <tt>Name</tt>, the model element with the -- identifier or name represented by <tt>Key</tt>. -- Returns null if the model element is not found. generic type Element_Type is new Model_Element with private; type Element_Type_Access is access all Element_Type'Class; function Find_Element (Model : in UML_Model; Name : in String; Key : in String; Mode : in Search_Type := BY_ID) return Element_Type_Access; -- ------------------------------ -- Data type -- ------------------------------ type Ref_Type_Element is new Model_Element with record Href : Unbounded_String; Ref : Model_Element_Access; end record; type Ref_Type_Element_Access is access all Ref_Type_Element'Class; -- Get the element type. overriding function Get_Type (Node : in Ref_Type_Element) return Element_Type; -- Reconcile the element by resolving the references to other elements in the model. overriding procedure Reconcile (Node : in out Ref_Type_Element; Model : in UML_Model); -- ------------------------------ -- Data type -- ------------------------------ type Data_Type_Element is new Model_Element with null record; type Data_Type_Element_Access is access all Data_Type_Element'Class; -- Get the element type. overriding function Get_Type (Node : in Data_Type_Element) return Element_Type; -- ------------------------------ -- Enum -- ------------------------------ type Enum_Element is new Data_Type_Element with null record; type Enum_Element_Access is access all Enum_Element'Class; -- Get the element type. overriding function Get_Type (Node : in Enum_Element) return Element_Type; procedure Add_Literal (Node : in out Enum_Element; Id : in Util.Beans.Objects.Object; Name : in Util.Beans.Objects.Object); -- ------------------------------ -- Literal -- ------------------------------ -- The literal describes a possible value for an enum. type Literal_Element is new Model_Element with null record; type Literal_Element_Access is access all Literal_Element'Class; -- Get the element type. overriding function Get_Type (Node : in Literal_Element) return Element_Type; -- ------------------------------ -- Stereotype -- ------------------------------ type Stereotype_Element is new Model_Element with null record; type Stereotype_Element_Access is access all Stereotype_Element'Class; -- Get the element type. overriding function Get_Type (Node : in Stereotype_Element) return Element_Type; -- Returns True if the model element has the stereotype with the given name. function Has_Stereotype (Node : in Model_Element'Class; Stereotype : in Stereotype_Element_Access) return Boolean; -- ------------------------------ -- Comment -- ------------------------------ type Comment_Element is new Model_Element with record Text : Ada.Strings.Unbounded.Unbounded_String; Ref_Id : Ada.Strings.Unbounded.Unbounded_String; end record; type Comment_Element_Access is access all Comment_Element'Class; -- Get the element type. overriding function Get_Type (Node : in Comment_Element) return Element_Type; -- ------------------------------ -- An operation -- ------------------------------ type Operation_Element is new Model_Element with record Visibility : Visibility_Type := VISIBILITY_PUBLIC; end record; type Operation_Element_Access is access all Operation_Element'Class; -- Get the element type. overriding function Get_Type (Node : in Operation_Element) return Element_Type; -- ------------------------------ -- An attribute -- ------------------------------ type Attribute_Element is new Model_Element with record Ref_Id : Ada.Strings.Unbounded.Unbounded_String; Data_Type : Data_Type_Element_Access; Visibility : Visibility_Type := VISIBILITY_PUBLIC; Changeability : Changeability_Type := CHANGEABILITY_CHANGEABLE; Initial_Value : Util.Beans.Objects.Object; Multiplicity_Lower : Integer := 0; Multiplicity_Upper : Integer := 1; end record; type Attribute_Element_Access is access all Attribute_Element'Class; -- Get the element type. overriding function Get_Type (Node : in Attribute_Element) return Element_Type; -- Reconcile the element by resolving the references to other elements in the model. overriding procedure Reconcile (Node : in out Attribute_Element; Model : in UML_Model); -- ------------------------------ -- An association end -- ------------------------------ type Association_End_Element is new Model_Element with record Visibility : Visibility_Type := VISIBILITY_PUBLIC; end record; type Association_End_Element_Access is access all Association_End_Element'Class; -- Get the element type. overriding function Get_Type (Node : in Association_End_Element) return Element_Type; -- ------------------------------ -- An association -- ------------------------------ type Association_Element is new Model_Element with record Visibility : Visibility_Type := VISIBILITY_PUBLIC; end record; type Association_Element_Access is access all Association_Element'Class; -- Get the element type. overriding function Get_Type (Node : in Association_Element) return Element_Type; -- ------------------------------ -- Tag Definition -- ------------------------------ TAG_DOCUMENTATION : constant String := "documentation"; TAG_AUTHOR : constant String := "author"; type Tag_Definition_Element is new Model_Element with record Multiplicity_Lower : Natural := 0; Multiplicity_Upper : Natural := 0; end record; type Tag_Definition_Element_Access is access all Tag_Definition_Element'Class; -- Get the element type. overriding function Get_Type (Node : in Tag_Definition_Element) return Element_Type; -- ------------------------------ -- Tagged value -- ------------------------------ type Tagged_Value_Element is new Model_Element with record Value : Ada.Strings.Unbounded.Unbounded_String; Value_Type : Ada.Strings.Unbounded.Unbounded_String; Ref_Id : Ada.Strings.Unbounded.Unbounded_String; Tag_Def : Tag_Definition_Element_Access; end record; -- Get the element type. overriding function Get_Type (Node : in Tagged_Value_Element) return Element_Type; -- Reconcile the element by resolving the references to other elements in the model. overriding procedure Reconcile (Node : in out Tagged_Value_Element; Model : in UML_Model); -- ------------------------------ -- A class -- ------------------------------ type Class_Element is new Data_Type_Element with record Operations : Model_Vector; Attributes : Model_Vector; Associations : Model_Vector; Visibility : Visibility_Type := VISIBILITY_PUBLIC; end record; type Class_Element_Access is access all Class_Element'Class; -- Get the element type. overriding function Get_Type (Node : in Class_Element) return Element_Type; -- ------------------------------ -- A package -- ------------------------------ type Package_Element; type Package_Element_Access is access all Package_Element'Class; type Package_Element is new Model_Element with record Classes : Model_Vector; end record; -- Get the element type. overriding function Get_Type (Node : in Package_Element) return Element_Type; end Gen.Model.XMI;
----------------------------------------------------------------------- -- gen-model-xmi -- UML-XMI model -- Copyright (C) 2012 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Containers.Hashed_Maps; with Ada.Strings.Unbounded; with Ada.Strings.Unbounded.Hash; with Ada.Containers.Vectors; with Util.Beans.Objects; with Gen.Model.Tables; package Gen.Model.XMI is use Ada.Strings.Unbounded; type Element_Type is (XMI_UNKNOWN, XMI_PACKAGE, XMI_CLASS, XMI_ASSOCIATION, XMI_ASSOCIATION_END, XMI_ATTRIBUTE, XMI_OPERATION, XMI_ENUMERATION, XMI_ENUMERATION_LITERAL, XMI_TAGGED_VALUE, XMI_TAG_DEFINITION, XMI_DATA_TYPE, XMI_STEREOTYPE, XMI_COMMENT); -- Defines the visibility of an element (a package, class, attribute, operation). type Visibility_Type is (VISIBILITY_PUBLIC, VISIBILITY_PACKAGE, VISIBILITY_PROTECTED, VISIBILITY_PRIVATE); -- Defines whether an attribute or association changes. type Changeability_Type is (CHANGEABILITY_INSERT, CHANGEABILITY_CHANGEABLE, CHANGEABILITY_FROZEN); type Model_Element; type Tagged_Value_Element; type Model_Element_Access is access all Model_Element'Class; type Tagged_Value_Element_Access is access all Tagged_Value_Element'Class; -- Define a list of model elements. package Model_Vectors is new Ada.Containers.Vectors (Index_Type => Positive, Element_Type => Model_Element_Access); subtype Model_Vector is Model_Vectors.Vector; subtype Model_Cursor is Model_Vectors.Cursor; -- Define a map to search an element from its XMI ID. package Model_Map is new Ada.Containers.Hashed_Maps (Key_Type => Unbounded_String, Element_Type => Model_Element_Access, Hash => Ada.Strings.Unbounded.Hash, Equivalent_Keys => "="); subtype Model_Map_Cursor is Model_Map.Cursor; type Model_Map_Access is access all Model_Map.Map; -- Returns true if the table cursor contains a valid table function Has_Element (Position : in Model_Map_Cursor) return Boolean renames Model_Map.Has_Element; -- Returns the table definition. function Element (Position : in Model_Map_Cursor) return Model_Element_Access renames Model_Map.Element; -- Move the iterator to the next table definition. procedure Next (Position : in out Model_Map_Cursor) renames Model_Map.Next; -- Iterate on the model element of the type <tt>On</tt> and execute the <tt>Process</tt> -- procedure. procedure Iterate (Model : in Model_Map.Map; On : in Element_Type; Process : not null access procedure (Id : in Unbounded_String; Node : in Model_Element_Access)); -- Generic procedure to iterate over the XMI elements of a vector -- and having the entity name <b>name</b>. generic type T (<>) is limited private; procedure Iterate_Elements (Closure : in out T; List : in Model_Vector; Process : not null access procedure (Closure : in out T; Node : in Model_Element_Access)); -- Map of UML models indexed on the model name. package UML_Model_Map is new Ada.Containers.Hashed_Maps (Key_Type => Unbounded_String, Element_Type => Model_Map.Map, Hash => Ada.Strings.Unbounded.Hash, Equivalent_Keys => "=", "=" => Model_Map."="); subtype UML_Model is UML_Model_Map.Map; type Search_Type is (BY_NAME, BY_ID); -- Find the model element with the given XMI id. -- Returns null if the model element is not found. function Find (Model : in Model_Map.Map; Key : in String; Mode : in Search_Type := BY_ID) return Model_Element_Access; -- Find the model element within all loaded UML models. -- Returns null if the model element is not found. function Find (Model : in UML_Model; Current : in Model_Map.Map; Id : in Ada.Strings.Unbounded.Unbounded_String) return Model_Element_Access; -- Dump the XMI model elements. procedure Dump (Map : in Model_Map.Map); -- Reconcile all the UML model elements by resolving all the references to UML elements. procedure Reconcile (Model : in out UML_Model; Debug : in Boolean := False); -- ------------------------------ -- Model Element -- ------------------------------ type Model_Element (Model : Model_Map_Access) is abstract new Definition with record -- Element XMI id. XMI_Id : Ada.Strings.Unbounded.Unbounded_String; -- List of tagged values for the element. Tagged_Values : Model_Vector; -- Elements contained. Elements : Model_Vector; -- Stereotypes associated with the element. Stereotypes : Model_Vector; -- The parent model element; Parent : Model_Element_Access; end record; -- Get the element type. function Get_Type (Node : in Model_Element) return Element_Type is abstract; -- Reconcile the element by resolving the references to other elements in the model. procedure Reconcile (Node : in out Model_Element; Model : in UML_Model); -- Find the element with the given name. If the name is a qualified name, navigate -- down the package/class to find the appropriate element. -- Returns null if the element was not found. function Find (Node : in Model_Element; Name : in String) return Model_Element_Access; -- Set the model name. procedure Set_Name (Node : in out Model_Element; Value : in Util.Beans.Objects.Object); -- Set the model XMI unique id. procedure Set_XMI_Id (Node : in out Model_Element; Value : in Util.Beans.Objects.Object); -- Find the tag value element with the given name. -- Returns null if there is no such tag. function Find_Tag_Value (Node : in Model_Element; Name : in String) return Tagged_Value_Element_Access; -- Get the documentation and comment associated with the model element. -- Returns the empty string if there is no comment. function Get_Comment (Node : in Model_Element) return String; -- Get the full qualified name for the element. function Get_Qualified_Name (Node : in Model_Element) return String; -- Find from the model file identified by <tt>Name</tt>, the model element with the -- identifier or name represented by <tt>Key</tt>. -- Returns null if the model element is not found. generic type Element_Type is new Model_Element with private; type Element_Type_Access is access all Element_Type'Class; function Find_Element (Model : in UML_Model; Name : in String; Key : in String; Mode : in Search_Type := BY_ID) return Element_Type_Access; -- ------------------------------ -- Data type -- ------------------------------ type Ref_Type_Element is new Model_Element with record Href : Unbounded_String; Ref : Model_Element_Access; end record; type Ref_Type_Element_Access is access all Ref_Type_Element'Class; -- Get the element type. overriding function Get_Type (Node : in Ref_Type_Element) return Element_Type; -- Reconcile the element by resolving the references to other elements in the model. overriding procedure Reconcile (Node : in out Ref_Type_Element; Model : in UML_Model); -- ------------------------------ -- Data type -- ------------------------------ type Data_Type_Element is new Model_Element with null record; type Data_Type_Element_Access is access all Data_Type_Element'Class; -- Get the element type. overriding function Get_Type (Node : in Data_Type_Element) return Element_Type; -- ------------------------------ -- Enum -- ------------------------------ type Enum_Element is new Data_Type_Element with null record; type Enum_Element_Access is access all Enum_Element'Class; -- Get the element type. overriding function Get_Type (Node : in Enum_Element) return Element_Type; procedure Add_Literal (Node : in out Enum_Element; Id : in Util.Beans.Objects.Object; Name : in Util.Beans.Objects.Object); -- ------------------------------ -- Literal -- ------------------------------ -- The literal describes a possible value for an enum. type Literal_Element is new Model_Element with null record; type Literal_Element_Access is access all Literal_Element'Class; -- Get the element type. overriding function Get_Type (Node : in Literal_Element) return Element_Type; -- ------------------------------ -- Stereotype -- ------------------------------ type Stereotype_Element is new Model_Element with null record; type Stereotype_Element_Access is access all Stereotype_Element'Class; -- Get the element type. overriding function Get_Type (Node : in Stereotype_Element) return Element_Type; -- Returns True if the model element has the stereotype with the given name. function Has_Stereotype (Node : in Model_Element'Class; Stereotype : in Stereotype_Element_Access) return Boolean; -- ------------------------------ -- Comment -- ------------------------------ type Comment_Element is new Model_Element with record Text : Ada.Strings.Unbounded.Unbounded_String; Ref_Id : Ada.Strings.Unbounded.Unbounded_String; end record; type Comment_Element_Access is access all Comment_Element'Class; -- Get the element type. overriding function Get_Type (Node : in Comment_Element) return Element_Type; -- ------------------------------ -- An operation -- ------------------------------ type Operation_Element is new Model_Element with record Visibility : Visibility_Type := VISIBILITY_PUBLIC; end record; type Operation_Element_Access is access all Operation_Element'Class; -- Get the element type. overriding function Get_Type (Node : in Operation_Element) return Element_Type; -- ------------------------------ -- An attribute -- ------------------------------ type Attribute_Element is new Model_Element with record Ref_Id : Ada.Strings.Unbounded.Unbounded_String; Data_Type : Data_Type_Element_Access; Visibility : Visibility_Type := VISIBILITY_PUBLIC; Changeability : Changeability_Type := CHANGEABILITY_CHANGEABLE; Initial_Value : Util.Beans.Objects.Object; Multiplicity_Lower : Integer := 0; Multiplicity_Upper : Integer := 1; end record; type Attribute_Element_Access is access all Attribute_Element'Class; -- Get the element type. overriding function Get_Type (Node : in Attribute_Element) return Element_Type; -- Reconcile the element by resolving the references to other elements in the model. overriding procedure Reconcile (Node : in out Attribute_Element; Model : in UML_Model); -- ------------------------------ -- An association end -- ------------------------------ type Association_End_Element is new Model_Element with record Visibility : Visibility_Type := VISIBILITY_PUBLIC; end record; type Association_End_Element_Access is access all Association_End_Element'Class; -- Get the element type. overriding function Get_Type (Node : in Association_End_Element) return Element_Type; -- ------------------------------ -- An association -- ------------------------------ type Association_Element is new Model_Element with record Visibility : Visibility_Type := VISIBILITY_PUBLIC; end record; type Association_Element_Access is access all Association_Element'Class; -- Get the element type. overriding function Get_Type (Node : in Association_Element) return Element_Type; -- ------------------------------ -- Tag Definition -- ------------------------------ TAG_DOCUMENTATION : constant String := "documentation"; TAG_AUTHOR : constant String := "author"; type Tag_Definition_Element is new Model_Element with record Multiplicity_Lower : Natural := 0; Multiplicity_Upper : Natural := 0; end record; type Tag_Definition_Element_Access is access all Tag_Definition_Element'Class; -- Get the element type. overriding function Get_Type (Node : in Tag_Definition_Element) return Element_Type; -- ------------------------------ -- Tagged value -- ------------------------------ type Tagged_Value_Element is new Model_Element with record Value : Ada.Strings.Unbounded.Unbounded_String; Value_Type : Ada.Strings.Unbounded.Unbounded_String; Ref_Id : Ada.Strings.Unbounded.Unbounded_String; Tag_Def : Tag_Definition_Element_Access; end record; -- Get the element type. overriding function Get_Type (Node : in Tagged_Value_Element) return Element_Type; -- Reconcile the element by resolving the references to other elements in the model. overriding procedure Reconcile (Node : in out Tagged_Value_Element; Model : in UML_Model); -- ------------------------------ -- A class -- ------------------------------ type Class_Element is new Data_Type_Element with record Operations : Model_Vector; Attributes : Model_Vector; Associations : Model_Vector; Visibility : Visibility_Type := VISIBILITY_PUBLIC; end record; type Class_Element_Access is access all Class_Element'Class; -- Get the element type. overriding function Get_Type (Node : in Class_Element) return Element_Type; -- ------------------------------ -- A package -- ------------------------------ type Package_Element; type Package_Element_Access is access all Package_Element'Class; type Package_Element is new Model_Element with record Classes : Model_Vector; Enums : Model_Vector; end record; -- Get the element type. overriding function Get_Type (Node : in Package_Element) return Element_Type; end Gen.Model.XMI;
Store the package enums in a separate vector
Store the package enums in a separate vector
Ada
apache-2.0
stcarrez/dynamo,stcarrez/dynamo,stcarrez/dynamo
84e735a83738698bfdc44b70d1773e38df3aaf27
src/asf-components-html-messages.adb
src/asf-components-html-messages.adb
----------------------------------------------------------------------- -- html.messages -- Faces messages -- Copyright (C) 2011, 2012 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with ASF.Utils; with ASF.Applications.Messages; with ASF.Components.Base; -- The <b>ASF.Components.Html.Messages</b> package implements the <b>h:message</b> -- and <b>h:messages</b> components. package body ASF.Components.Html.Messages is use ASF.Components.Base; use ASF.Applications.Messages; MSG_ATTRIBUTE_NAMES : Util.Strings.String_Set.Set; FATAL_ATTRIBUTE_NAMES : Util.Strings.String_Set.Set; ERROR_ATTRIBUTE_NAMES : Util.Strings.String_Set.Set; WARN_ATTRIBUTE_NAMES : Util.Strings.String_Set.Set; INFO_ATTRIBUTE_NAMES : Util.Strings.String_Set.Set; -- ------------------------------ -- Check whether the UI component whose name is given in <b>Name</b> has some messages -- associated with it. -- ------------------------------ function Has_Message (Name : in Util.Beans.Objects.Object) return Util.Beans.Objects.Object is Context : constant ASF.Contexts.Faces.Faces_Context_Access := ASF.Contexts.Faces.Current; begin if Context = null then return Util.Beans.Objects.To_Object (False); end if; declare Id : constant String := Util.Beans.Objects.To_String (Name); Msgs : constant ASF.Applications.Messages.Vectors.Cursor := Context.Get_Messages (Id); begin return Util.Beans.Objects.To_Object (Applications.Messages.Vectors.Has_Element (Msgs)); end; end Has_Message; -- ------------------------------ -- Write a single message enclosed by the tag represented by <b>Tag</b>. -- ------------------------------ procedure Write_Message (UI : in UIHtmlComponent'Class; Message : in ASF.Applications.Messages.Message; Mode : in Message_Mode; Show_Detail : in Boolean; Show_Summary : in Boolean; Context : in out Faces_Context'Class) is Writer : constant Response_Writer_Access := Context.Get_Response_Writer; begin case Mode is when SPAN_NO_STYLE => Writer.Start_Element ("span"); when SPAN => Writer.Start_Element ("span"); UI.Render_Attributes (Context, MSG_ATTRIBUTE_NAMES, Writer); when LIST => Writer.Start_Element ("li"); when TABLE => Writer.Start_Element ("tr"); end case; case Get_Severity (Message) is when FATAL => UI.Render_Attributes (Context, FATAL_ATTRIBUTE_NAMES, Writer); when ERROR => UI.Render_Attributes (Context, ERROR_ATTRIBUTE_NAMES, Writer); when WARN => UI.Render_Attributes (Context, WARN_ATTRIBUTE_NAMES, Writer); when INFO | NONE => UI.Render_Attributes (Context, INFO_ATTRIBUTE_NAMES, Writer); end case; if Mode = TABLE then Writer.Start_Element ("td"); end if; if Show_Summary then Writer.Write_Text (Get_Summary (Message)); end if; if Show_Detail then Writer.Write_Text (Get_Detail (Message)); end if; case Mode is when SPAN | SPAN_NO_STYLE => Writer.End_Element ("span"); when LIST => Writer.End_Element ("li"); when TABLE => Writer.End_Element ("td"); Writer.End_Element ("tr"); end case; end Write_Message; -- ------------------------------ -- Render a list of messages each of them being enclosed by the <b>Tag</b> element. -- ------------------------------ procedure Write_Messages (UI : in UIHtmlComponent'Class; Mode : in Message_Mode; Context : in out Faces_Context'Class; Messages : in out ASF.Applications.Messages.Vectors.Cursor) is procedure Process_Message (Message : in ASF.Applications.Messages.Message); Show_Detail : constant Boolean := UI.Get_Attribute ("showDetail", Context, True); Show_Summary : constant Boolean := UI.Get_Attribute ("showSummary", Context, False); procedure Process_Message (Message : in ASF.Applications.Messages.Message) is begin Write_Message (UI, Message, Mode, Show_Detail, Show_Summary, Context); end Process_Message; begin while ASF.Applications.Messages.Vectors.Has_Element (Messages) loop Vectors.Query_Element (Messages, Process_Message'Access); Vectors.Next (Messages); end loop; end Write_Messages; -- ------------------------------ -- Encode the begining of the <b>h:message</b> component. -- ------------------------------ procedure Encode_Begin (UI : in UIMessage; Context : in out Faces_Context'Class) is begin if not UI.Is_Rendered (Context) then return; end if; declare Name : constant Util.Beans.Objects.Object := UI.Get_Attribute (Context, "for"); Messages : ASF.Applications.Messages.Vectors.Cursor; begin -- No specification of 'for' attribute, render the global messages. if Util.Beans.Objects.Is_Null (Name) then Messages := Context.Get_Messages (""); else declare Id : constant String := Util.Beans.Objects.To_String (Name); Target : constant UIComponent_Access := UI.Find (Id => Id); begin -- If the component does not exist, report an error in the logs. if Target = null then UI.Log_Error ("Cannot find component {0}", Id); else Messages := Context.Get_Messages (Id); end if; end; end if; -- If we have some message, render the first one (as specified by <h:message>). if ASF.Applications.Messages.Vectors.Has_Element (Messages) then declare Show_Detail : constant Boolean := UI.Get_Attribute ("showDetail", Context, True); Show_Summary : constant Boolean := UI.Get_Attribute ("showSummary", Context, False); begin Write_Message (UI, ASF.Applications.Messages.Vectors.Element (Messages), SPAN, Show_Detail, Show_Summary, Context); end; end if; end; end Encode_Begin; -- Encode the end of the <b>h:message</b> component. procedure Encode_End (UI : in UIMessage; Context : in out Faces_Context'Class) is begin null; end Encode_End; -- ------------------------------ -- Encode the begining of the <b>h:message</b> component. -- ------------------------------ procedure Encode_Begin (UI : in UIMessages; Context : in out Faces_Context'Class) is begin if UI.Is_Rendered (Context) then declare Name : constant Util.Beans.Objects.Object := UI.Get_Attribute (Context, "for"); Messages : ASF.Applications.Messages.Vectors.Cursor; begin -- No specification of 'for' attribute, render the global messages. if Util.Beans.Objects.Is_Null (Name) then if UI.Get_Attribute ("globalOnly", Context) then Messages := Context.Get_Messages (""); end if; else declare Id : constant String := Util.Beans.Objects.To_String (Name); Target : constant UIComponent_Access := UI.Find (Id => Id); begin -- If the component does not exist, report an error in the logs. if Target = null then UI.Log_Error ("Cannot find component {0}", Id); else Messages := Context.Get_Messages (Id); end if; end; end if; -- If we have some message, render them. if ASF.Applications.Messages.Vectors.Has_Element (Messages) then declare Writer : constant Response_Writer_Access := Context.Get_Response_Writer; Layout : constant String := Util.Beans.Objects.To_String (UI.Get_Attribute (Context, "layout")); begin if Layout = "table" then Writer.Start_Element ("table"); UI.Render_Attributes (Context, MSG_ATTRIBUTE_NAMES, Writer); Write_Messages (UI, TABLE, Context, Messages); Writer.End_Element ("table"); else Writer.Start_Element ("ul"); UI.Render_Attributes (Context, MSG_ATTRIBUTE_NAMES, Writer); Write_Messages (UI, LIST, Context, Messages); Writer.End_Element ("ul"); end if; end; end if; end; end if; end Encode_Begin; -- Encode the end of the <b>h:message</b> component. procedure Encode_End (UI : in UIMessages; Context : in out Faces_Context'Class) is begin null; end Encode_End; FATAL_CLASS_ATTR : aliased constant String := "fatalClass"; FATAL_STYLE_CLASS_ATTR : aliased constant String := "fatalStyle"; ERROR_CLASS_ATTR : aliased constant String := "errorClass"; ERROR_STYLE_CLASS_ATTR : aliased constant String := "errorStyle"; WARN_CLASS_ATTR : aliased constant String := "warnClass"; WARN_STYLE_CLASS_ATTR : aliased constant String := "warnStyle"; INFO_CLASS_ATTR : aliased constant String := "infoClass"; INFO_STYLE_CLASS_ATTR : aliased constant String := "infoStyle"; begin ASF.Utils.Set_Text_Attributes (MSG_ATTRIBUTE_NAMES); -- ASF.Utils.Set_Text_Attributes (WARN_ATTRIBUTE_NAMES); -- ASF.Utils.Set_Text_Attributes (INFO_ATTRIBUTE_NAMES); -- -- ASF.Utils.Set_Text_Attributes (FATAL_ATTRIBUTE_NAMES); FATAL_ATTRIBUTE_NAMES.Insert (FATAL_CLASS_ATTR'Access); FATAL_ATTRIBUTE_NAMES.Insert (FATAL_STYLE_CLASS_ATTR'Access); ERROR_ATTRIBUTE_NAMES.Insert (ERROR_CLASS_ATTR'Access); ERROR_ATTRIBUTE_NAMES.Insert (ERROR_STYLE_CLASS_ATTR'Access); WARN_ATTRIBUTE_NAMES.Insert (WARN_CLASS_ATTR'Access); WARN_ATTRIBUTE_NAMES.Insert (WARN_STYLE_CLASS_ATTR'Access); INFO_ATTRIBUTE_NAMES.Insert (INFO_CLASS_ATTR'Access); INFO_ATTRIBUTE_NAMES.Insert (INFO_STYLE_CLASS_ATTR'Access); end ASF.Components.Html.Messages;
----------------------------------------------------------------------- -- html.messages -- Faces messages -- Copyright (C) 2011, 2012, 2013 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with ASF.Utils; with ASF.Applications.Messages; with ASF.Components.Base; -- The <b>ASF.Components.Html.Messages</b> package implements the <b>h:message</b> -- and <b>h:messages</b> components. package body ASF.Components.Html.Messages is use ASF.Components.Base; use ASF.Applications.Messages; MSG_ATTRIBUTE_NAMES : Util.Strings.String_Set.Set; FATAL_ATTRIBUTE_NAMES : Util.Strings.String_Set.Set; ERROR_ATTRIBUTE_NAMES : Util.Strings.String_Set.Set; WARN_ATTRIBUTE_NAMES : Util.Strings.String_Set.Set; INFO_ATTRIBUTE_NAMES : Util.Strings.String_Set.Set; -- ------------------------------ -- Check whether the UI component whose name is given in <b>Name</b> has some messages -- associated with it. -- ------------------------------ function Has_Message (Name : in Util.Beans.Objects.Object) return Util.Beans.Objects.Object is Context : constant ASF.Contexts.Faces.Faces_Context_Access := ASF.Contexts.Faces.Current; begin if Context = null then return Util.Beans.Objects.To_Object (False); end if; declare Id : constant String := Util.Beans.Objects.To_String (Name); Msgs : constant ASF.Applications.Messages.Vectors.Cursor := Context.Get_Messages (Id); begin return Util.Beans.Objects.To_Object (Applications.Messages.Vectors.Has_Element (Msgs)); end; end Has_Message; -- ------------------------------ -- Write a single message enclosed by the tag represented by <b>Tag</b>. -- ------------------------------ procedure Write_Message (UI : in UIHtmlComponent'Class; Message : in ASF.Applications.Messages.Message; Mode : in Message_Mode; Show_Detail : in Boolean; Show_Summary : in Boolean; Context : in out Faces_Context'Class) is Writer : constant Response_Writer_Access := Context.Get_Response_Writer; begin case Mode is when SPAN_NO_STYLE => Writer.Start_Element ("span"); when SPAN => Writer.Start_Element ("span"); UI.Render_Attributes (Context, MSG_ATTRIBUTE_NAMES, Writer); when LIST => Writer.Start_Element ("li"); when TABLE => Writer.Start_Element ("tr"); end case; case Get_Severity (Message) is when FATAL => UI.Render_Attributes (Context, FATAL_ATTRIBUTE_NAMES, Writer, Write_Id => Mode /= SPAN_NO_STYLE); when ERROR => UI.Render_Attributes (Context, ERROR_ATTRIBUTE_NAMES, Writer, Write_Id => Mode /= SPAN_NO_STYLE); when WARN => UI.Render_Attributes (Context, WARN_ATTRIBUTE_NAMES, Writer, Write_Id => Mode /= SPAN_NO_STYLE); when INFO | NONE => UI.Render_Attributes (Context, INFO_ATTRIBUTE_NAMES, Writer, Write_Id => Mode /= SPAN_NO_STYLE); end case; if Mode = TABLE then Writer.Start_Element ("td"); end if; if Show_Summary then Writer.Write_Text (Get_Summary (Message)); end if; if Show_Detail then Writer.Write_Text (Get_Detail (Message)); end if; case Mode is when SPAN | SPAN_NO_STYLE => Writer.End_Element ("span"); when LIST => Writer.End_Element ("li"); when TABLE => Writer.End_Element ("td"); Writer.End_Element ("tr"); end case; end Write_Message; -- ------------------------------ -- Render a list of messages each of them being enclosed by the <b>Tag</b> element. -- ------------------------------ procedure Write_Messages (UI : in UIHtmlComponent'Class; Mode : in Message_Mode; Context : in out Faces_Context'Class; Messages : in out ASF.Applications.Messages.Vectors.Cursor) is procedure Process_Message (Message : in ASF.Applications.Messages.Message); Show_Detail : constant Boolean := UI.Get_Attribute ("showDetail", Context, True); Show_Summary : constant Boolean := UI.Get_Attribute ("showSummary", Context, False); procedure Process_Message (Message : in ASF.Applications.Messages.Message) is begin Write_Message (UI, Message, Mode, Show_Detail, Show_Summary, Context); end Process_Message; begin while ASF.Applications.Messages.Vectors.Has_Element (Messages) loop Vectors.Query_Element (Messages, Process_Message'Access); Vectors.Next (Messages); end loop; end Write_Messages; -- ------------------------------ -- Encode the begining of the <b>h:message</b> component. -- ------------------------------ procedure Encode_Begin (UI : in UIMessage; Context : in out Faces_Context'Class) is begin if not UI.Is_Rendered (Context) then return; end if; declare Name : constant Util.Beans.Objects.Object := UI.Get_Attribute (Context, "for"); Messages : ASF.Applications.Messages.Vectors.Cursor; begin -- No specification of 'for' attribute, render the global messages. if Util.Beans.Objects.Is_Null (Name) then Messages := Context.Get_Messages (""); else declare Id : constant String := Util.Beans.Objects.To_String (Name); Target : constant UIComponent_Access := UI.Find (Id => Id); begin -- If the component does not exist, report an error in the logs. if Target = null then UI.Log_Error ("Cannot find component {0}", Id); else Messages := Context.Get_Messages (Id); end if; end; end if; -- If we have some message, render the first one (as specified by <h:message>). if ASF.Applications.Messages.Vectors.Has_Element (Messages) then declare Show_Detail : constant Boolean := UI.Get_Attribute ("showDetail", Context, True); Show_Summary : constant Boolean := UI.Get_Attribute ("showSummary", Context, False); begin Write_Message (UI, ASF.Applications.Messages.Vectors.Element (Messages), SPAN, Show_Detail, Show_Summary, Context); end; end if; end; end Encode_Begin; -- Encode the end of the <b>h:message</b> component. procedure Encode_End (UI : in UIMessage; Context : in out Faces_Context'Class) is begin null; end Encode_End; -- ------------------------------ -- Encode the begining of the <b>h:message</b> component. -- ------------------------------ procedure Encode_Begin (UI : in UIMessages; Context : in out Faces_Context'Class) is begin if UI.Is_Rendered (Context) then declare Name : constant Util.Beans.Objects.Object := UI.Get_Attribute (Context, "for"); Messages : ASF.Applications.Messages.Vectors.Cursor; begin -- No specification of 'for' attribute, render the global messages. if Util.Beans.Objects.Is_Null (Name) then if UI.Get_Attribute ("globalOnly", Context) then Messages := Context.Get_Messages (""); end if; else declare Id : constant String := Util.Beans.Objects.To_String (Name); Target : constant UIComponent_Access := UI.Find (Id => Id); begin -- If the component does not exist, report an error in the logs. if Target = null then UI.Log_Error ("Cannot find component {0}", Id); else Messages := Context.Get_Messages (Id); end if; end; end if; -- If we have some message, render them. if ASF.Applications.Messages.Vectors.Has_Element (Messages) then declare Writer : constant Response_Writer_Access := Context.Get_Response_Writer; Layout : constant String := Util.Beans.Objects.To_String (UI.Get_Attribute (Context, "layout")); begin if Layout = "table" then Writer.Start_Element ("table"); UI.Render_Attributes (Context, MSG_ATTRIBUTE_NAMES, Writer); Write_Messages (UI, TABLE, Context, Messages); Writer.End_Element ("table"); else Writer.Start_Element ("ul"); UI.Render_Attributes (Context, MSG_ATTRIBUTE_NAMES, Writer); Write_Messages (UI, LIST, Context, Messages); Writer.End_Element ("ul"); end if; end; end if; end; end if; end Encode_Begin; -- Encode the end of the <b>h:message</b> component. procedure Encode_End (UI : in UIMessages; Context : in out Faces_Context'Class) is begin null; end Encode_End; FATAL_CLASS_ATTR : aliased constant String := "fatalClass"; FATAL_STYLE_CLASS_ATTR : aliased constant String := "fatalStyle"; ERROR_CLASS_ATTR : aliased constant String := "errorClass"; ERROR_STYLE_CLASS_ATTR : aliased constant String := "errorStyle"; WARN_CLASS_ATTR : aliased constant String := "warnClass"; WARN_STYLE_CLASS_ATTR : aliased constant String := "warnStyle"; INFO_CLASS_ATTR : aliased constant String := "infoClass"; INFO_STYLE_CLASS_ATTR : aliased constant String := "infoStyle"; begin ASF.Utils.Set_Text_Attributes (MSG_ATTRIBUTE_NAMES); -- ASF.Utils.Set_Text_Attributes (WARN_ATTRIBUTE_NAMES); -- ASF.Utils.Set_Text_Attributes (INFO_ATTRIBUTE_NAMES); -- -- ASF.Utils.Set_Text_Attributes (FATAL_ATTRIBUTE_NAMES); FATAL_ATTRIBUTE_NAMES.Insert (FATAL_CLASS_ATTR'Access); FATAL_ATTRIBUTE_NAMES.Insert (FATAL_STYLE_CLASS_ATTR'Access); ERROR_ATTRIBUTE_NAMES.Insert (ERROR_CLASS_ATTR'Access); ERROR_ATTRIBUTE_NAMES.Insert (ERROR_STYLE_CLASS_ATTR'Access); WARN_ATTRIBUTE_NAMES.Insert (WARN_CLASS_ATTR'Access); WARN_ATTRIBUTE_NAMES.Insert (WARN_STYLE_CLASS_ATTR'Access); INFO_ATTRIBUTE_NAMES.Insert (INFO_CLASS_ATTR'Access); INFO_ATTRIBUTE_NAMES.Insert (INFO_STYLE_CLASS_ATTR'Access); end ASF.Components.Html.Messages;
Disable the rendering of the component id for the SPAN_NO_STYLE mode
Disable the rendering of the component id for the SPAN_NO_STYLE mode
Ada
apache-2.0
stcarrez/ada-asf,stcarrez/ada-asf,stcarrez/ada-asf
ec1e352446e25fd743150d234c16f293bae60098
src/asf-components-utils-escapes.adb
src/asf-components-utils-escapes.adb
----------------------------------------------------------------------- -- components-utils-escape -- Escape generated content produced by component children -- Copyright (C) 2011, 2012, 2014 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Strings.Transforms; package body ASF.Components.Utils.Escapes is -- ------------------------------ -- Write the content that was collected by rendering the inner children. -- Escape the content using Javascript escape rules. -- ------------------------------ procedure Write_Content (UI : in UIEscape; Writer : in out Contexts.Writer.Response_Writer'Class; Content : in String; Context : in out ASF.Contexts.Faces.Faces_Context'Class) is pragma Unreferenced (UI, Context); Result : Ada.Strings.Unbounded.Unbounded_String; Mode : constant String := UI.Get_Attribute (ESCAPE_MODE_NAME, Context); begin if Mode = "xml" then Util.Strings.Transforms.Escape_Xml (Content => Content, Into => Result); else Util.Strings.Transforms.Escape_Java (Content => Content, Into => Result); end if; Writer.Write (Result); end Write_Content; -- ------------------------------ -- Encode the children components in the javascript queue. -- ------------------------------ overriding procedure Encode_Children (UI : in UIEscape; Context : in out ASF.Contexts.Faces.Faces_Context'Class) is procedure Process (Content : in String); procedure Process (Content : in String) is Writer : constant Contexts.Writer.Response_Writer_Access := Context.Get_Response_Writer; begin UIEscape'Class (UI).Write_Content (Writer.all, Content, Context); end Process; begin UI.Wrap_Encode_Children (Context, Process'Access); end Encode_Children; end ASF.Components.Utils.Escapes;
----------------------------------------------------------------------- -- components-utils-escape -- Escape generated content produced by component children -- Copyright (C) 2011, 2012, 2014 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Strings.Transforms; package body ASF.Components.Utils.Escapes is -- ------------------------------ -- Write the content that was collected by rendering the inner children. -- Escape the content using Javascript escape rules. -- ------------------------------ procedure Write_Content (UI : in UIEscape; Writer : in out Contexts.Writer.Response_Writer'Class; Content : in String; Context : in out ASF.Contexts.Faces.Faces_Context'Class) is Result : Ada.Strings.Unbounded.Unbounded_String; Mode : constant String := UI.Get_Attribute (ESCAPE_MODE_NAME, Context); begin if Mode = "xml" then Util.Strings.Transforms.Escape_Xml (Content => Content, Into => Result); else Util.Strings.Transforms.Escape_Java (Content => Content, Into => Result); end if; Writer.Write (Result); end Write_Content; -- ------------------------------ -- Encode the children components in the javascript queue. -- ------------------------------ overriding procedure Encode_Children (UI : in UIEscape; Context : in out ASF.Contexts.Faces.Faces_Context'Class) is procedure Process (Content : in String); procedure Process (Content : in String) is Writer : constant Contexts.Writer.Response_Writer_Access := Context.Get_Response_Writer; begin UIEscape'Class (UI).Write_Content (Writer.all, Content, Context); end Process; begin UI.Wrap_Encode_Children (Context, Process'Access); end Encode_Children; end ASF.Components.Utils.Escapes;
Fix compilation warning
Fix compilation warning
Ada
apache-2.0
Letractively/ada-asf,Letractively/ada-asf,Letractively/ada-asf
5da049fa40b4277f195f90ddda7816a1d2c5651c
src/util-dates-iso8601.adb
src/util-dates-iso8601.adb
----------------------------------------------------------------------- -- util-dates-iso8601 -- ISO8601 dates -- Copyright (C) 2011, 2013, 2015 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- package body Util.Dates.ISO8601 is -- ------------------------------ -- Parses an ISO8601 date and return it as a calendar time. -- Raises Constraint_Error if the date format is not recognized. -- ------------------------------ function Value (Date : in String) return Ada.Calendar.Time is use Ada.Calendar; Result : Date_Record; begin if Date'Length < 4 then raise Constraint_Error with "Invalid date"; end if; Result.Year := Year_Number'Value (Date (Date'First .. Date'First + 3)); if Date'Length = 4 then -- ISO8601 date: YYYY Result.Month := 1; Result.Month_Day := 1; elsif Date'Length = 7 and Date (Date'First + 4) = '-' then -- ISO8601 date: YYYY-MM Result.Month := Month_Number'Value (Date (Date'First + 4 .. Date'Last)); Result.Month_Day := 1; elsif Date'Length = 8 then -- ISO8601 date: YYYYMMDD Result.Month := Month_Number'Value (Date (Date'First + 4 .. Date'First + 5)); Result.Month_Day := Day_Number'Value (Date (Date'First + 6 .. Date'First + 7)); elsif Date'Length >= 9 and then Date (Date'First + 4) = '-' and then Date (Date'First + 7) = '-' then -- ISO8601 date: YYYY-MM-DD Result.Month := Month_Number'Value (Date (Date'First + 5 .. Date'First + 6)); Result.Month_Day := Day_Number'Value (Date (Date'First + 8 .. Date'First + 9)); else raise Constraint_Error with "invalid date"; end if; return Ada.Calendar.Formatting.Time_Of (Year => Result.Year, Month => Result.Month, Day => Result.Month_Day, Hour => 0, Minute => 0, Second => 0, Sub_Second => 0.0); end Value; -- ------------------------------ -- Return the ISO8601 date. -- ------------------------------ function Image (Date : in Ada.Calendar.Time) return String is D : Date_Record; begin Split (D, Date); return Image (D); end Image; function Image (Date : in Date_Record) return String is To_Char : constant array (0 .. 9) of Character := "0123456789"; Result : String (1 .. 10) := "0000-00-00"; begin Result (1) := To_Char (Date.Year / 1000); Result (2) := To_Char (Date.Year / 100 mod 10); Result (3) := To_Char (Date.Year / 10 mod 10); Result (4) := To_Char (Date.Year mod 10); Result (6) := To_Char (Date.Month / 10); Result (7) := To_Char (Date.Month mod 10); Result (9) := To_Char (Date.Month_Day / 10); Result (10) := To_Char (Date.Month_Day mod 10); return Result; end Image; end Util.Dates.ISO8601;
----------------------------------------------------------------------- -- util-dates-iso8601 -- ISO8601 dates -- Copyright (C) 2011, 2013, 2015, 2016 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- package body Util.Dates.ISO8601 is -- ------------------------------ -- Parses an ISO8601 date and return it as a calendar time. -- Raises Constraint_Error if the date format is not recognized. -- ------------------------------ function Value (Date : in String) return Ada.Calendar.Time is use Ada.Calendar; use Ada.Calendar.Formatting; Result : Date_Record; Pos : Natural; begin if Date'Length < 4 then raise Constraint_Error with "Invalid date"; end if; Result.Hour := 0; Result.Minute := 0; Result.Second := 0; Result.Sub_Second := 0.0; Result.Time_Zone := 0; Result.Year := Year_Number'Value (Date (Date'First .. Date'First + 3)); if Date'Length = 4 then -- ISO8601 date: YYYY Result.Month := 1; Result.Month_Day := 1; elsif Date'Length = 7 and Date (Date'First + 4) = '-' then -- ISO8601 date: YYYY-MM Result.Month := Month_Number'Value (Date (Date'First + 4 .. Date'Last)); Result.Month_Day := 1; elsif Date'Length = 8 then -- ISO8601 date: YYYYMMDD Result.Month := Month_Number'Value (Date (Date'First + 4 .. Date'First + 5)); Result.Month_Day := Day_Number'Value (Date (Date'First + 6 .. Date'First + 7)); elsif Date'Length >= 9 and then Date (Date'First + 4) = '-' and then Date (Date'First + 7) = '-' then -- ISO8601 date: YYYY-MM-DD Result.Month := Month_Number'Value (Date (Date'First + 5 .. Date'First + 6)); Result.Month_Day := Day_Number'Value (Date (Date'First + 8 .. Date'First + 9)); -- ISO8601 date: YYYY-MM-DDTHH if Date'Length > 12 then if Date (Date'First + 10) /= 'T' then raise Constraint_Error with "invalid date"; end if; Result.Hour := Hour_Number'Value (Date (Date'First + 11 .. Date'First + 12)); Pos := Date'First + 13; end if; if Date'Length > 15 then if Date (Date'First + 13) /= ':' then raise Constraint_Error with "invalid date"; end if; Result.Minute := Minute_Number'Value (Date (Date'First + 14 .. Date'First + 15)); Pos := Date'First + 16; end if; if Date'Length > 18 then if Date (Date'First + 16) /= ':' then raise Constraint_Error with "invalid date"; end if; Result.Second := Second_Number'Value (Date (Date'First + 17 .. Date'First + 18)); Pos := Date'First + 19; end if; -- ISO8601 timezone: +hh:mm or -hh:mm -- if Date'Length > Pos + 4 then -- if Date (Pos) /= '+' and Date (Pos) /= '-' and Date (Pos + 2) /= ':' then -- raise Constraint_Error with "invalid date"; -- end if; -- end if; else raise Constraint_Error with "invalid date"; end if; return Ada.Calendar.Formatting.Time_Of (Year => Result.Year, Month => Result.Month, Day => Result.Month_Day, Hour => Result.Hour, Minute => Result.Minute, Second => Result.Second, Sub_Second => Result.Sub_Second, Time_Zone => Result.Time_Zone); end Value; -- ------------------------------ -- Return the ISO8601 date. -- ------------------------------ function Image (Date : in Ada.Calendar.Time) return String is D : Date_Record; begin Split (D, Date); return Image (D); end Image; function Image (Date : in Date_Record) return String is To_Char : constant array (0 .. 9) of Character := "0123456789"; Result : String (1 .. 10) := "0000-00-00"; begin Result (1) := To_Char (Date.Year / 1000); Result (2) := To_Char (Date.Year / 100 mod 10); Result (3) := To_Char (Date.Year / 10 mod 10); Result (4) := To_Char (Date.Year mod 10); Result (6) := To_Char (Date.Month / 10); Result (7) := To_Char (Date.Month mod 10); Result (9) := To_Char (Date.Month_Day / 10); Result (10) := To_Char (Date.Month_Day mod 10); return Result; end Image; function Image (Date : in Ada.Calendar.Time; Precision : in Precision_Type) return String is D : Date_Record; begin Split (D, Date); return Image (D, Precision); end Image; function Image (Date : in Date_Record; Precision : in Precision_Type) return String is use type Ada.Calendar.Time_Zones.Time_Offset; To_Char : constant array (0 .. 9) of Character := "0123456789"; Result : String (1 .. 29) := "0000-00-00T00:00:00.000-00:00"; N, Tz : Natural; begin Result (1) := To_Char (Date.Year / 1000); Result (2) := To_Char (Date.Year / 100 mod 10); Result (3) := To_Char (Date.Year / 10 mod 10); Result (4) := To_Char (Date.Year mod 10); if Precision = YEAR then return Result (1 .. 4); end if; Result (6) := To_Char (Date.Month / 10); Result (7) := To_Char (Date.Month mod 10); if Precision = MONTH then return Result (1 .. 7); end if; Result (9) := To_Char (Date.Month_Day / 10); Result (10) := To_Char (Date.Month_Day mod 10); if Precision = DAY then return Result (1 .. 10); end if; Result (12) := To_Char (Date.Hour / 10); Result (13) := To_Char (Date.Hour mod 10); if Precision = HOUR then return Result (1 .. 13); end if; Result (15) := To_Char (Date.Minute / 10); Result (16) := To_Char (Date.Minute mod 10); if Precision = MINUTE then return Result (1 .. 16); end if; Result (18) := To_Char (Date.Second / 10); Result (19) := To_Char (Date.Second mod 10); if Precision = SECOND then return Result (1 .. 19); end if; N := Natural (Date.Sub_Second * 1000.0); Result (21) := To_Char (N / 100); Result (22) := To_Char ((N mod 100) / 10); Result (23) := To_Char (N mod 10); if Date.Time_Zone < 0 then Tz := Natural (-Date.Time_Zone); else Result (24) := '+'; Tz := Natural (Date.Time_Zone); end if; Result (25) := To_Char (Tz / 600); Result (26) := To_Char ((Tz / 60) mod 10); Tz := Tz mod 60; Result (28) := To_Char (Tz / 10); Result (29) := To_Char (Tz mod 10); return Result; end Image; end Util.Dates.ISO8601;
Implement new Image operation with several precision format for the date
Implement new Image operation with several precision format for the date
Ada
apache-2.0
stcarrez/ada-util,stcarrez/ada-util
190f7c8aed766702e881ac2bcf2fe73f70fe2e14
regtests/security-random-tests.adb
regtests/security-random-tests.adb
----------------------------------------------------------------------- -- security-random-tests - Tests for random package -- Copyright (C) 2017, 2018 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Strings.Unbounded; with Util.Test_Caller; package body Security.Random.Tests is package Caller is new Util.Test_Caller (Test, "Security.Random"); procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is begin Caller.Add_Test (Suite, "Test Security.Random.Generate", Test_Generate'Access); end Add_Tests; -- ------------------------------ -- Test Yadis discovery using static files -- ------------------------------ procedure Test_Generate (T : in out Test) is use Ada.Strings.Unbounded; G : Generator; Max : constant Ada.Streams.Stream_Element_Offset := 10; begin for I in 1 .. Max loop declare use type Ada.Streams.Stream_Element; S : Ada.Streams.Stream_Element_Array (1 .. I) := (others => 0); Rand : Ada.Strings.Unbounded.Unbounded_String; begin -- Try 5 times to fill the array with random patterns and make sure -- we don't get any 0. for Retry in 1 .. 5 loop G.Generate (S); exit when (for all R of S => R /= 0); end loop; T.Assert ((for all R of S => R /= 0), "Generator failed to initialize all bytes"); G.Generate (Positive (I), Rand); T.Assert (Length (Rand) > 0, "Generator failed to produce a base64url sequence"); end; end loop; end Test_Generate; end Security.Random.Tests;
----------------------------------------------------------------------- -- security-random-tests - Tests for random package -- Copyright (C) 2017, 2018, 2022 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Strings.Unbounded; with Util.Test_Caller; package body Security.Random.Tests is package Caller is new Util.Test_Caller (Test, "Security.Random"); procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is begin Caller.Add_Test (Suite, "Test Security.Random.Generate", Test_Generate'Access); Caller.Add_Test (Suite, "Test Security.Random.Generate_String", Test_Generate_String'Access); end Add_Tests; -- ------------------------------ -- Test Yadis discovery using static files -- ------------------------------ procedure Test_Generate (T : in out Test) is use Ada.Strings.Unbounded; G : Generator; Max : constant Ada.Streams.Stream_Element_Offset := 10; begin for I in 1 .. Max loop declare use type Ada.Streams.Stream_Element; S : Ada.Streams.Stream_Element_Array (1 .. I) := (others => 0); Rand : Ada.Strings.Unbounded.Unbounded_String; begin -- Try 5 times to fill the array with random patterns and make sure -- we don't get any 0. for Retry in 1 .. 5 loop G.Generate (S); exit when (for all R of S => R /= 0); end loop; T.Assert ((for all R of S => R /= 0), "Generator failed to initialize all bytes"); G.Generate (Positive (I), Rand); T.Assert (Length (Rand) > 0, "Generator failed to produce a base64url sequence"); end; end loop; end Test_Generate; procedure Test_Generate_String (T : in out Test) is G : Generator; begin declare S1 : constant String := G.Generate (Bits => 256); S2 : constant String := G.Generate (Bits => 256); begin Util.Tests.Assert_Equals (T, 43, Natural (S1'Length), "Generated string 1 is too small"); Util.Tests.Assert_Equals (T, 43, Natural (S2'Length), "Generated string 2 is too small"); T.Assert (S1 /= S2, "Generated string are equal"); end; end Test_Generate_String; end Security.Random.Tests;
Add Test_Generate_String to check the length of random string
Add Test_Generate_String to check the length of random string
Ada
apache-2.0
stcarrez/ada-security
494f624a0f28cd46dc324e57afda79ebd1750c9e
regtests/util-http-clients-tests.adb
regtests/util-http-clients-tests.adb
----------------------------------------------------------------------- -- util-http-clients-tests -- Unit tests for HTTP client -- Copyright (C) 2012 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Unchecked_Deallocation; with Util.Test_Caller; with Util.Strings.Transforms; with Util.Http.Tools; with Util.Strings; with Util.Log.Loggers; package body Util.Http.Clients.Tests is -- The logger Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("Util.Http.Clients.Tests"); package body Http_Tests is package Caller is new Util.Test_Caller (Http_Test, "Http-" & NAME); procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is begin Caller.Add_Test (Suite, "Test Util.Http.Clients." & NAME & ".Get", Test_Http_Get'Access); Caller.Add_Test (Suite, "Test Util.Http.Clients." & NAME & ".Post", Test_Http_Post'Access); end Add_Tests; overriding procedure Set_Up (T : in out Http_Test) is begin Test (T).Set_Up; Register; end Set_Up; end Http_Tests; overriding procedure Set_Up (T : in out Test) is begin Log.Info ("Starting test server"); T.Server := new Test_Server; T.Server.Start; end Set_Up; overriding procedure Tear_Down (T : in out Test) is procedure Free is new Ada.Unchecked_Deallocation (Object => Test_Server'Class, Name => Test_Server_Access); begin if T.Server /= null then Log.Info ("Stopping test server"); T.Server.Stop; Free (T.Server); T.Server := null; end if; end Tear_Down; -- ------------------------------ -- Process the line received by the server. -- ------------------------------ overriding procedure Process_Line (Into : in out Test_Server; Line : in Ada.Strings.Unbounded.Unbounded_String; Stream : in out Util.Streams.Texts.Reader_Stream'Class; Client : in out Util.Streams.Sockets.Socket_Stream'Class) is L : constant String := Ada.Strings.Unbounded.To_String (Line); Pos : Natural := Util.Strings.Index (L, ' '); begin if Pos > 0 and Into.Method = UNKNOWN then if L (L'First .. Pos - 1) = "GET" then Into.Method := GET; elsif L (L'First .. Pos - 1) = "POST" then Into.Method := POST; else Into.Method := UNKNOWN; end if; end if; Pos := Util.Strings.Index (L, ':'); if Pos > 0 then if L (L'First .. Pos) = "Content-Type:" then Into.Content_Type := Ada.Strings.Unbounded.To_Unbounded_String (L (Pos + 2 .. L'Last - 2)); elsif L (L'First .. Pos) = "Content-Length:" then Into.Length := Natural'Value (L (Pos + 1 .. L'Last - 2)); end if; end if; if L'Length = 2 and then Into.Length > 0 then for I in 1 .. Into.Length loop declare C : Character; begin Stream.Read (C); Ada.Strings.Unbounded.Append (Into.Result, C); end; end loop; declare Output : Util.Streams.Texts.Print_Stream; begin Output.Initialize (Client'Unchecked_Access); Output.Write ("HTTP/1.1 200 Found" & ASCII.CR & ASCII.LF); Output.Write ("Content-Length: 4" & ASCII.CR & ASCII.LF); Output.Write (ASCII.CR & ASCII.LF); Output.Write ("OK" & ASCII.CR & ASCII.LF); Output.Flush; end; end if; Log.Info ("Received: {0}", L); end Process_Line; -- ------------------------------ -- Get the test server base URI. -- ------------------------------ function Get_Uri (T : in Test) return String is begin return "http://" & T.Server.Get_Host & ":" & Util.Strings.Image (T.Server.Get_Port); end Get_Uri; -- ------------------------------ -- Test the http Get operation. -- ------------------------------ procedure Test_Http_Get (T : in out Test) is Request : Client; Reply : Response; begin Request.Get ("http://www.google.com", Reply); T.Assert (Reply.Get_Status = 200 or Reply.Get_Status = 302, "Get status is invalid"); Util.Http.Tools.Save_Response (Util.Tests.Get_Test_Path ("http_get.txt"), Reply, True); -- Check the content. declare Content : constant String := Util.Strings.Transforms.To_Lower_Case (Reply.Get_Body); begin Util.Tests.Assert_Matches (T, ".*html.*", Content, "Invalid GET content"); end; -- Check one header. declare Content : constant String := Reply.Get_Header ("Content-Type"); begin T.Assert (Content'Length > 0, "Empty Content-Type header"); Util.Tests.Assert_Matches (T, ".*text/html.*", Content, "Invalid content type"); end; end Test_Http_Get; -- ------------------------------ -- Test the http POST operation. -- ------------------------------ procedure Test_Http_Post (T : in out Test) is Request : Client; Reply : Response; Uri : constant String := T.Get_Uri; begin Log.Info ("Post on " & Uri); T.Server.Method := UNKNOWN; Request.Post (Uri & "/post", "p1=1", Reply); T.Assert (T.Server.Method = POST, "Invalid method received by server"); Util.Tests.Assert_Equals (T, "application/x-www-form-urlencoded", T.Server.Content_Type, "Invalid content type received by server"); Util.Tests.Assert_Equals (T, "OK" & ASCII.CR & ASCII.LF, Reply.Get_Body, "Invalid response"); Util.Http.Tools.Save_Response (Util.Tests.Get_Test_Path ("http_post.txt"), Reply, True); end Test_Http_Post; end Util.Http.Clients.Tests;
----------------------------------------------------------------------- -- util-http-clients-tests -- Unit tests for HTTP client -- Copyright (C) 2012 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Unchecked_Deallocation; with Util.Test_Caller; with Util.Strings.Transforms; with Util.Http.Tools; with Util.Strings; with Util.Log.Loggers; package body Util.Http.Clients.Tests is -- The logger Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("Util.Http.Clients.Tests"); package body Http_Tests is package Caller is new Util.Test_Caller (Http_Test, "Http-" & NAME); procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is begin Caller.Add_Test (Suite, "Test Util.Http.Clients." & NAME & ".Get", Test_Http_Get'Access); Caller.Add_Test (Suite, "Test Util.Http.Clients." & NAME & ".Post", Test_Http_Post'Access); end Add_Tests; overriding procedure Set_Up (T : in out Http_Test) is begin Test (T).Set_Up; Register; end Set_Up; end Http_Tests; overriding procedure Set_Up (T : in out Test) is begin Log.Info ("Starting test server"); T.Server := new Test_Server; T.Server.Start; end Set_Up; overriding procedure Tear_Down (T : in out Test) is procedure Free is new Ada.Unchecked_Deallocation (Object => Test_Server'Class, Name => Test_Server_Access); begin if T.Server /= null then Log.Info ("Stopping test server"); T.Server.Stop; Free (T.Server); T.Server := null; end if; end Tear_Down; -- ------------------------------ -- Process the line received by the server. -- ------------------------------ overriding procedure Process_Line (Into : in out Test_Server; Line : in Ada.Strings.Unbounded.Unbounded_String; Stream : in out Util.Streams.Texts.Reader_Stream'Class; Client : in out Util.Streams.Sockets.Socket_Stream'Class) is L : constant String := Ada.Strings.Unbounded.To_String (Line); Pos : Natural := Util.Strings.Index (L, ' '); begin if Pos > 0 and Into.Method = UNKNOWN then if L (L'First .. Pos - 1) = "GET" then Into.Method := GET; elsif L (L'First .. Pos - 1) = "POST" then Into.Method := POST; else Into.Method := UNKNOWN; end if; end if; Pos := Util.Strings.Index (L, ':'); if Pos > 0 then if L (L'First .. Pos) = "Content-Type:" then Into.Content_Type := Ada.Strings.Unbounded.To_Unbounded_String (L (Pos + 2 .. L'Last - 2)); elsif L (L'First .. Pos) = "Content-Length:" then Into.Length := Natural'Value (L (Pos + 1 .. L'Last - 2)); end if; end if; if L'Length = 2 and then Into.Length > 0 then for I in 1 .. Into.Length loop declare C : Character; begin Stream.Read (C); Ada.Strings.Unbounded.Append (Into.Result, C); end; end loop; declare Output : Util.Streams.Texts.Print_Stream; begin Output.Initialize (Client'Unchecked_Access); Output.Write ("HTTP/1.1 200 Found" & ASCII.CR & ASCII.LF); Output.Write ("Content-Length: 4" & ASCII.CR & ASCII.LF); Output.Write (ASCII.CR & ASCII.LF); Output.Write ("OK" & ASCII.CR & ASCII.LF); Output.Flush; end; end if; Log.Info ("Received: {0}", L); end Process_Line; -- ------------------------------ -- Get the test server base URI. -- ------------------------------ function Get_Uri (T : in Test) return String is begin return "http://" & T.Server.Get_Host & ":" & Util.Strings.Image (T.Server.Get_Port); end Get_Uri; -- ------------------------------ -- Test the http Get operation. -- ------------------------------ procedure Test_Http_Get (T : in out Test) is Request : Client; Reply : Response; begin Request.Get ("http://www.google.com", Reply); T.Assert (Reply.Get_Status = 200 or Reply.Get_Status = 302, "Get status is invalid: " & Natural'Image (Reply.Get_Status)); Util.Http.Tools.Save_Response (Util.Tests.Get_Test_Path ("http_get.txt"), Reply, True); -- Check the content. declare Content : constant String := Util.Strings.Transforms.To_Lower_Case (Reply.Get_Body); begin Util.Tests.Assert_Matches (T, ".*html.*", Content, "Invalid GET content"); end; -- Check one header. declare Content : constant String := Reply.Get_Header ("Content-Type"); begin T.Assert (Content'Length > 0, "Empty Content-Type header"); Util.Tests.Assert_Matches (T, ".*text/html.*", Content, "Invalid content type"); end; end Test_Http_Get; -- ------------------------------ -- Test the http POST operation. -- ------------------------------ procedure Test_Http_Post (T : in out Test) is Request : Client; Reply : Response; Uri : constant String := T.Get_Uri; begin Log.Info ("Post on " & Uri); T.Server.Method := UNKNOWN; Request.Post (Uri & "/post", "p1=1", Reply); T.Assert (T.Server.Method = POST, "Invalid method received by server"); Util.Tests.Assert_Equals (T, "application/x-www-form-urlencoded", T.Server.Content_Type, "Invalid content type received by server"); Util.Tests.Assert_Equals (T, "OK" & ASCII.CR & ASCII.LF, Reply.Get_Body, "Invalid response"); Util.Http.Tools.Save_Response (Util.Tests.Get_Test_Path ("http_post.txt"), Reply, True); end Test_Http_Post; end Util.Http.Clients.Tests;
Update the test to indicate the HTTP response status if an error occurs
Update the test to indicate the HTTP response status if an error occurs
Ada
apache-2.0
flottokarotto/ada-util,flottokarotto/ada-util,Letractively/ada-util,Letractively/ada-util
5a528c6a603a3a87bfb033c62e6717e6aabd9a42
matp/src/mat-formats.adb
matp/src/mat-formats.adb
----------------------------------------------------------------------- -- mat-formats - Format various types for the console or GUI interface -- Copyright (C) 2015 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Strings; package body MAT.Formats is use type MAT.Types.Target_Tick_Ref; Hex_Prefix : Boolean := True; Conversion : constant String (1 .. 10) := "0123456789"; function Location (File : in Ada.Strings.Unbounded.Unbounded_String) return String; function Event_Malloc (Item : in MAT.Events.Targets.Probe_Event_Type; Related : in MAT.Events.Targets.Target_Event_Vector; Start_Time : in MAT.Types.Target_Tick_Ref) return String; function Event_Free (Item : in MAT.Events.Targets.Probe_Event_Type; Related : in MAT.Events.Targets.Target_Event_Vector; Start_Time : in MAT.Types.Target_Tick_Ref) return String; -- ------------------------------ -- Format the address into a string. -- ------------------------------ function Addr (Value : in MAT.Types.Target_Addr) return String is Hex : constant String := MAT.Types.Hex_Image (Value); begin if Hex_Prefix then return "0x" & Hex; else return Hex; end if; end Addr; -- ------------------------------ -- Format the size into a string. -- ------------------------------ function Size (Value : in MAT.Types.Target_Size) return String is Result : constant String := MAT.Types.Target_Size'Image (Value); begin if Result (Result'First) = ' ' then return Result (Result'First + 1 .. Result'Last); else return Result; end if; end Size; -- ------------------------------ -- Format the time relative to the start time. -- ------------------------------ function Time (Value : in MAT.Types.Target_Tick_Ref; Start : in MAT.Types.Target_Tick_Ref) return String is T : constant MAT.Types.Target_Tick_Ref := Value - Start; Sec : constant MAT.Types.Target_Tick_Ref := T / 1_000_000; Usec : constant MAT.Types.Target_Tick_Ref := T mod 1_000_000; Msec : Natural := Natural (Usec / 1_000); Frac : String (1 .. 5); begin Frac (5) := 's'; Frac (4) := Conversion (Msec mod 10 + 1); Msec := Msec / 10; Frac (3) := Conversion (Msec mod 10 + 1); Msec := Msec / 10; Frac (2) := Conversion (Msec mod 10 + 1); Frac (1) := '.'; return MAT.Types.Target_Tick_Ref'Image (Sec) & Frac; end Time; -- ------------------------------ -- Format the duration in seconds, milliseconds or microseconds. -- ------------------------------ function Duration (Value : in MAT.Types.Target_Tick_Ref) return String is Sec : constant MAT.Types.Target_Tick_Ref := Value / 1_000_000; Usec : constant MAT.Types.Target_Tick_Ref := Value mod 1_000_000; Msec : constant Natural := Natural (Usec / 1_000); Val : Natural; Frac : String (1 .. 5); begin if Sec = 0 and Msec = 0 then return Util.Strings.Image (Integer (Usec)) & "us"; elsif Sec = 0 then Val := Natural (Usec mod 1_000); Frac (5) := 's'; Frac (4) := 'm'; Frac (3) := Conversion (Val mod 10 + 1); Val := Val / 10; Frac (3) := Conversion (Val mod 10 + 1); Val := Val / 10; Frac (2) := Conversion (Val mod 10 + 1); Frac (1) := '.'; return Util.Strings.Image (Integer (Msec)) & Frac; else Val := Msec; Frac (4) := 's'; Frac (3) := Conversion (Val mod 10 + 1); Val := Val / 10; Frac (3) := Conversion (Val mod 10 + 1); Val := Val / 10; Frac (2) := Conversion (Val mod 10 + 1); Frac (1) := '.'; return Util.Strings.Image (Integer (Msec)) & Frac (1 .. 4); end if; end Duration; function Location (File : in Ada.Strings.Unbounded.Unbounded_String) return String is Pos : constant Natural := Ada.Strings.Unbounded.Index (File, "/", Ada.Strings.Backward); Len : constant Natural := Ada.Strings.Unbounded.Length (File); begin if Pos /= 0 then return Ada.Strings.Unbounded.Slice (File, Pos + 1, Len); else return Ada.Strings.Unbounded.To_String (File); end if; end Location; -- ------------------------------ -- Format a file, line, function information into a string. -- ------------------------------ function Location (File : in Ada.Strings.Unbounded.Unbounded_String; Line : in Natural; Func : in Ada.Strings.Unbounded.Unbounded_String) return String is begin if Ada.Strings.Unbounded.Length (File) = 0 then return Ada.Strings.Unbounded.To_String (Func); elsif Line > 0 then declare Num : constant String := Natural'Image (Line); begin return Ada.Strings.Unbounded.To_String (Func) & " (" & Location (File) & ":" & Num (Num'First + 1 .. Num'Last) & ")"; end; else return Ada.Strings.Unbounded.To_String (Func) & " (" & Location (File) & ")"; end if; end Location; -- ------------------------------ -- Format a short description of the event. -- ------------------------------ function Event (Item : in MAT.Events.Targets.Probe_Event_Type; Mode : in Format_Type := NORMAL) return String is use type MAT.Types.Target_Addr; begin case Item.Index is when MAT.Events.Targets.MSG_MALLOC => if Mode = BRIEF then return "malloc(" & Size (Item.Size) & ")"; else return "malloc(" & Size (Item.Size) & ") = " & Addr (Item.Addr); end if; when MAT.Events.Targets.MSG_REALLOC => if Mode = BRIEF then if Item.Old_Addr = 0 then return "realloc(0," & Size (Item.Size) & ")"; else return "realloc(" & Addr (Item.Old_Addr) & "," & Size (Item.Size) & ")"; end if; else if Item.Old_Addr = 0 then return "realloc(0," & Size (Item.Size) & ") = " & Addr (Item.Addr); else return "realloc(" & Addr (Item.Old_Addr) & "," & Size (Item.Size) & ") = " & Addr (Item.Addr); end if; end if; when MAT.Events.Targets.MSG_FREE => return "free(" & Addr (Item.Addr) & ")"; when MAT.Events.Targets.MSG_BEGIN => return "begin"; when MAT.Events.Targets.MSG_END => return "end"; when MAT.Events.Targets.MSG_LIBRARY => return "library"; end case; end Event; function Event_Malloc (Item : in MAT.Events.Targets.Probe_Event_Type; Related : in MAT.Events.Targets.Target_Event_Vector; Start_Time : in MAT.Types.Target_Tick_Ref) return String is Free_Event : MAT.Events.Targets.Probe_Event_Type; begin Free_Event := MAT.Events.Targets.Find (Related, MAT.Events.Targets.MSG_FREE); return Size (Item.Size) & " bytes allocated after " & Duration (Item.Time - Start_Time) & ", freed " & Duration (Free_Event.Time - Item.Time) & " after by event" & MAT.Events.Targets.Event_Id_Type'Image (Free_Event.Id) ; exception when MAT.Events.Targets.Not_Found => return Size (Item.Size) & " bytes allocated (never freed)"; end Event_Malloc; function Event_Free (Item : in MAT.Events.Targets.Probe_Event_Type; Related : in MAT.Events.Targets.Target_Event_Vector; Start_Time : in MAT.Types.Target_Tick_Ref) return String is Alloc_Event : MAT.Events.Targets.Probe_Event_Type; begin Alloc_Event := MAT.Events.Targets.Find (Related, MAT.Events.Targets.MSG_MALLOC); return Size (Alloc_Event.Size) & " bytes freed after " & Duration (Item.Time - Start_Time) & ", alloc'ed for " & Duration (Item.Time - Alloc_Event.Time) & " by event" & MAT.Events.Targets.Event_Id_Type'Image (Alloc_Event.Id); exception when MAT.Events.Targets.Not_Found => return Size (Item.Size) & " bytes freed"; end Event_Free; -- ------------------------------ -- Format a short description of the event. -- ------------------------------ function Event (Item : in MAT.Events.Targets.Probe_Event_Type; Related : in MAT.Events.Targets.Target_Event_Vector; Start_Time : in MAT.Types.Target_Tick_Ref) return String is begin case Item.Index is when MAT.Events.Targets.MSG_MALLOC => return Event_Malloc (Item, Related, Start_Time); when MAT.Events.Targets.MSG_REALLOC => return Size (Item.Size) & " bytes reallocated"; when MAT.Events.Targets.MSG_FREE => return Event_Free (Item, Related, Start_Time); when MAT.Events.Targets.MSG_BEGIN => return "Begin event"; when MAT.Events.Targets.MSG_END => return "End event"; when MAT.Events.Targets.MSG_LIBRARY => return "Library information event"; end case; end Event; end MAT.Formats;
----------------------------------------------------------------------- -- mat-formats - Format various types for the console or GUI interface -- Copyright (C) 2015 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Strings; package body MAT.Formats is use type MAT.Types.Target_Tick_Ref; Hex_Prefix : Boolean := True; Conversion : constant String (1 .. 10) := "0123456789"; function Location (File : in Ada.Strings.Unbounded.Unbounded_String) return String; function Event_Malloc (Item : in MAT.Events.Targets.Probe_Event_Type; Related : in MAT.Events.Targets.Target_Event_Vector; Start_Time : in MAT.Types.Target_Tick_Ref) return String; function Event_Free (Item : in MAT.Events.Targets.Probe_Event_Type; Related : in MAT.Events.Targets.Target_Event_Vector; Start_Time : in MAT.Types.Target_Tick_Ref) return String; -- ------------------------------ -- Format the address into a string. -- ------------------------------ function Addr (Value : in MAT.Types.Target_Addr) return String is Hex : constant String := MAT.Types.Hex_Image (Value); begin if Hex_Prefix then return "0x" & Hex; else return Hex; end if; end Addr; -- ------------------------------ -- Format the size into a string. -- ------------------------------ function Size (Value : in MAT.Types.Target_Size) return String is Result : constant String := MAT.Types.Target_Size'Image (Value); begin if Result (Result'First) = ' ' then return Result (Result'First + 1 .. Result'Last); else return Result; end if; end Size; -- ------------------------------ -- Format the time relative to the start time. -- ------------------------------ function Time (Value : in MAT.Types.Target_Tick_Ref; Start : in MAT.Types.Target_Tick_Ref) return String is T : constant MAT.Types.Target_Tick_Ref := Value - Start; Sec : constant MAT.Types.Target_Tick_Ref := T / 1_000_000; Usec : constant MAT.Types.Target_Tick_Ref := T mod 1_000_000; Msec : Natural := Natural (Usec / 1_000); Frac : String (1 .. 5); begin Frac (5) := 's'; Frac (4) := Conversion (Msec mod 10 + 1); Msec := Msec / 10; Frac (3) := Conversion (Msec mod 10 + 1); Msec := Msec / 10; Frac (2) := Conversion (Msec mod 10 + 1); Frac (1) := '.'; return MAT.Types.Target_Tick_Ref'Image (Sec) & Frac; end Time; -- ------------------------------ -- Format the duration in seconds, milliseconds or microseconds. -- ------------------------------ function Duration (Value : in MAT.Types.Target_Tick_Ref) return String is Sec : constant MAT.Types.Target_Tick_Ref := Value / 1_000_000; Usec : constant MAT.Types.Target_Tick_Ref := Value mod 1_000_000; Msec : constant Natural := Natural (Usec / 1_000); Val : Natural; Frac : String (1 .. 5); begin if Sec = 0 and Msec = 0 then return Util.Strings.Image (Integer (Usec)) & "us"; elsif Sec = 0 then Val := Natural (Usec mod 1_000); Frac (5) := 's'; Frac (4) := 'm'; Frac (3) := Conversion (Val mod 10 + 1); Val := Val / 10; Frac (3) := Conversion (Val mod 10 + 1); Val := Val / 10; Frac (2) := Conversion (Val mod 10 + 1); Frac (1) := '.'; return Util.Strings.Image (Integer (Msec)) & Frac; else Val := Msec; Frac (4) := 's'; Frac (3) := Conversion (Val mod 10 + 1); Val := Val / 10; Frac (3) := Conversion (Val mod 10 + 1); Val := Val / 10; Frac (2) := Conversion (Val mod 10 + 1); Frac (1) := '.'; return Util.Strings.Image (Integer (Sec)) & Frac (1 .. 4); end if; end Duration; function Location (File : in Ada.Strings.Unbounded.Unbounded_String) return String is Pos : constant Natural := Ada.Strings.Unbounded.Index (File, "/", Ada.Strings.Backward); Len : constant Natural := Ada.Strings.Unbounded.Length (File); begin if Pos /= 0 then return Ada.Strings.Unbounded.Slice (File, Pos + 1, Len); else return Ada.Strings.Unbounded.To_String (File); end if; end Location; -- ------------------------------ -- Format a file, line, function information into a string. -- ------------------------------ function Location (File : in Ada.Strings.Unbounded.Unbounded_String; Line : in Natural; Func : in Ada.Strings.Unbounded.Unbounded_String) return String is begin if Ada.Strings.Unbounded.Length (File) = 0 then return Ada.Strings.Unbounded.To_String (Func); elsif Line > 0 then declare Num : constant String := Natural'Image (Line); begin return Ada.Strings.Unbounded.To_String (Func) & " (" & Location (File) & ":" & Num (Num'First + 1 .. Num'Last) & ")"; end; else return Ada.Strings.Unbounded.To_String (Func) & " (" & Location (File) & ")"; end if; end Location; -- ------------------------------ -- Format a short description of the event. -- ------------------------------ function Event (Item : in MAT.Events.Targets.Probe_Event_Type; Mode : in Format_Type := NORMAL) return String is use type MAT.Types.Target_Addr; begin case Item.Index is when MAT.Events.Targets.MSG_MALLOC => if Mode = BRIEF then return "malloc(" & Size (Item.Size) & ")"; else return "malloc(" & Size (Item.Size) & ") = " & Addr (Item.Addr); end if; when MAT.Events.Targets.MSG_REALLOC => if Mode = BRIEF then if Item.Old_Addr = 0 then return "realloc(0," & Size (Item.Size) & ")"; else return "realloc(" & Addr (Item.Old_Addr) & "," & Size (Item.Size) & ")"; end if; else if Item.Old_Addr = 0 then return "realloc(0," & Size (Item.Size) & ") = " & Addr (Item.Addr); else return "realloc(" & Addr (Item.Old_Addr) & "," & Size (Item.Size) & ") = " & Addr (Item.Addr); end if; end if; when MAT.Events.Targets.MSG_FREE => return "free(" & Addr (Item.Addr) & ")"; when MAT.Events.Targets.MSG_BEGIN => return "begin"; when MAT.Events.Targets.MSG_END => return "end"; when MAT.Events.Targets.MSG_LIBRARY => return "library"; end case; end Event; function Event_Malloc (Item : in MAT.Events.Targets.Probe_Event_Type; Related : in MAT.Events.Targets.Target_Event_Vector; Start_Time : in MAT.Types.Target_Tick_Ref) return String is Free_Event : MAT.Events.Targets.Probe_Event_Type; begin Free_Event := MAT.Events.Targets.Find (Related, MAT.Events.Targets.MSG_FREE); return Size (Item.Size) & " bytes allocated after " & Duration (Item.Time - Start_Time) & ", freed " & Duration (Free_Event.Time - Item.Time) & " after by event" & MAT.Events.Targets.Event_Id_Type'Image (Free_Event.Id) ; exception when MAT.Events.Targets.Not_Found => return Size (Item.Size) & " bytes allocated (never freed)"; end Event_Malloc; function Event_Free (Item : in MAT.Events.Targets.Probe_Event_Type; Related : in MAT.Events.Targets.Target_Event_Vector; Start_Time : in MAT.Types.Target_Tick_Ref) return String is Alloc_Event : MAT.Events.Targets.Probe_Event_Type; begin Alloc_Event := MAT.Events.Targets.Find (Related, MAT.Events.Targets.MSG_MALLOC); return Size (Alloc_Event.Size) & " bytes freed after " & Duration (Item.Time - Start_Time) & ", alloc'ed for " & Duration (Item.Time - Alloc_Event.Time) & " by event" & MAT.Events.Targets.Event_Id_Type'Image (Alloc_Event.Id); exception when MAT.Events.Targets.Not_Found => return Size (Item.Size) & " bytes freed"; end Event_Free; -- ------------------------------ -- Format a short description of the event. -- ------------------------------ function Event (Item : in MAT.Events.Targets.Probe_Event_Type; Related : in MAT.Events.Targets.Target_Event_Vector; Start_Time : in MAT.Types.Target_Tick_Ref) return String is begin case Item.Index is when MAT.Events.Targets.MSG_MALLOC => return Event_Malloc (Item, Related, Start_Time); when MAT.Events.Targets.MSG_REALLOC => return Size (Item.Size) & " bytes reallocated"; when MAT.Events.Targets.MSG_FREE => return Event_Free (Item, Related, Start_Time); when MAT.Events.Targets.MSG_BEGIN => return "Begin event"; when MAT.Events.Targets.MSG_END => return "End event"; when MAT.Events.Targets.MSG_LIBRARY => return "Library information event"; end case; end Event; end MAT.Formats;
Fix formatting of time with seconds > 0
Fix formatting of time with seconds > 0
Ada
apache-2.0
stcarrez/mat,stcarrez/mat,stcarrez/mat
1af1066b73e47fc66f041728341359126c5cfb25
src/gen-model-mappings.adb
src/gen-model-mappings.adb
----------------------------------------------------------------------- -- gen-model-mappings -- Type mappings for Code Generator -- Copyright (C) 2011, 2012, 2015 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Log.Loggers; -- The <b>Gen.Model.Mappings</b> package controls the mappings to convert an XML -- type into the Ada type. package body Gen.Model.Mappings is use Ada.Strings.Unbounded; Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("Gen.Model.Mappings"); Types : Mapping_Maps.Map; Mapping_Name : Unbounded_String; -- ------------------------------ -- Get the value identified by the name. -- If the name cannot be found, the method should return the Null object. -- ------------------------------ overriding function Get_Value (From : in Mapping_Definition; Name : in String) return Util.Beans.Objects.Object is begin if Name = "name" then return Util.Beans.Objects.To_Object (From.Target); elsif Name = "isBoolean" then return Util.Beans.Objects.To_Object (From.Kind = T_BOOLEAN); elsif Name = "isInteger" then return Util.Beans.Objects.To_Object (From.Kind = T_INTEGER); elsif Name = "isString" then return Util.Beans.Objects.To_Object (From.Kind = T_STRING); elsif Name = "isIdentifier" then return Util.Beans.Objects.To_Object (From.Kind = T_IDENTIFIER); elsif Name = "isDate" then return Util.Beans.Objects.To_Object (From.Kind = T_DATE); elsif Name = "isBlob" then return Util.Beans.Objects.To_Object (From.Kind = T_BLOB); elsif Name = "isEnum" then return Util.Beans.Objects.To_Object (From.Kind = T_ENUM); elsif Name = "isPrimitiveType" then return Util.Beans.Objects.To_Object (From.Kind /= T_TABLE and From.Kind /= T_BLOB); else return Definition (From).Get_Value (Name); end if; end Get_Value; -- ------------------------------ -- Find the mapping for the given type name. -- ------------------------------ function Find_Type (Name : in Ada.Strings.Unbounded.Unbounded_String; Allow_Null : in Boolean) return Mapping_Definition_Access is Pos : constant Mapping_Maps.Cursor := Types.Find (Mapping_Name & Name); begin if not Mapping_Maps.Has_Element (Pos) then Log.Info ("Type '{0}' not found in mapping table '{1}'", To_String (Name), To_String (Mapping_Name)); return null; elsif Allow_Null then if Mapping_Maps.Element (Pos).Allow_Null = null then Log.Info ("Type '{0}' does not allow a null value in mapping table '{1}'", To_String (Name), To_String (Mapping_Name)); return Mapping_Maps.Element (Pos); end if; return Mapping_Maps.Element (Pos).Allow_Null; else return Mapping_Maps.Element (Pos); end if; end Find_Type; procedure Register_Type (Name : in String; Mapping : in Mapping_Definition_Access; Kind : in Basic_Type) is N : constant Unbounded_String := Mapping_Name & To_Unbounded_String (Name); Pos : constant Mapping_Maps.Cursor := Types.Find (N); begin Log.Debug ("Register type '{0}'", Name); if not Mapping_Maps.Has_Element (Pos) then Mapping.Kind := Kind; Types.Insert (N, Mapping); end if; end Register_Type; -- ------------------------------ -- Register a type mapping <b>From</b> that is mapped to <b>Target</b>. -- ------------------------------ procedure Register_Type (Target : in String; From : in String; Kind : in Basic_Type; Allow_Null : in Boolean) is Name : constant Unbounded_String := Mapping_Name & To_Unbounded_String (From); Pos : constant Mapping_Maps.Cursor := Types.Find (Name); Mapping : Mapping_Definition_Access; Found : Boolean; begin Log.Debug ("Register type '{0}' mapped to '{1}' type {2}", From, Target, Basic_Type'Image (Kind)); Found := Mapping_Maps.Has_Element (Pos); if Found then Mapping := Mapping_Maps.Element (Pos); else Mapping := new Mapping_Definition; Mapping.Set_Name (From); Types.Insert (Name, Mapping); end if; if Allow_Null then Mapping.Allow_Null := new Mapping_Definition; Mapping.Allow_Null.Target := To_Unbounded_String (Target); Mapping.Allow_Null.Kind := Kind; Mapping.Allow_Null.Nullable := True; if not Found then Mapping.Target := To_Unbounded_String (Target); Mapping.Kind := Kind; end if; else Mapping.Target := To_Unbounded_String (Target); Mapping.Kind := Kind; end if; end Register_Type; -- ------------------------------ -- Setup the type mapping for the language identified by the given name. -- ------------------------------ procedure Set_Mapping_Name (Name : in String) is begin Log.Info ("Using type mapping {0}", Name); Mapping_Name := To_Unbounded_String (Name & "."); end Set_Mapping_Name; end Gen.Model.Mappings;
----------------------------------------------------------------------- -- gen-model-mappings -- Type mappings for Code Generator -- Copyright (C) 2011, 2012, 2015, 2018 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Log.Loggers; -- The <b>Gen.Model.Mappings</b> package controls the mappings to convert an XML -- type into the Ada type. package body Gen.Model.Mappings is use Ada.Strings.Unbounded; Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("Gen.Model.Mappings"); Types : Mapping_Maps.Map; Mapping_Name : Unbounded_String; -- ------------------------------ -- Get the value identified by the name. -- If the name cannot be found, the method should return the Null object. -- ------------------------------ overriding function Get_Value (From : in Mapping_Definition; Name : in String) return Util.Beans.Objects.Object is begin if Name = "name" then return Util.Beans.Objects.To_Object (From.Target); elsif Name = "isBoolean" then return Util.Beans.Objects.To_Object (From.Kind = T_BOOLEAN); elsif Name = "isInteger" then return Util.Beans.Objects.To_Object (From.Kind = T_INTEGER); elsif Name = "isString" then return Util.Beans.Objects.To_Object (From.Kind = T_STRING); elsif Name = "isIdentifier" then return Util.Beans.Objects.To_Object (From.Kind = T_IDENTIFIER); elsif Name = "isDate" then return Util.Beans.Objects.To_Object (From.Kind = T_DATE); elsif Name = "isBlob" then return Util.Beans.Objects.To_Object (From.Kind = T_BLOB); elsif Name = "isEnum" then return Util.Beans.Objects.To_Object (From.Kind = T_ENUM); elsif Name = "isPrimitiveType" then return Util.Beans.Objects.To_Object (From.Kind /= T_TABLE and From.Kind /= T_BLOB); else return Definition (From).Get_Value (Name); end if; end Get_Value; -- ------------------------------ -- Get the type name. -- ------------------------------ function Get_Type_Name (From : Mapping_Definition) return String is begin case From.Kind is when T_BOOLEAN => return "boolean"; when T_INTEGER => return "integer"; when T_DATE => return "date"; when T_IDENTIFIER => return "identifier"; when T_STRING => return "string"; when T_ENUM => return From.Get_Name; when others => return From.Get_Name; end case; end Get_Type_Name; -- ------------------------------ -- Find the mapping for the given type name. -- ------------------------------ function Find_Type (Name : in Ada.Strings.Unbounded.Unbounded_String; Allow_Null : in Boolean) return Mapping_Definition_Access is Pos : constant Mapping_Maps.Cursor := Types.Find (Mapping_Name & Name); begin if not Mapping_Maps.Has_Element (Pos) then Log.Info ("Type '{0}' not found in mapping table '{1}'", To_String (Name), To_String (Mapping_Name)); return null; elsif Allow_Null then if Mapping_Maps.Element (Pos).Allow_Null = null then Log.Info ("Type '{0}' does not allow a null value in mapping table '{1}'", To_String (Name), To_String (Mapping_Name)); return Mapping_Maps.Element (Pos); end if; return Mapping_Maps.Element (Pos).Allow_Null; else return Mapping_Maps.Element (Pos); end if; end Find_Type; procedure Register_Type (Name : in String; Mapping : in Mapping_Definition_Access; Kind : in Basic_Type) is N : constant Unbounded_String := Mapping_Name & To_Unbounded_String (Name); Pos : constant Mapping_Maps.Cursor := Types.Find (N); begin Log.Debug ("Register type '{0}'", Name); if not Mapping_Maps.Has_Element (Pos) then Mapping.Kind := Kind; Types.Insert (N, Mapping); end if; end Register_Type; -- ------------------------------ -- Register a type mapping <b>From</b> that is mapped to <b>Target</b>. -- ------------------------------ procedure Register_Type (Target : in String; From : in String; Kind : in Basic_Type; Allow_Null : in Boolean) is Name : constant Unbounded_String := Mapping_Name & To_Unbounded_String (From); Pos : constant Mapping_Maps.Cursor := Types.Find (Name); Mapping : Mapping_Definition_Access; Found : Boolean; begin Log.Debug ("Register type '{0}' mapped to '{1}' type {2}", From, Target, Basic_Type'Image (Kind)); Found := Mapping_Maps.Has_Element (Pos); if Found then Mapping := Mapping_Maps.Element (Pos); else Mapping := new Mapping_Definition; Mapping.Set_Name (From); Types.Insert (Name, Mapping); end if; if Allow_Null then Mapping.Allow_Null := new Mapping_Definition; Mapping.Allow_Null.Target := To_Unbounded_String (Target); Mapping.Allow_Null.Kind := Kind; Mapping.Allow_Null.Nullable := True; if not Found then Mapping.Target := To_Unbounded_String (Target); Mapping.Kind := Kind; end if; else Mapping.Target := To_Unbounded_String (Target); Mapping.Kind := Kind; end if; end Register_Type; -- ------------------------------ -- Setup the type mapping for the language identified by the given name. -- ------------------------------ procedure Set_Mapping_Name (Name : in String) is begin Log.Info ("Using type mapping {0}", Name); Mapping_Name := To_Unbounded_String (Name & "."); end Set_Mapping_Name; end Gen.Model.Mappings;
Implement Get_Type_Name function
Implement Get_Type_Name function
Ada
apache-2.0
stcarrez/dynamo,stcarrez/dynamo,stcarrez/dynamo
85683c3374579d06cb85b6a771bd8c76e2dd713d
src/security-oauth-clients.ads
src/security-oauth-clients.ads
----------------------------------------------------------------------- -- security-oauth -- OAuth Security -- Copyright (C) 2012, 2013, 2016, 2017 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Strings.Unbounded; -- The <b>Security.OAuth.Clients</b> package implements the client OAuth 2.0 authorization. -- -- Note: OAuth 1.0 could be implemented but since it's being deprecated it's not worth doing it. package Security.OAuth.Clients is -- ------------------------------ -- Access Token -- ------------------------------ -- Access tokens are credentials used to access protected resources. -- The access token is represented as a <b>Principal</b>. This is an opaque -- value for an application. type Access_Token (Len : Natural) is new Security.Principal with private; type Access_Token_Access is access all Access_Token'Class; -- Get the principal name. This is the OAuth access token. function Get_Name (From : in Access_Token) return String; type OpenID_Token (Len, Id_Len, Refresh_Len : Natural) is new Access_Token with private; type OpenID_Token_Access is access all OpenID_Token'Class; -- Get the id_token that was returned by the authentication process. function Get_Id_Token (From : in OpenID_Token) return String; -- Generate a random nonce with at last the number of random bits. -- The number of bits is rounded up to a multiple of 32. -- The random bits are then converted to base64url in the returned string. function Create_Nonce (Bits : in Positive := 256) return String; -- ------------------------------ -- Application -- ------------------------------ -- The <b>Application</b> holds the necessary information to let a user -- grant access to its protected resources on the resource server. It contains -- information that allows the OAuth authorization server to identify the -- application (client id and secret key). type Application is new Security.OAuth.Application with private; -- Set the OAuth authorization server URI that the application must use -- to exchange the OAuth code into an access token. procedure Set_Provider_URI (App : in out Application; URI : in String); -- OAuth 2.0 Section 4.1.1 Authorization Request -- Build a unique opaque value used to prevent cross-site request forgery. -- The <b>Nonce</b> parameters is an optional but recommended unique value -- used only once. The state value will be returned back by the OAuth provider. -- This protects the <tt>client_id</tt> and <tt>redirect_uri</tt> parameters. function Get_State (App : in Application; Nonce : in String) return String; -- Get the authenticate parameters to build the URI to redirect the user to -- the OAuth authorization form. function Get_Auth_Params (App : in Application; State : in String; Scope : in String := "") return String; -- OAuth 2.0 Section 4.1.2 Authorization Response -- Verify that the <b>State</b> opaque value was created by the <b>Get_State</b> -- operation with the given client and redirect URL. function Is_Valid_State (App : in Application; Nonce : in String; State : in String) return Boolean; -- OAuth 2.0 Section 4.1.3. Access Token Request -- Section 4.1.4. Access Token Response -- Exchange the OAuth code into an access token. function Request_Access_Token (App : in Application; Code : in String) return Access_Token_Access; -- Create the access token function Create_Access_Token (App : in Application; Token : in String; Refresh : in String; Id_Token : in String; Expires : in Natural) return Access_Token_Access; private type Access_Token (Len : Natural) is new Security.Principal with record Access_Id : String (1 .. Len); end record; type OpenID_Token (Len, Id_Len, Refresh_Len : Natural) is new Access_Token (Len) with record Id_Token : String (1 .. Id_Len); Refresh_Token : String (1 .. Refresh_Len); end record; type Application is new Security.OAuth.Application with record Request_URI : Ada.Strings.Unbounded.Unbounded_String; end record; end Security.OAuth.Clients;
----------------------------------------------------------------------- -- security-oauth -- OAuth Security -- Copyright (C) 2012, 2013, 2016, 2017, 2018 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Strings.Unbounded; -- The <b>Security.OAuth.Clients</b> package implements the client OAuth 2.0 authorization. -- -- Note: OAuth 1.0 could be implemented but since it's being deprecated it's not worth doing it. package Security.OAuth.Clients is -- ------------------------------ -- Access Token -- ------------------------------ -- Access tokens are credentials used to access protected resources. -- The access token is represented as a <b>Principal</b>. This is an opaque -- value for an application. type Access_Token (Len : Natural) is new Security.Principal with private; type Access_Token_Access is access all Access_Token'Class; -- Get the principal name. This is the OAuth access token. function Get_Name (From : in Access_Token) return String; type OpenID_Token (Len, Id_Len, Refresh_Len : Natural) is new Access_Token with private; type OpenID_Token_Access is access all OpenID_Token'Class; -- Get the id_token that was returned by the authentication process. function Get_Id_Token (From : in OpenID_Token) return String; -- Generate a random nonce with at last the number of random bits. -- The number of bits is rounded up to a multiple of 32. -- The random bits are then converted to base64url in the returned string. function Create_Nonce (Bits : in Positive := 256) return String; type Grant_Type is new Security.Principal with private; -- Get the principal name. This is the OAuth access token. function Get_Name (From : in Grant_Type) return String; -- ------------------------------ -- Application -- ------------------------------ -- The <b>Application</b> holds the necessary information to let a user -- grant access to its protected resources on the resource server. It contains -- information that allows the OAuth authorization server to identify the -- application (client id and secret key). type Application is new Security.OAuth.Application with private; -- Set the OAuth authorization server URI that the application must use -- to exchange the OAuth code into an access token. procedure Set_Provider_URI (App : in out Application; URI : in String); -- OAuth 2.0 Section 4.1.1 Authorization Request -- Build a unique opaque value used to prevent cross-site request forgery. -- The <b>Nonce</b> parameters is an optional but recommended unique value -- used only once. The state value will be returned back by the OAuth provider. -- This protects the <tt>client_id</tt> and <tt>redirect_uri</tt> parameters. function Get_State (App : in Application; Nonce : in String) return String; -- Get the authenticate parameters to build the URI to redirect the user to -- the OAuth authorization form. function Get_Auth_Params (App : in Application; State : in String; Scope : in String := "") return String; -- OAuth 2.0 Section 4.1.2 Authorization Response -- Verify that the <b>State</b> opaque value was created by the <b>Get_State</b> -- operation with the given client and redirect URL. function Is_Valid_State (App : in Application; Nonce : in String; State : in String) return Boolean; -- OAuth 2.0 Section 4.1.3. Access Token Request -- Section 4.1.4. Access Token Response -- Exchange the OAuth code into an access token. function Request_Access_Token (App : in Application; Code : in String) return Access_Token_Access; -- Create the access token function Create_Access_Token (App : in Application; Token : in String; Refresh : in String; Id_Token : in String; Expires : in Natural) return Access_Token_Access; private type Access_Token (Len : Natural) is new Security.Principal with record Access_Id : String (1 .. Len); end record; type OpenID_Token (Len, Id_Len, Refresh_Len : Natural) is new Access_Token (Len) with record Id_Token : String (1 .. Id_Len); Refresh_Token : String (1 .. Refresh_Len); end record; type Application is new Security.OAuth.Application with record Request_URI : Ada.Strings.Unbounded.Unbounded_String; end record; type Grant_Type is new Security.Principal with record Access_Token : Ada.Strings.Unbounded.Unbounded_String; Refresh_Token : Ada.Strings.Unbounded.Unbounded_String; Id_Token : Ada.Strings.Unbounded.Unbounded_String; end record; end Security.OAuth.Clients;
Declare the Grant_Type for a better representation of a grant returned during the OAuth authorization Declare the Get_Name function for Grant_Type
Declare the Grant_Type for a better representation of a grant returned during the OAuth authorization Declare the Get_Name function for Grant_Type
Ada
apache-2.0
stcarrez/ada-security
68ba9c2c9d59839de8f31e51690a15bc13ecb878
regtests/util-texts-builders_tests.ads
regtests/util-texts-builders_tests.ads
----------------------------------------------------------------------- -- util-texts-builders_tests -- Unit tests for text builders -- Copyright (C) 2013 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Tests; package Util.Texts.Builders_Tests is procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite); type Test is new Util.Tests.Test with null record; -- Test the length operation. procedure Test_Length (T : in out Test); -- Test the append operation. procedure Test_Append (T : in out Test); -- Test the iterate operation. procedure Test_Iterate (T : in out Test); -- Test the clear operation. procedure Test_Clear (T : in out Test); -- Test the append and iterate performance. procedure Test_Perf (T : in out Test); end Util.Texts.Builders_Tests;
----------------------------------------------------------------------- -- util-texts-builders_tests -- Unit tests for text builders -- Copyright (C) 2013, 2016 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Tests; package Util.Texts.Builders_Tests is procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite); type Test is new Util.Tests.Test with null record; -- Test the length operation. procedure Test_Length (T : in out Test); -- Test the append operation. procedure Test_Append (T : in out Test); -- Test the iterate operation. procedure Test_Iterate (T : in out Test); -- Test the clear operation. procedure Test_Clear (T : in out Test); -- Test the tail operation. procedure Test_Tail (T : in out Test); -- Test the append and iterate performance. procedure Test_Perf (T : in out Test); end Util.Texts.Builders_Tests;
Declare the Test_Tail procedure
Declare the Test_Tail procedure
Ada
apache-2.0
stcarrez/ada-util,stcarrez/ada-util
bbcbc409473862ef502c3d232d2d2cf0d67a4e4f
src/el-objects-enums.adb
src/el-objects-enums.adb
----------------------------------------------------------------------- -- EL.Objects.Enums -- Helper conversion for discrete types -- Copyright (C) 2010 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Characters.Conversions; package body EL.Objects.Enums is use Ada.Characters.Conversions; Value_Range : constant Long_Long_Integer := T'Pos (T'Last) - T'Pos (T'First) + 1; NAME : aliased constant String := "Enum"; Value_Type : aliased constant Basic_Type := Basic_Type '(Name => NAME'Access); -- ------------------------------ -- Create an object from the given value. -- ------------------------------ function To_Object (Value : in T) return Object is begin return Object '(Controlled with V => Object_Value '(Of_Type => TYPE_INTEGER, Int_Value => Long_Long_Integer (T'Pos (Value))), Type_Def => Value_Type'Access); end To_Object; -- ------------------------------ -- Convert the object into a value. -- Raises Constraint_Error if the object cannot be converter to the target type. -- ------------------------------ function To_Value (Value : in EL.Objects.Object) return T is begin case Value.V.Of_Type is when TYPE_INTEGER => if ROUND_VALUE then return T'Val (Value.V.Int_Value mod Value_Range); else return T'Val (Value.V.Int_Value); end if; when TYPE_BOOLEAN => return T'Val (Boolean'Pos (Value.V.Bool_Value)); when TYPE_FLOAT => if ROUND_VALUE then return T'Val (To_Long_Long_Integer (Value) mod Value_Range); else return T'Val (To_Long_Long_Integer (Value)); end if; when TYPE_STRING => if Value.V.Proxy = null then raise Constraint_Error with "The object value is null"; end if; return T'Value (Value.V.Proxy.String_Value.all); when TYPE_WIDE_STRING => if Value.V.Proxy = null then raise Constraint_Error with "The object value is null"; end if; return T'Value (To_String (Value.V.Proxy.Wide_String_Value.all)); when TYPE_NULL => raise Constraint_Error with "The object value is null"; when TYPE_TIME => raise Constraint_Error with "Cannot convert a date into a discrete type"; when TYPE_BEAN => raise Constraint_Error with "Cannot convert a bean into a discrete type"; end case; end To_Value; end EL.Objects.Enums;
----------------------------------------------------------------------- -- EL.Objects.Enums -- Helper conversion for discrete types -- Copyright (C) 2010 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Characters.Conversions; package body EL.Objects.Enums is use Ada.Characters.Conversions; Value_Range : constant Long_Long_Integer := T'Pos (T'Last) - T'Pos (T'First) + 1; -- ------------------------------ -- Integer Type -- ------------------------------ type Enum_Type is new Int_Type with null record; -- Get the type name overriding function Get_Name (Type_Def : in Enum_Type) return String; overriding function To_String (Type_Def : in Enum_Type; Value : in Object_Value) return String; -- ------------------------------ -- Get the type name -- ------------------------------ overriding function Get_Name (Type_Def : Enum_Type) return String is pragma Unreferenced (Type_Def); begin return "Enum"; end Get_Name; -- ------------------------------ -- Convert the value into a string. -- ------------------------------ overriding function To_String (Type_Def : in Enum_Type; Value : in Object_Value) return String is pragma Unreferenced (Type_Def); begin return T'Image (T'Val (Value.Int_Value)); end To_String; Value_Type : aliased constant Enum_Type := Enum_Type '(others => <>); -- ------------------------------ -- Create an object from the given value. -- ------------------------------ function To_Object (Value : in T) return Object is begin return Object '(Controlled with V => Object_Value '(Of_Type => TYPE_INTEGER, Int_Value => Long_Long_Integer (T'Pos (Value))), Type_Def => Value_Type'Access); end To_Object; -- ------------------------------ -- Convert the object into a value. -- Raises Constraint_Error if the object cannot be converter to the target type. -- ------------------------------ function To_Value (Value : in EL.Objects.Object) return T is begin case Value.V.Of_Type is when TYPE_INTEGER => if ROUND_VALUE then return T'Val (Value.V.Int_Value mod Value_Range); else return T'Val (Value.V.Int_Value); end if; when TYPE_BOOLEAN => return T'Val (Boolean'Pos (Value.V.Bool_Value)); when TYPE_FLOAT => if ROUND_VALUE then return T'Val (To_Long_Long_Integer (Value) mod Value_Range); else return T'Val (To_Long_Long_Integer (Value)); end if; when TYPE_STRING => if Value.V.Proxy = null then raise Constraint_Error with "The object value is null"; end if; return T'Value (Value.V.Proxy.String_Value.all); when TYPE_WIDE_STRING => if Value.V.Proxy = null then raise Constraint_Error with "The object value is null"; end if; return T'Value (To_String (Value.V.Proxy.Wide_String_Value.all)); when TYPE_NULL => raise Constraint_Error with "The object value is null"; when TYPE_TIME => raise Constraint_Error with "Cannot convert a date into a discrete type"; when TYPE_BEAN => raise Constraint_Error with "Cannot convert a bean into a discrete type"; end case; end To_Value; end EL.Objects.Enums;
Implement the necessary functions for the enum type definition.
Implement the necessary functions for the enum type definition.
Ada
apache-2.0
stcarrez/ada-el
148d296278205d997332261af73e081d46e0e0f5
src/http/util-http-clients-mockups.adb
src/http/util-http-clients-mockups.adb
----------------------------------------------------------------------- -- util-http-clients-mockups -- HTTP Clients -- Copyright (C) 2011, 2012 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Files; with Util.Http.Mockups; package body Util.Http.Clients.Mockups is use Ada.Strings.Unbounded; Manager : aliased File_Http_Manager; -- ------------------------------ -- Register the Http manager. -- ------------------------------ procedure Register is begin Default_Http_Manager := Manager'Access; end Register; -- ------------------------------ -- Set the path of the file that contains the response for the next -- <b>Do_Get</b> and <b>Do_Post</b> calls. -- ------------------------------ procedure Set_File (Path : in String) is begin Manager.File := To_Unbounded_String (Path); end Set_File; procedure Create (Manager : in File_Http_Manager; Http : in out Client'Class) is pragma Unreferenced (Manager); begin Http.Delegate := new Util.Http.Mockups.Mockup_Request; end Create; procedure Do_Get (Manager : in File_Http_Manager; Http : in Client'Class; URI : in String; Reply : out Response'Class) is pragma Unreferenced (Http, URI); Rep : constant Util.Http.Mockups.Mockup_Response_Access := new Util.Http.Mockups.Mockup_Response; Content : Ada.Strings.Unbounded.Unbounded_String; begin Reply.Delegate := Rep.all'Access; Util.Files.Read_File (Path => To_String (Manager.File), Into => Content, Max_Size => 100000); Rep.Set_Body (To_String (Content)); Rep.Set_Status (SC_OK); end Do_Get; procedure Do_Post (Manager : in File_Http_Manager; Http : in Client'Class; URI : in String; Data : in String; Reply : out Response'Class) is pragma Unreferenced (Data); begin Manager.Do_Get (Http, URI, Reply); end Do_Post; end Util.Http.Clients.Mockups;
----------------------------------------------------------------------- -- util-http-clients-mockups -- HTTP Clients -- Copyright (C) 2011, 2012, 2017 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Files; with Util.Http.Mockups; package body Util.Http.Clients.Mockups is use Ada.Strings.Unbounded; Manager : aliased File_Http_Manager; -- ------------------------------ -- Register the Http manager. -- ------------------------------ procedure Register is begin Default_Http_Manager := Manager'Access; end Register; -- ------------------------------ -- Set the path of the file that contains the response for the next -- <b>Do_Get</b> and <b>Do_Post</b> calls. -- ------------------------------ procedure Set_File (Path : in String) is begin Manager.File := To_Unbounded_String (Path); end Set_File; procedure Create (Manager : in File_Http_Manager; Http : in out Client'Class) is pragma Unreferenced (Manager); begin Http.Delegate := new Util.Http.Mockups.Mockup_Request; end Create; overriding procedure Do_Get (Manager : in File_Http_Manager; Http : in Client'Class; URI : in String; Reply : out Response'Class) is pragma Unreferenced (Http, URI); Rep : constant Util.Http.Mockups.Mockup_Response_Access := new Util.Http.Mockups.Mockup_Response; Content : Ada.Strings.Unbounded.Unbounded_String; begin Reply.Delegate := Rep.all'Access; Util.Files.Read_File (Path => To_String (Manager.File), Into => Content, Max_Size => 100000); Rep.Set_Body (To_String (Content)); Rep.Set_Status (SC_OK); end Do_Get; overriding procedure Do_Post (Manager : in File_Http_Manager; Http : in Client'Class; URI : in String; Data : in String; Reply : out Response'Class) is pragma Unreferenced (Data); begin Manager.Do_Get (Http, URI, Reply); end Do_Post; overriding procedure Do_Put (Manager : in File_Http_Manager; Http : in Client'Class; URI : in String; Data : in String; Reply : out Response'Class) is pragma Unreferenced (Data); begin Manager.Do_Get (Http, URI, Reply); end Do_Put; end Util.Http.Clients.Mockups;
Implement the Do_Put procedure
Implement the Do_Put procedure
Ada
apache-2.0
stcarrez/ada-util,stcarrez/ada-util
6ab13933bb4dc3710075db0608e6bce35880b80f
src/orka/implementation/orka-debug.adb
src/orka/implementation/orka-debug.adb
-- SPDX-License-Identifier: Apache-2.0 -- -- Copyright (c) 2017 onox <[email protected]> -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. with GL.Errors; with GL.Debug.Logs; with GL.Toggles; with GL.Types; with Orka.Loggers; with Orka.Logging; package body Orka.Debug is use GL.Debug; Has_Seen_API_Error : Boolean := False with Volatile => True; Debug_Synchronous : Boolean := False with Volatile => True; procedure Log_Debug_Message (From : Source; Kind : Message_Type; Level : Severity; ID : GL.Types.UInt; Message : String) is use all type Orka.Loggers.Source; use all type Orka.Loggers.Severity; Source : constant Orka.Loggers.Source := (case From is when OpenGL => OpenGL, when Window_System => Window_System, when Shader_Compiler => Shader_Compiler, when Third_Party => Third_Party, when Application => Application, when Other => Other); Severity : constant Orka.Loggers.Severity := (case Level is when High => Loggers.Error, when Medium => Loggers.Warning, when Low => Loggers.Info, when Notification => Loggers.Debug); begin if Debug_Synchronous and then Has_Seen_API_Error then Has_Seen_API_Error := False; GL.Errors.Raise_Exception_On_OpenGL_Error; end if; Logging.Log (Source, Loggers.Message_Type (Kind), Severity, Natural (ID), Message); if Debug_Synchronous and then (Source = OpenGL and Kind = Error) then GL.Errors.Raise_Exception_On_OpenGL_Error; Has_Seen_API_Error := True; end if; end Log_Debug_Message; procedure Set_Log_Messages (Enable : Boolean; Raise_API_Error : Boolean := False) is begin if Enable then declare Count : constant Natural := Natural (GL.Debug.Logs.Logged_Messages); begin if Count > 0 then Log_Debug_Message (Application, Other, Notification, 0, "Flushing" & Count'Image & " messages in the debug log:"); end if; end; for M of GL.Debug.Logs.Message_Log loop Log_Debug_Message (M.From, M.Kind, M.Level, M.ID, M.Message.Element); end loop; GL.Toggles.Set (GL.Toggles.Debug_Output_Synchronous, (if Raise_API_Error then GL.Toggles.Enabled else GL.Toggles.Disabled)); Debug_Synchronous := Raise_API_Error; GL.Toggles.Enable (GL.Toggles.Debug_Output); GL.Debug.Set_Message_Callback (Log_Debug_Message'Access); GL.Debug.Set (GL.Debug.Low, True); else GL.Toggles.Disable (GL.Toggles.Debug_Output); GL.Debug.Disable_Message_Callback; end if; end Set_Log_Messages; end Orka.Debug;
-- SPDX-License-Identifier: Apache-2.0 -- -- Copyright (c) 2017 onox <[email protected]> -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. with GL.Errors; with GL.Debug.Logs; with GL.Toggles; with GL.Types; with Orka.Loggers; with Orka.Logging; package body Orka.Debug is use GL.Debug; Has_Seen_API_Error : Boolean := False with Volatile => True; Debug_Synchronous : Boolean := False with Volatile => True; procedure Log_Debug_Message (From : Source; Kind : Message_Type; Level : Severity; ID : GL.Types.UInt; Message : String) is use all type Orka.Loggers.Source; use all type Orka.Loggers.Severity; Source : constant Orka.Loggers.Source := (case From is when OpenGL => OpenGL, when Window_System => Window_System, when Shader_Compiler => Shader_Compiler, when Third_Party => Third_Party, when Application => Application, when Other => Other); Severity : constant Orka.Loggers.Severity := (case Level is when High => Loggers.Error, when Medium => Loggers.Warning, when Low => Loggers.Info, when Notification => Loggers.Debug); begin if Debug_Synchronous and then Has_Seen_API_Error then Has_Seen_API_Error := False; GL.Errors.Raise_Exception_On_OpenGL_Error; end if; Logging.Log (Source, Loggers.Message_Type (Kind), Severity, Natural (ID), Message); if Debug_Synchronous and then (Source = OpenGL and Kind = Error) then GL.Errors.Raise_Exception_On_OpenGL_Error; Has_Seen_API_Error := True; end if; end Log_Debug_Message; procedure Set_Log_Messages (Enable : Boolean; Raise_API_Error : Boolean := False) is begin if Enable then -- Enable synchronous output to prevent interleaving messages while -- flushing the log below GL.Toggles.Enable (GL.Toggles.Debug_Output_Synchronous); Debug_Synchronous := Raise_API_Error; GL.Toggles.Enable (GL.Toggles.Debug_Output); GL.Debug.Set_Message_Callback (Log_Debug_Message'Access); GL.Debug.Set (GL.Debug.Low, True); -- At this point, a callback has been set, which guarantees that no -- new messages will be stored in the log while we are flushing it declare Count : constant Natural := Natural (GL.Debug.Logs.Logged_Messages); Remaining : Natural := Count; begin if Count > 0 then Log_Debug_Message (Application, Other, Notification, 0, "Flushing" & Count'Image & " messages in the debug log:"); -- Use a loop because GL may fetch less messages than stored in the log while Remaining > 0 loop declare Messages : constant GL.Debug.Logs.Message_Array := GL.Debug.Logs.Message_Log; begin for M of Messages loop Log_Debug_Message (M.From, M.Kind, M.Level, M.ID, M.Message.Element); end loop; Remaining := Remaining - Messages'Length; end; end loop; Log_Debug_Message (Application, Other, Notification, 0, "End of messages in log"); end if; end; GL.Toggles.Set (GL.Toggles.Debug_Output_Synchronous, (if Raise_API_Error then GL.Toggles.Enabled else GL.Toggles.Disabled)); else GL.Toggles.Disable (GL.Toggles.Debug_Output); GL.Debug.Disable_Message_Callback; end if; end Set_Log_Messages; end Orka.Debug;
Make flushing log in procedure Set_Log_Messages more robust
orka: Make flushing log in procedure Set_Log_Messages more robust Signed-off-by: onox <[email protected]>
Ada
apache-2.0
onox/orka
b805d843006ab9cb3c27fa37f0a7c4644446fb3a
src/sys/os-windows/util-systems-os.ads
src/sys/os-windows/util-systems-os.ads
----------------------------------------------------------------------- -- util-system-os -- Windows system operations -- Copyright (C) 2011, 2012, 2015, 2018, 2019 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Unchecked_Deallocation; with System; with Interfaces.C; with Interfaces.C.Strings; with Util.Systems.Types; with Util.Systems.Constants; -- The <b>Util.Systems.Os</b> package defines various types and operations which are specific -- to the OS (Windows). package Util.Systems.Os is -- The directory separator. Directory_Separator : constant Character := '\'; -- The path separator. Path_Separator : constant Character := ';'; -- The line ending separator. Line_Separator : constant String := "" & ASCII.CR & ASCII.LF; -- Defines several windows specific types. type BOOL is mod 8; type WORD is new Interfaces.C.short; type DWORD is new Interfaces.C.unsigned_long; type PDWORD is access all DWORD; for PDWORD'Size use Standard'Address_Size; function Get_Last_Error return Integer with Import => True, Convention => Stdcall, Link_Name => "GetLastError"; function Errno return Integer with Import => True, Convention => Stdcall, Link_Name => "GetLastError"; -- Some useful error codes (See Windows document "System Error Codes (0-499)"). ERROR_BROKEN_PIPE : constant Integer := 109; -- ------------------------------ -- Handle -- ------------------------------ -- The windows HANDLE is defined as a void* in the C API. subtype HANDLE is Util.Systems.Types.HANDLE; use type Util.Systems.Types.HANDLE; INVALID_HANDLE_VALUE : constant HANDLE := -1; type PHANDLE is access all HANDLE; for PHANDLE'Size use Standard'Address_Size; function Wait_For_Single_Object (H : in HANDLE; Time : in DWORD) return DWORD with Import => True, Convention => Stdcall, Link_Name => "WaitForSingleObject"; type Security_Attributes is record Length : DWORD; Security_Descriptor : System.Address; Inherit : Interfaces.C.int := 0; end record; type LPSECURITY_ATTRIBUTES is access all Security_Attributes; for LPSECURITY_ATTRIBUTES'Size use Standard'Address_Size; -- ------------------------------ -- File operations -- ------------------------------ subtype File_Type is Util.Systems.Types.File_Type; NO_FILE : constant File_Type := 0; STD_INPUT_HANDLE : constant DWORD := -10; STD_OUTPUT_HANDLE : constant DWORD := -11; STD_ERROR_HANDLE : constant DWORD := -12; -- These values are specific to Linux. O_RDONLY : constant Interfaces.C.int := Util.Systems.Constants.O_RDONLY; O_WRONLY : constant Interfaces.C.int := Util.Systems.Constants.O_WRONLY; O_RDWR : constant Interfaces.C.int := Util.Systems.Constants.O_RDWR; O_CREAT : constant Interfaces.C.int := Util.Systems.Constants.O_CREAT; O_EXCL : constant Interfaces.C.int := Util.Systems.Constants.O_EXCL; O_TRUNC : constant Interfaces.C.int := Util.Systems.Constants.O_TRUNC; O_APPEND : constant Interfaces.C.int := Util.Systems.Constants.O_APPEND; function Get_Std_Handle (Kind : in DWORD) return File_Type with Import => True, Convention => Stdcall, Link_Name => "GetStdHandle"; function STDIN_FILENO return File_Type is (Get_Std_Handle (STD_INPUT_HANDLE)); function STDOUT_FILENO return File_Type is (Get_Std_Handle (STD_OUTPUT_HANDLE)); function STDERR_FILENO return File_Type is (Get_Std_Handle (STD_ERROR_HANDLE)); function Close_Handle (Fd : in File_Type) return BOOL with Import => True, Convention => Stdcall, Link_Name => "CloseHandle"; function Duplicate_Handle (SourceProcessHandle : in HANDLE; SourceHandle : in HANDLE; TargetProcessHandle : in HANDLE; TargetHandle : in PHANDLE; DesiredAccess : in DWORD; InheritHandle : in BOOL; Options : in DWORD) return BOOL with Import => True, Convention => Stdcall, Link_Name => "DuplicateHandle"; function Read_File (Fd : in File_Type; Buf : in System.Address; Size : in DWORD; Result : in PDWORD; Overlap : in System.Address) return BOOL with Import => True, Convention => Stdcall, Link_Name => "ReadFile"; function Write_File (Fd : in File_Type; Buf : in System.Address; Size : in DWORD; Result : in PDWORD; Overlap : in System.Address) return BOOL with Import => True, Convention => Stdcall, Link_Name => "WriteFile"; function Create_Pipe (Read_Handle : in PHANDLE; Write_Handle : in PHANDLE; Attributes : in LPSECURITY_ATTRIBUTES; Buf_Size : in DWORD) return BOOL with Import => True, Convention => Stdcall, Link_Name => "CreatePipe"; subtype LPWSTR is Interfaces.C.Strings.chars_ptr; subtype LPCSTR is Interfaces.C.Strings.chars_ptr; subtype PBYTE is Interfaces.C.Strings.chars_ptr; subtype Ptr is Interfaces.C.Strings.chars_ptr; subtype LPCTSTR is System.Address; subtype LPTSTR is System.Address; type CommandPtr is access all Interfaces.C.wchar_array; NULL_STR : constant LPWSTR := Interfaces.C.Strings.Null_Ptr; type FileTime is record dwLowDateTime : DWORD; dwHighDateTime : DWORD; end record; type LPFILETIME is access all FileTime; function To_Time (Time : in FileTime) return Util.Systems.Types.Time_Type; type Startup_Info is record cb : DWORD := 0; lpReserved : LPWSTR := NULL_STR; lpDesktop : LPWSTR := NULL_STR; lpTitle : LPWSTR := NULL_STR; dwX : DWORD := 0; dwY : DWORD := 0; dwXsize : DWORD := 0; dwYsize : DWORD := 0; dwXCountChars : DWORD := 0; dwYCountChars : DWORD := 0; dwFillAttribute : DWORD := 0; dwFlags : DWORD := 0; wShowWindow : WORD := 0; cbReserved2 : WORD := 0; lpReserved2 : PBYTE := Interfaces.C.Strings.Null_Ptr; hStdInput : HANDLE := 0; hStdOutput : HANDLE := 0; hStdError : HANDLE := 0; end record; type Startup_Info_Access is access all Startup_Info; type PROCESS_INFORMATION is record hProcess : HANDLE := NO_FILE; hThread : HANDLE := NO_FILE; dwProcessId : DWORD; dwThreadId : DWORD; end record; type Process_Information_Access is access all PROCESS_INFORMATION; function Get_Current_Process return HANDLE with Import => True, Convention => Stdcall, Link_Name => "GetCurrentProcess"; function Get_Exit_Code_Process (Proc : in HANDLE; Code : in PDWORD) return BOOL with Import => True, Convention => Stdcall, Link_Name => "GetExitCodeProcess"; function Create_Process (Name : in LPCTSTR; Command : in System.Address; Process_Attributes : in LPSECURITY_ATTRIBUTES; Thread_Attributes : in LPSECURITY_ATTRIBUTES; Inherit_Handles : in BOOL; Creation_Flags : in DWORD; Environment : in LPTSTR; Directory : in LPCTSTR; Startup_Info : in Startup_Info_Access; Process_Info : in Process_Information_Access) return Integer with Import => True, Convention => Stdcall, Link_Name => "CreateProcessW"; -- Terminate the windows process and all its threads. function Terminate_Process (Proc : in HANDLE; Code : in DWORD) return Integer with Import => True, Convention => Stdcall, Link_Name => "TerminateProcess"; function Sys_Stat (Path : in LPWSTR; Stat : access Util.Systems.Types.Stat_Type) return Integer with Import => True, Convention => Stdcall, Link_Name => "_stat64"; function Sys_Fstat (Fs : in File_Type; Stat : access Util.Systems.Types.Stat_Type) return Integer; function Sys_Lseek (Fs : in File_Type; Offset : in Util.Systems.Types.off_t; Mode : in Util.Systems.Types.Seek_Mode) return Util.Systems.Types.off_t; FILE_SHARE_WRITE : constant DWORD := 16#02#; FILE_SHARE_READ : constant DWORD := 16#01#; GENERIC_READ : constant DWORD := 16#80000000#; GENERIC_WRITE : constant DWORD := 16#40000000#; CREATE_NEW : constant DWORD := 1; CREATE_ALWAYS : constant DWORD := 2; OPEN_EXISTING : constant DWORD := 3; OPEN_ALWAYS : constant DWORD := 4; TRUNCATE_EXISTING : constant DWORD := 5; FILE_APPEND_DATA : constant DWORD := 4; FILE_ATTRIBUTE_ARCHIVE : constant DWORD := 16#20#; FILE_ATTRIBUTE_HIDDEN : constant DWORD := 16#02#; FILE_ATTRIBUTE_NORMAL : constant DWORD := 16#80#; FILE_ATTRIBUTE_READONLY : constant DWORD := 16#01#; FILE_ATTRIBUTE_TEMPORARY : constant DWORD := 16#100#; function Create_File (Name : in LPCTSTR; Desired_Access : in DWORD; Share_Mode : in DWORD; Attributes : in LPSECURITY_ATTRIBUTES; Creation : in DWORD; Flags : in DWORD; Template_File : HANDLE) return HANDLE with Import => True, Convention => Stdcall, Link_Name => "CreateFileW"; -- Close a file function Sys_Close (Fd : in File_Type) return Integer; -- Open a file function Sys_Open (Path : in Ptr; Flags : in Interfaces.C.int; Mode : in Util.Systems.Types.mode_t) return File_Type; function Sys_Ftruncate (Fs : in File_Type; Length : in Util.Systems.Types.off_t) return Integer; function Sys_Fchmod (Fd : in File_Type; Mode : in Util.Systems.Types.mode_t) return Integer; -- Change permission of a file. function Sys_Chmod (Path : in Ptr; Mode : in Util.Systems.Types.mode_t) return Integer with Import => True, Convention => Stdcall, Link_Name => "_chmod"; function Strerror (Errno : in Integer) return Interfaces.C.Strings.chars_ptr with Import => True, Convention => Stdcall, Link_Name => "strerror"; function Sys_GetHandleInformation (Fd : in HANDLE; Flags : access DWORD) return BOOL with Import => True, Convention => Stdcall, Link_Name => "GetHandleInformation"; type Wchar_Ptr is access all Interfaces.C.wchar_array; function To_WSTR (Value : in String) return Wchar_Ptr; procedure Free is new Ada.Unchecked_Deallocation (Object => Interfaces.C.wchar_array, Name => Wchar_Ptr); private -- kernel32 is used on Windows32 as well as Windows64. pragma Linker_Options ("-lkernel32"); end Util.Systems.Os;
----------------------------------------------------------------------- -- util-system-os -- Windows system operations -- Copyright (C) 2011, 2012, 2015, 2018, 2019, 2021 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Unchecked_Deallocation; with System; with Interfaces.C; with Interfaces.C.Strings; with Util.Systems.Types; with Util.Systems.Constants; -- The <b>Util.Systems.Os</b> package defines various types and operations which are specific -- to the OS (Windows). package Util.Systems.Os is -- The directory separator. Directory_Separator : constant Character := '\'; -- The path separator. Path_Separator : constant Character := ';'; -- The line ending separator. Line_Separator : constant String := "" & ASCII.CR & ASCII.LF; -- Defines several windows specific types. type BOOL is mod 8; type WORD is new Interfaces.C.short; type DWORD is new Interfaces.C.unsigned_long; type PDWORD is access all DWORD; for PDWORD'Size use Standard'Address_Size; function Get_Last_Error return Integer with Import => True, Convention => Stdcall, Link_Name => "GetLastError"; function Errno return Integer with Import => True, Convention => Stdcall, Link_Name => "GetLastError"; -- Some useful error codes (See Windows document "System Error Codes (0-499)"). ERROR_BROKEN_PIPE : constant Integer := 109; -- ------------------------------ -- Handle -- ------------------------------ -- The windows HANDLE is defined as a void* in the C API. subtype HANDLE is Util.Systems.Types.HANDLE; use type Util.Systems.Types.HANDLE; INVALID_HANDLE_VALUE : constant HANDLE := -1; type PHANDLE is access all HANDLE; for PHANDLE'Size use Standard'Address_Size; function Wait_For_Single_Object (H : in HANDLE; Time : in DWORD) return DWORD with Import => True, Convention => Stdcall, Link_Name => "WaitForSingleObject"; type Security_Attributes is record Length : DWORD; Security_Descriptor : System.Address; Inherit : Interfaces.C.int := 0; end record; type LPSECURITY_ATTRIBUTES is access all Security_Attributes; for LPSECURITY_ATTRIBUTES'Size use Standard'Address_Size; -- ------------------------------ -- File operations -- ------------------------------ subtype File_Type is Util.Systems.Types.File_Type; NO_FILE : constant File_Type := 0; STD_INPUT_HANDLE : constant DWORD := 16#fffffff6#; STD_OUTPUT_HANDLE : constant DWORD := 16#fffffff5#; STD_ERROR_HANDLE : constant DWORD := 16#fffffff4#; -- These values are specific to Linux. O_RDONLY : constant Interfaces.C.int := Util.Systems.Constants.O_RDONLY; O_WRONLY : constant Interfaces.C.int := Util.Systems.Constants.O_WRONLY; O_RDWR : constant Interfaces.C.int := Util.Systems.Constants.O_RDWR; O_CREAT : constant Interfaces.C.int := Util.Systems.Constants.O_CREAT; O_EXCL : constant Interfaces.C.int := Util.Systems.Constants.O_EXCL; O_TRUNC : constant Interfaces.C.int := Util.Systems.Constants.O_TRUNC; O_APPEND : constant Interfaces.C.int := Util.Systems.Constants.O_APPEND; function Get_Std_Handle (Kind : in DWORD) return File_Type with Import => True, Convention => Stdcall, Link_Name => "GetStdHandle"; function STDIN_FILENO return File_Type is (Get_Std_Handle (STD_INPUT_HANDLE)); function STDOUT_FILENO return File_Type is (Get_Std_Handle (STD_OUTPUT_HANDLE)); function STDERR_FILENO return File_Type is (Get_Std_Handle (STD_ERROR_HANDLE)); function Close_Handle (Fd : in File_Type) return BOOL with Import => True, Convention => Stdcall, Link_Name => "CloseHandle"; function Duplicate_Handle (SourceProcessHandle : in HANDLE; SourceHandle : in HANDLE; TargetProcessHandle : in HANDLE; TargetHandle : in PHANDLE; DesiredAccess : in DWORD; InheritHandle : in BOOL; Options : in DWORD) return BOOL with Import => True, Convention => Stdcall, Link_Name => "DuplicateHandle"; function Read_File (Fd : in File_Type; Buf : in System.Address; Size : in DWORD; Result : in PDWORD; Overlap : in System.Address) return BOOL with Import => True, Convention => Stdcall, Link_Name => "ReadFile"; function Write_File (Fd : in File_Type; Buf : in System.Address; Size : in DWORD; Result : in PDWORD; Overlap : in System.Address) return BOOL with Import => True, Convention => Stdcall, Link_Name => "WriteFile"; function Create_Pipe (Read_Handle : in PHANDLE; Write_Handle : in PHANDLE; Attributes : in LPSECURITY_ATTRIBUTES; Buf_Size : in DWORD) return BOOL with Import => True, Convention => Stdcall, Link_Name => "CreatePipe"; subtype LPWSTR is Interfaces.C.Strings.chars_ptr; subtype LPCSTR is Interfaces.C.Strings.chars_ptr; subtype PBYTE is Interfaces.C.Strings.chars_ptr; subtype Ptr is Interfaces.C.Strings.chars_ptr; subtype LPCTSTR is System.Address; subtype LPTSTR is System.Address; type CommandPtr is access all Interfaces.C.wchar_array; NULL_STR : constant LPWSTR := Interfaces.C.Strings.Null_Ptr; type FileTime is record dwLowDateTime : DWORD; dwHighDateTime : DWORD; end record; type LPFILETIME is access all FileTime; function To_Time (Time : in FileTime) return Util.Systems.Types.Time_Type; type Startup_Info is record cb : DWORD := 0; lpReserved : LPWSTR := NULL_STR; lpDesktop : LPWSTR := NULL_STR; lpTitle : LPWSTR := NULL_STR; dwX : DWORD := 0; dwY : DWORD := 0; dwXsize : DWORD := 0; dwYsize : DWORD := 0; dwXCountChars : DWORD := 0; dwYCountChars : DWORD := 0; dwFillAttribute : DWORD := 0; dwFlags : DWORD := 0; wShowWindow : WORD := 0; cbReserved2 : WORD := 0; lpReserved2 : PBYTE := Interfaces.C.Strings.Null_Ptr; hStdInput : HANDLE := 0; hStdOutput : HANDLE := 0; hStdError : HANDLE := 0; end record; type Startup_Info_Access is access all Startup_Info; type PROCESS_INFORMATION is record hProcess : HANDLE := NO_FILE; hThread : HANDLE := NO_FILE; dwProcessId : DWORD; dwThreadId : DWORD; end record; type Process_Information_Access is access all PROCESS_INFORMATION; function Get_Current_Process return HANDLE with Import => True, Convention => Stdcall, Link_Name => "GetCurrentProcess"; function Get_Exit_Code_Process (Proc : in HANDLE; Code : in PDWORD) return BOOL with Import => True, Convention => Stdcall, Link_Name => "GetExitCodeProcess"; function Create_Process (Name : in LPCTSTR; Command : in System.Address; Process_Attributes : in LPSECURITY_ATTRIBUTES; Thread_Attributes : in LPSECURITY_ATTRIBUTES; Inherit_Handles : in BOOL; Creation_Flags : in DWORD; Environment : in LPTSTR; Directory : in LPCTSTR; Startup_Info : in Startup_Info_Access; Process_Info : in Process_Information_Access) return Integer with Import => True, Convention => Stdcall, Link_Name => "CreateProcessW"; -- Terminate the windows process and all its threads. function Terminate_Process (Proc : in HANDLE; Code : in DWORD) return Integer with Import => True, Convention => Stdcall, Link_Name => "TerminateProcess"; function Sys_Stat (Path : in LPWSTR; Stat : access Util.Systems.Types.Stat_Type) return Integer with Import => True, Convention => Stdcall, Link_Name => "_stat64"; function Sys_Fstat (Fs : in File_Type; Stat : access Util.Systems.Types.Stat_Type) return Integer; function Sys_Lseek (Fs : in File_Type; Offset : in Util.Systems.Types.off_t; Mode : in Util.Systems.Types.Seek_Mode) return Util.Systems.Types.off_t; FILE_SHARE_WRITE : constant DWORD := 16#02#; FILE_SHARE_READ : constant DWORD := 16#01#; GENERIC_READ : constant DWORD := 16#80000000#; GENERIC_WRITE : constant DWORD := 16#40000000#; CREATE_NEW : constant DWORD := 1; CREATE_ALWAYS : constant DWORD := 2; OPEN_EXISTING : constant DWORD := 3; OPEN_ALWAYS : constant DWORD := 4; TRUNCATE_EXISTING : constant DWORD := 5; FILE_APPEND_DATA : constant DWORD := 4; FILE_ATTRIBUTE_ARCHIVE : constant DWORD := 16#20#; FILE_ATTRIBUTE_HIDDEN : constant DWORD := 16#02#; FILE_ATTRIBUTE_NORMAL : constant DWORD := 16#80#; FILE_ATTRIBUTE_READONLY : constant DWORD := 16#01#; FILE_ATTRIBUTE_TEMPORARY : constant DWORD := 16#100#; function Create_File (Name : in LPCTSTR; Desired_Access : in DWORD; Share_Mode : in DWORD; Attributes : in LPSECURITY_ATTRIBUTES; Creation : in DWORD; Flags : in DWORD; Template_File : HANDLE) return HANDLE with Import => True, Convention => Stdcall, Link_Name => "CreateFileW"; -- Close a file function Sys_Close (Fd : in File_Type) return Integer; -- Open a file function Sys_Open (Path : in Ptr; Flags : in Interfaces.C.int; Mode : in Util.Systems.Types.mode_t) return File_Type; function Sys_Ftruncate (Fs : in File_Type; Length : in Util.Systems.Types.off_t) return Integer; function Sys_Fchmod (Fd : in File_Type; Mode : in Util.Systems.Types.mode_t) return Integer; -- Change permission of a file. function Sys_Chmod (Path : in Ptr; Mode : in Util.Systems.Types.mode_t) return Integer with Import => True, Convention => Stdcall, Link_Name => "_chmod"; function Strerror (Errno : in Integer) return Interfaces.C.Strings.chars_ptr with Import => True, Convention => Stdcall, Link_Name => "strerror"; function Sys_GetHandleInformation (Fd : in HANDLE; Flags : access DWORD) return BOOL with Import => True, Convention => Stdcall, Link_Name => "GetHandleInformation"; type Wchar_Ptr is access all Interfaces.C.wchar_array; function To_WSTR (Value : in String) return Wchar_Ptr; procedure Free is new Ada.Unchecked_Deallocation (Object => Interfaces.C.wchar_array, Name => Wchar_Ptr); private -- kernel32 is used on Windows32 as well as Windows64. pragma Linker_Options ("-lkernel32"); end Util.Systems.Os;
Fix compilation warnings with GNAT 2021
Fix compilation warnings with GNAT 2021
Ada
apache-2.0
stcarrez/ada-util,stcarrez/ada-util
3c2138c442d22e61a7e7344e0263fa08eede427d
src/asf-lifecycles-response.adb
src/asf-lifecycles-response.adb
----------------------------------------------------------------------- -- asf-lifecycles-response -- Response phase -- Copyright (C) 2010, 2011, 2012, 2017 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Exceptions; with ASF.Applications.Main; with ASF.Components.Root; with ASF.Responses; with Util.Log.Loggers; -- The <b>ASF.Lifecycles.Response</b> package defines the behavior -- of the response phase. package body ASF.Lifecycles.Response is use Ada.Exceptions; use ASF.Applications; -- The logger Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("ASF.Lifecycles.Response"); -- ------------------------------ -- Initialize the phase controller. -- ------------------------------ overriding procedure Initialize (Controller : in out Response_Controller; App : access ASF.Applications.Main.Application'Class) is begin Controller.View_Handler := App.Get_View_Handler; end Initialize; -- ------------------------------ -- Execute the restore view phase. -- ------------------------------ overriding procedure Execute (Controller : in Response_Controller; Context : in out ASF.Contexts.Faces.Faces_Context'Class) is View : constant Components.Root.UIViewRoot := Context.Get_View_Root; begin if Components.Root.Get_Root (View) = null then Log.Warn ("Page not found: {0}", Context.Get_View_Name); Context.Get_Response.Send_Error (ASF.Responses.SC_NOT_FOUND); Context.Response_Completed; else Controller.View_Handler.Render_View (Context, View); end if; exception when E : others => Log.Error ("Error when displaying view {0}: {1}: {2}", "?", Exception_Name (E), Exception_Message (E)); raise; end Execute; end ASF.Lifecycles.Response;
----------------------------------------------------------------------- -- asf-lifecycles-response -- Response phase -- Copyright (C) 2010, 2011, 2012, 2017, 2018 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Exceptions; with ASF.Components.Root; with ASF.Responses; with Util.Log.Loggers; -- The <b>ASF.Lifecycles.Response</b> package defines the behavior -- of the response phase. package body ASF.Lifecycles.Response is use Ada.Exceptions; use ASF.Applications; -- The logger Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("ASF.Lifecycles.Response"); -- ------------------------------ -- Initialize the phase controller. -- ------------------------------ overriding procedure Initialize (Controller : in out Response_Controller; Views : access ASF.Applications.Views.View_Handler'Class) is begin Controller.View_Handler := Views; end Initialize; -- ------------------------------ -- Execute the restore view phase. -- ------------------------------ overriding procedure Execute (Controller : in Response_Controller; Context : in out ASF.Contexts.Faces.Faces_Context'Class) is View : constant Components.Root.UIViewRoot := Context.Get_View_Root; begin if Components.Root.Get_Root (View) = null then Log.Warn ("Page not found: {0}", Context.Get_View_Name); Context.Get_Response.Send_Error (ASF.Responses.SC_NOT_FOUND); Context.Response_Completed; else Controller.View_Handler.Render_View (Context, View); end if; exception when E : others => Log.Error ("Error when displaying view {0}: {1}: {2}", "?", Exception_Name (E), Exception_Message (E)); raise; end Execute; end ASF.Lifecycles.Response;
Update Initialize to use a ASF.Applications.Views.View_Handler'Class
Update Initialize to use a ASF.Applications.Views.View_Handler'Class
Ada
apache-2.0
stcarrez/ada-asf,stcarrez/ada-asf,stcarrez/ada-asf
fcae0477c2db50a9f3998482f82660991bebfdde
mat/src/events/mat-events-targets.adb
mat/src/events/mat-events-targets.adb
----------------------------------------------------------------------- -- mat-events-targets - Events received and collected from a target -- Copyright (C) 2014 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- package body MAT.Events.Targets is -- ------------------------------ -- Add the event in the list of events and increment the event counter. -- ------------------------------ procedure Insert (Target : in out Target_Events; Event : in Probe_Event_Type) is begin Target.Events.Insert (Event); Util.Concurrent.Counters.Increment (Target.Event_Count); end Insert; procedure Get_Events (Target : in out Target_Events; Start : in MAT.Types.Target_Time; Finish : in MAT.Types.Target_Time; Into : in out Target_Event_Vector) is begin Target.Events.Get_Events (Start, Finish, Into); end Get_Events; -- ------------------------------ -- Get the current event counter. -- ------------------------------ function Get_Event_Counter (Target : in Target_Events) return Integer is begin return Util.Concurrent.Counters.Value (Target.Event_Count); end Get_EVent_Counter; protected body Event_Collector is -- ------------------------------ -- Add the event in the list of events. -- ------------------------------ procedure Insert (Event : in Probe_Event_Type) is Info : Target_Event; begin if Current = null then Current := new Event_Block; Current.Start := Event.Time; Events.Insert (Event.Time, Current); end if; Current.Count := Current.Count + 1; Current.Events (Current.Count) := Event; Current.Finish := Event.Time; if Current.Count = Current.Events'Last then Current := null; end if; end Insert; procedure Get_Events (Start : in MAT.Types.Target_Time; Finish : in MAT.Types.Target_Time; Into : in out Target_Event_Vector) is Iter : Event_Cursor := Events.Floor (Start); Block : Event_Block_Access; begin while Event_Maps.Has_Element (Iter) loop Block := Event_Maps.Element (Iter); exit when Block.Start > Finish; for I in Block.Events'First .. Block.Count loop exit when Block.Events (I).Time > Finish; if Block.Events (I).Time >= Start then Into.Append (Block.Events (I)); end if; end loop; Event_Maps.Next (Iter); end loop; end Get_Events; end Event_Collector; end MAT.Events.Targets;
----------------------------------------------------------------------- -- mat-events-targets - Events received and collected from a target -- Copyright (C) 2014 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- package body MAT.Events.Targets is -- ------------------------------ -- Add the event in the list of events and increment the event counter. -- ------------------------------ procedure Insert (Target : in out Target_Events; Event : in Probe_Event_Type) is begin Target.Events.Insert (Event); Util.Concurrent.Counters.Increment (Target.Event_Count); end Insert; procedure Get_Events (Target : in out Target_Events; Start : in MAT.Types.Target_Time; Finish : in MAT.Types.Target_Time; Into : in out Target_Event_Vector) is begin Target.Events.Get_Events (Start, Finish, Into); end Get_Events; -- ------------------------------ -- Get the current event counter. -- ------------------------------ function Get_Event_Counter (Target : in Target_Events) return Integer is begin return Util.Concurrent.Counters.Value (Target.Event_Count); end Get_Event_Counter; protected body Event_Collector is -- ------------------------------ -- Add the event in the list of events. -- ------------------------------ procedure Insert (Event : in Probe_Event_Type) is Info : Target_Event; begin if Current = null then Current := new Event_Block; Current.Start := Event.Time; Events.Insert (Event.Time, Current); end if; Current.Count := Current.Count + 1; Current.Events (Current.Count) := Event; Current.Finish := Event.Time; if Current.Count = Current.Events'Last then Current := null; end if; end Insert; procedure Get_Events (Start : in MAT.Types.Target_Time; Finish : in MAT.Types.Target_Time; Into : in out Target_Event_Vector) is Iter : Event_Cursor := Events.Floor (Start); Block : Event_Block_Access; begin while Event_Maps.Has_Element (Iter) loop Block := Event_Maps.Element (Iter); exit when Block.Start > Finish; for I in Block.Events'First .. Block.Count loop exit when Block.Events (I).Time > Finish; if Block.Events (I).Time >= Start then Into.Append (Block.Events (I)); end if; end loop; Event_Maps.Next (Iter); end loop; end Get_Events; -- ------------------------------ -- Get the start and finish time for the events that have been received. -- ------------------------------ procedure Get_Time_Range (Start : out MAT.Types.Target_Time; Finish : out MAT.Types.Target_Time) is First : constant Event_Block_Access := Events.First_Element; Last : constant Event_Block_Access := Events.Last_Element; begin Start := First.Events (First.Events'First).Time; Finish := Last.Events (Last.Count).Time; end Get_Time_Range; end Event_Collector; end MAT.Events.Targets;
Implement the Get_Time_Range protected procedure
Implement the Get_Time_Range protected procedure
Ada
apache-2.0
stcarrez/mat,stcarrez/mat,stcarrez/mat
0566aa05ce2915265d73e4255cea1082d51f99c6
mat/src/memory/mat-memory-targets.adb
mat/src/memory/mat-memory-targets.adb
----------------------------------------------------------------------- -- Memory Events - Definition and Analysis of memory events -- Copyright (C) 2014 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Log.Loggers; with MAT.Memory.Readers; package body MAT.Memory.Targets is -- The logger Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("MAT.Memory.Targets"); -- ------------------------------ -- Initialize the target memory object to manage the memory slots, the stack frames -- and setup the reader to analyze the memory events. -- ------------------------------ procedure Initialize (Memory : in out Target_Memory; Reader : in out MAT.Readers.Manager_Base'Class) is Memory_Reader : constant MAT.Memory.Readers.Memory_Reader_Access := new MAT.Memory.Readers.Memory_Servant; begin Memory.Reader := Memory_Reader.all'Access; Memory_Reader.Data := Memory'Unrestricted_Access; Memory.Frames := Frames.Create_Root; MAT.Memory.Readers.Register (Reader, Memory_Reader); end Initialize; -- ------------------------------ -- Collect the information about memory slot sizes allocated by the application. -- ------------------------------ procedure Size_Information (Memory : in Target_Memory; Sizes : in out Size_Info_Map) is Iter : Allocation_Cursor := Memory.Memory_Slots.First; procedure Update_Count (Size : in MAT.Types.Target_Size; Info : in out Size_Info_Type) is begin Info.Count := Info.Count + 1; end Update_Count; procedure Collect (Addr : in MAT.Types.Target_Addr; Slot : in Allocation) is Pos : Size_Info_Cursor := Sizes.Find (Slot.Size); begin if Size_Info_Maps.Has_Element (Pos) then Sizes.Update_Element (Pos, Update_Count'Access); else declare Info : Size_Info_Type; begin Info.Count := 1; Sizes.Insert (Slot.Size, Info); end; end if; end Collect; begin while Allocation_Maps.Has_Element (Iter) loop Allocation_Maps.Query_Element (Iter, Collect'Access); Allocation_Maps.Next (Iter); end loop; end Size_Information; protected body Memory_Allocator is -- ------------------------------ -- Take into account a malloc probe. The memory slot [Addr .. Slot.Size] is inserted -- in the used slots map. The freed slots that intersect the malloc'ed region are -- removed from the freed map. -- ------------------------------ procedure Probe_Malloc (Addr : in MAT.Types.Target_Addr; Slot : in Allocation) is Iter : Allocation_Cursor; Last : constant MAT.Types.Target_Addr := Addr + MAT.Types.Target_Addr (Slot.Size); Item : Allocation; begin -- Walk the list of free blocks and remove all the blocks which intersect the region -- [Addr .. Addr + Slot.Size]. We start walking at the first block below and near -- the address. Slots are then removed when they intersect the malloc'ed region. Iter := Freed_Slots.Floor (Addr); while Allocation_Maps.Has_Element (Iter) loop declare Freed_Addr : constant MAT.Types.Target_Addr := Allocation_Maps.Key (Iter); begin exit when Freed_Addr > Last; Item := Allocation_Maps.Element (Iter); if Freed_Addr + MAT.Types.Target_Addr (Item.Size) > Addr then Freed_Slots.Delete (Iter); Iter := Freed_Slots.Floor (Addr); else Allocation_Maps.Next (Iter); end if; end; end loop; Used_Slots.Insert (Addr, Slot); end Probe_Malloc; -- ------------------------------ -- Take into account a free probe. Add the memory slot in the freed map and remove -- the slot from the used slots map. -- ------------------------------ procedure Probe_Free (Addr : in MAT.Types.Target_Addr; Slot : in Allocation) is Item : Allocation; Iter : Allocation_Cursor; begin Iter := Used_Slots.Find (Addr); if Allocation_Maps.Has_Element (Iter) then Item := Allocation_Maps.Element (Iter); MAT.Frames.Release (Item.Frame); Used_Slots.Delete (Iter); Item.Frame := Slot.Frame; Freed_Slots.Insert (Addr, Item); end if; end Probe_Free; end Memory_Allocator; end MAT.Memory.Targets;
----------------------------------------------------------------------- -- Memory Events - Definition and Analysis of memory events -- Copyright (C) 2014 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Log.Loggers; with MAT.Memory.Readers; package body MAT.Memory.Targets is -- The logger Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("MAT.Memory.Targets"); -- ------------------------------ -- Initialize the target memory object to manage the memory slots, the stack frames -- and setup the reader to analyze the memory events. -- ------------------------------ procedure Initialize (Memory : in out Target_Memory; Reader : in out MAT.Readers.Manager_Base'Class) is Memory_Reader : constant MAT.Memory.Readers.Memory_Reader_Access := new MAT.Memory.Readers.Memory_Servant; begin Memory.Reader := Memory_Reader.all'Access; Memory_Reader.Data := Memory'Unrestricted_Access; Memory.Frames := Frames.Create_Root; MAT.Memory.Readers.Register (Reader, Memory_Reader); end Initialize; -- ------------------------------ -- Collect the information about memory slot sizes allocated by the application. -- ------------------------------ procedure Size_Information (Memory : in Target_Memory; Sizes : in out Size_Info_Map) is Iter : Allocation_Cursor := Memory.Memory_Slots.First; procedure Update_Count (Size : in MAT.Types.Target_Size; Info : in out Size_Info_Type) is begin Info.Count := Info.Count + 1; end Update_Count; procedure Collect (Addr : in MAT.Types.Target_Addr; Slot : in Allocation) is Pos : Size_Info_Cursor := Sizes.Find (Slot.Size); begin if Size_Info_Maps.Has_Element (Pos) then Sizes.Update_Element (Pos, Update_Count'Access); else declare Info : Size_Info_Type; begin Info.Count := 1; Sizes.Insert (Slot.Size, Info); end; end if; end Collect; begin while Allocation_Maps.Has_Element (Iter) loop Allocation_Maps.Query_Element (Iter, Collect'Access); Allocation_Maps.Next (Iter); end loop; end Size_Information; protected body Memory_Allocator is -- ------------------------------ -- Remove the memory region [Addr .. Addr + Size] from the free list. -- ------------------------------ procedure Remove_Free (Addr : in MAT.Types.Target_Addr; Size : in MAT.Types.Target_Size) is Iter : Allocation_Cursor; Last : constant MAT.Types.Target_Addr := Addr + MAT.Types.Target_Addr (Size); Slot : Allocation; begin -- Walk the list of free blocks and remove all the blocks which intersect the region -- [Addr .. Addr + Slot.Size]. We start walking at the first block below and near -- the address. Slots are then removed when they intersect the malloc'ed region. Iter := Freed_Slots.Floor (Addr); while Allocation_Maps.Has_Element (Iter) loop declare Freed_Addr : constant MAT.Types.Target_Addr := Allocation_Maps.Key (Iter); begin exit when Freed_Addr > Last; Slot := Allocation_Maps.Element (Iter); if Freed_Addr + MAT.Types.Target_Addr (Slot.Size) > Addr then Freed_Slots.Delete (Iter); Iter := Freed_Slots.Floor (Addr); else Allocation_Maps.Next (Iter); end if; end; end loop; end Remove_Free; -- ------------------------------ -- Take into account a malloc probe. The memory slot [Addr .. Slot.Size] is inserted -- in the used slots map. The freed slots that intersect the malloc'ed region are -- removed from the freed map. -- ------------------------------ procedure Probe_Malloc (Addr : in MAT.Types.Target_Addr; Slot : in Allocation) is begin Remove_Free (Addr, Slot.Size); Used_Slots.Insert (Addr, Slot); end Probe_Malloc; -- ------------------------------ -- Take into account a free probe. Add the memory slot in the freed map and remove -- the slot from the used slots map. -- ------------------------------ procedure Probe_Free (Addr : in MAT.Types.Target_Addr; Slot : in Allocation) is Item : Allocation; Iter : Allocation_Cursor; begin Iter := Used_Slots.Find (Addr); if Allocation_Maps.Has_Element (Iter) then Item := Allocation_Maps.Element (Iter); MAT.Frames.Release (Item.Frame); Used_Slots.Delete (Iter); Item.Frame := Slot.Frame; Freed_Slots.Insert (Addr, Item); end if; end Probe_Free; -- ------------------------------ -- Take into account a realloc probe. The old memory slot represented by Old_Addr is -- removed from the used slots maps and the new memory slot [Addr .. Slot.Size] is -- inserted in the used slots map. -- ------------------------------ procedure Probe_Realloc (Addr : in MAT.Types.Target_Addr; Old_Addr : in MAT.Types.Target_Addr; Slot : in Allocation) is Old_Slot : Allocation; Pos : Allocation_Cursor; procedure Update_Size (Key : in MAT.Types.Target_Addr; Element : in out Allocation) is begin Element.Size := Slot.Size; MAT.Frames.Release (Element.Frame); Element.Frame := Slot.Frame; end Update_Size; begin if Old_Addr /= 0 then Pos := Used_Slots.Find (Old_Addr); if Allocation_Maps.Has_Element (Pos) then if Addr = Old_Addr then Used_Slots.Update_Element (Pos, Update_Size'Access); else Used_Slots.Delete (Pos); Used_Slots.Insert (Addr, Slot); end if; else Used_Slots.Insert (Addr, Slot); end if; else Used_Slots.Insert (Addr, Slot); end if; Remove_Free (Addr, Slot.Size); end Probe_Realloc; end Memory_Allocator; end MAT.Memory.Targets;
Implement protected operation Probe_Realloc
Implement protected operation Probe_Realloc
Ada
apache-2.0
stcarrez/mat,stcarrez/mat,stcarrez/mat
e3d2f4ab571fb978974c7c0345a68e8d7986eb58
regtests/util-beans-objects-datasets-tests.adb
regtests/util-beans-objects-datasets-tests.adb
----------------------------------------------------------------------- -- util-beans-objects-datasets-tests -- Unit tests for dataset beans -- Copyright (C) 2013, 2015, 2017, 2021 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Test_Caller; package body Util.Beans.Objects.Datasets.Tests is package Caller is new Util.Test_Caller (Test, "Beans.Datasets"); procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is begin Caller.Add_Test (Suite, "Test Util.Beans.Objects.Datasets", Test_Fill_Dataset'Access); end Add_Tests; -- Test the creation, initialization and retrieval of dataset content. procedure Test_Fill_Dataset (T : in out Test) is procedure Fill (Row : in out Object_Array); Set : Dataset; procedure Fill (Row : in out Object_Array) is begin Row (Row'First) := To_Object (String '("john")); Row (Row'First + 1) := To_Object (String '("[email protected]")); Row (Row'First + 2) := To_Object (Set.Get_Count); end Fill; begin Set.Add_Column ("name"); Set.Add_Column ("email"); Set.Add_Column ("age"); for I in 1 .. 100 loop Set.Append (Fill'Access); end loop; Util.Tests.Assert_Equals (T, 100, Set.Get_Count, "Invalid number of rows"); for I in 1 .. 100 loop Set.Set_Row_Index (I); declare R : constant Object := Set.Get_Row; begin T.Assert (not Is_Null (R), "Row is null"); Util.Tests.Assert_Equals (T, "john", To_String (Get_Value (R, "name")), "Invalid 'name' attribute"); Util.Tests.Assert_Equals (T, I, To_Integer (Get_Value (R, "age")), "Invalid 'age' attribute"); end; end loop; end Test_Fill_Dataset; end Util.Beans.Objects.Datasets.Tests;
----------------------------------------------------------------------- -- util-beans-objects-datasets-tests -- Unit tests for dataset beans -- Copyright (C) 2013, 2015, 2017, 2021, 2022 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Test_Caller; with Util.Beans.Objects.Iterators; package body Util.Beans.Objects.Datasets.Tests is package Caller is new Util.Test_Caller (Test, "Beans.Datasets"); procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is begin Caller.Add_Test (Suite, "Test Util.Beans.Objects.Datasets", Test_Fill_Dataset'Access); end Add_Tests; -- Test the creation, initialization and retrieval of dataset content. procedure Test_Fill_Dataset (T : in out Test) is procedure Fill (Row : in out Object_Array); Set : aliased Dataset; procedure Fill (Row : in out Object_Array) is begin Row (Row'First) := To_Object (String '("john")); Row (Row'First + 1) := To_Object (String '("[email protected]")); Row (Row'First + 2) := To_Object (Set.Get_Count); end Fill; begin Set.Add_Column ("name"); Set.Add_Column ("email"); Set.Add_Column ("age"); for I in 1 .. 100 loop Set.Append (Fill'Access); end loop; Util.Tests.Assert_Equals (T, 100, Set.Get_Count, "Invalid number of rows"); for I in 1 .. 100 loop Set.Set_Row_Index (I); declare R : constant Object := Set.Get_Row; begin T.Assert (not Is_Null (R), "Row is null"); Util.Tests.Assert_Equals (T, "john", To_String (Get_Value (R, "name")), "Invalid 'name' attribute"); Util.Tests.Assert_Equals (T, I, To_Integer (Get_Value (R, "age")), "Invalid 'age' attribute"); end; end loop; declare List : constant Object := To_Object (Set'Unchecked_Access, STATIC); Iter : Iterators.Iterator := Iterators.First (List); Count : Natural := 0; begin while Iterators.Has_Element (Iter) loop Count := Count + 1; declare R : constant Object := Iterators.Element (Iter); begin T.Assert (not Is_Null (R), "Row is null"); Util.Tests.Assert_Equals (T, "john", To_String (Get_Value (R, "name")), "Invalid 'name' attribute"); Util.Tests.Assert_Equals (T, Count, To_Integer (Get_Value (R, "age")), "Invalid 'age' attribute"); end; Iterators.Next (Iter); end loop; Util.Tests.Assert_Equals (T, 100, Count, "Invalid number of rows"); end; end Test_Fill_Dataset; end Util.Beans.Objects.Datasets.Tests;
Add a test for the iterator on datasets
Add a test for the iterator on datasets
Ada
apache-2.0
stcarrez/ada-util,stcarrez/ada-util
c1ba7fb62f84712593d240a7d2fe94504aff26fc
src/security-policies-roles.adb
src/security-policies-roles.adb
----------------------------------------------------------------------- -- security-policies-roles -- Role based policies -- Copyright (C) 2010, 2011, 2012 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Log.Loggers; with Util.Serialize.Mappers.Record_Mapper; with Security.Controllers; with Security.Controllers.Roles; package body Security.Policies.Roles is use Util.Log; -- The logger Log : constant Loggers.Logger := Loggers.Create ("Security.Policies.Roles"); -- ------------------------------ -- Get the policy name. -- ------------------------------ overriding function Get_Name (From : in Role_Policy) return String is pragma Unreferenced (From); begin return "role"; end Get_Name; -- ------------------------------ -- Get the role name. -- ------------------------------ function Get_Role_Name (Manager : in Role_Policy; Role : in Role_Type) return String is use type Ada.Strings.Unbounded.String_Access; begin if Manager.Names (Role) = null then return ""; else return Manager.Names (Role).all; end if; end Get_Role_Name; -- ------------------------------ -- Find the role type associated with the role name identified by <b>Name</b>. -- Raises <b>Invalid_Name</b> if there is no role type. -- ------------------------------ function Find_Role (Manager : in Role_Policy; Name : in String) return Role_Type is use type Ada.Strings.Unbounded.String_Access; begin Log.Debug ("Searching role {0}", Name); for I in Role_Type'First .. Manager.Next_Role loop exit when Manager.Names (I) = null; if Name = Manager.Names (I).all then return I; end if; end loop; Log.Debug ("Role {0} not found", Name); raise Invalid_Name; end Find_Role; -- ------------------------------ -- Create a role -- ------------------------------ procedure Create_Role (Manager : in out Role_Policy; Name : in String; Role : out Role_Type) is begin Role := Manager.Next_Role; Log.Info ("Role {0} is {1}", Name, Role_Type'Image (Role)); if Manager.Next_Role = Role_Type'Last then Log.Error ("Too many roles allocated. Number of roles is {0}", Role_Type'Image (Role_Type'Last)); else Manager.Next_Role := Manager.Next_Role + 1; end if; Manager.Names (Role) := new String '(Name); end Create_Role; -- ------------------------------ -- Get or build a permission type for the given name. -- ------------------------------ procedure Add_Role_Type (Manager : in out Role_Policy; Name : in String; Result : out Role_Type) is begin Result := Manager.Find_Role (Name); exception when Invalid_Name => Manager.Create_Role (Name, Result); end Add_Role_Type; type Config_Fields is (FIELD_NAME, FIELD_ROLE, FIELD_ROLE_PERMISSION, FIELD_ROLE_NAME); type Controller_Config_Access is access all Controller_Config; procedure Set_Member (Into : in out Controller_Config; Field : in Config_Fields; Value : in Util.Beans.Objects.Object); -- ------------------------------ -- Called while parsing the XML policy file when the <name>, <role> and <role-permission> -- XML entities are found. Create the new permission when the complete permission definition -- has been parsed and save the permission in the security manager. -- ------------------------------ procedure Set_Member (Into : in out Controller_Config; Field : in Config_Fields; Value : in Util.Beans.Objects.Object) is use Security.Controllers.Roles; begin case Field is when FIELD_NAME => Into.Name := Value; when FIELD_ROLE => declare Role : constant String := Util.Beans.Objects.To_String (Value); begin Into.Roles (Into.Count + 1) := Into.Manager.Find_Role (Role); Into.Count := Into.Count + 1; exception when Permissions.Invalid_Name => raise Util.Serialize.Mappers.Field_Error with "Invalid role: " & Role; end; when FIELD_ROLE_PERMISSION => if Into.Count = 0 then raise Util.Serialize.Mappers.Field_Error with "Missing at least one role"; end if; declare Name : constant String := Util.Beans.Objects.To_String (Into.Name); Perm : constant Role_Controller_Access := new Role_Controller '(Count => Into.Count, Roles => Into.Roles (1 .. Into.Count)); begin Into.Manager.Add_Permission (Name, Perm.all'Access); Into.Count := 0; end; when FIELD_ROLE_NAME => declare Name : constant String := Util.Beans.Objects.To_String (Value); Role : Role_Type; begin Into.Manager.Add_Role_Type (Name, Role); end; end case; end Set_Member; package Config_Mapper is new Util.Serialize.Mappers.Record_Mapper (Element_Type => Controller_Config, Element_Type_Access => Controller_Config_Access, Fields => Config_Fields, Set_Member => Set_Member); Mapper : aliased Config_Mapper.Mapper; -- ------------------------------ -- Setup the XML parser to read the <b>role-permission</b> description. -- ------------------------------ procedure Set_Reader_Config (Policy : in out Role_Policy; Reader : in out Util.Serialize.IO.XML.Parser) is Config : Controller_Config_Access := new Controller_Config; begin Reader.Add_Mapping ("policy-rules", Mapper'Access); Reader.Add_Mapping ("module", Mapper'Access); Config.Manager := Policy'Unchecked_Access; Config_Mapper.Set_Context (Reader, Config); end Set_Reader_Config; begin Mapper.Add_Mapping ("role-permission", FIELD_ROLE_PERMISSION); Mapper.Add_Mapping ("role-permission/name", FIELD_NAME); Mapper.Add_Mapping ("role-permission/role", FIELD_ROLE); Mapper.Add_Mapping ("security-role/role-name", FIELD_ROLE_NAME); end Security.Policies.Roles;
----------------------------------------------------------------------- -- security-policies-roles -- Role based policies -- Copyright (C) 2010, 2011, 2012 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Log.Loggers; with Util.Serialize.Mappers.Record_Mapper; with Security.Controllers; with Security.Controllers.Roles; package body Security.Policies.Roles is use Util.Log; -- The logger Log : constant Loggers.Logger := Loggers.Create ("Security.Policies.Roles"); -- ------------------------------ -- Get the policy name. -- ------------------------------ overriding function Get_Name (From : in Role_Policy) return String is pragma Unreferenced (From); begin return "role"; end Get_Name; -- ------------------------------ -- Get the role name. -- ------------------------------ function Get_Role_Name (Manager : in Role_Policy; Role : in Role_Type) return String is use type Ada.Strings.Unbounded.String_Access; begin if Manager.Names (Role) = null then return ""; else return Manager.Names (Role).all; end if; end Get_Role_Name; -- ------------------------------ -- Find the role type associated with the role name identified by <b>Name</b>. -- Raises <b>Invalid_Name</b> if there is no role type. -- ------------------------------ function Find_Role (Manager : in Role_Policy; Name : in String) return Role_Type is use type Ada.Strings.Unbounded.String_Access; begin Log.Debug ("Searching role {0}", Name); for I in Role_Type'First .. Manager.Next_Role loop exit when Manager.Names (I) = null; if Name = Manager.Names (I).all then return I; end if; end loop; Log.Debug ("Role {0} not found", Name); raise Invalid_Name; end Find_Role; -- ------------------------------ -- Create a role -- ------------------------------ procedure Create_Role (Manager : in out Role_Policy; Name : in String; Role : out Role_Type) is begin Role := Manager.Next_Role; Log.Info ("Role {0} is {1}", Name, Role_Type'Image (Role)); if Manager.Next_Role = Role_Type'Last then Log.Error ("Too many roles allocated. Number of roles is {0}", Role_Type'Image (Role_Type'Last)); else Manager.Next_Role := Manager.Next_Role + 1; end if; Manager.Names (Role) := new String '(Name); end Create_Role; -- ------------------------------ -- Get or build a permission type for the given name. -- ------------------------------ procedure Add_Role_Type (Manager : in out Role_Policy; Name : in String; Result : out Role_Type) is begin Result := Manager.Find_Role (Name); exception when Invalid_Name => Manager.Create_Role (Name, Result); end Add_Role_Type; type Config_Fields is (FIELD_NAME, FIELD_ROLE, FIELD_ROLE_PERMISSION, FIELD_ROLE_NAME); type Controller_Config_Access is access all Controller_Config; procedure Set_Member (Into : in out Controller_Config; Field : in Config_Fields; Value : in Util.Beans.Objects.Object); -- ------------------------------ -- Called while parsing the XML policy file when the <name>, <role> and <role-permission> -- XML entities are found. Create the new permission when the complete permission definition -- has been parsed and save the permission in the security manager. -- ------------------------------ procedure Set_Member (Into : in out Controller_Config; Field : in Config_Fields; Value : in Util.Beans.Objects.Object) is use Security.Controllers.Roles; begin case Field is when FIELD_NAME => Into.Name := Value; when FIELD_ROLE => declare Role : constant String := Util.Beans.Objects.To_String (Value); begin Into.Roles (Into.Count + 1) := Into.Manager.Find_Role (Role); Into.Count := Into.Count + 1; exception when Permissions.Invalid_Name => raise Util.Serialize.Mappers.Field_Error with "Invalid role: " & Role; end; when FIELD_ROLE_PERMISSION => if Into.Count = 0 then raise Util.Serialize.Mappers.Field_Error with "Missing at least one role"; end if; declare Name : constant String := Util.Beans.Objects.To_String (Into.Name); Perm : constant Role_Controller_Access := new Role_Controller '(Count => Into.Count, Roles => Into.Roles (1 .. Into.Count)); begin Into.Manager.Add_Permission (Name, Perm.all'Access); Into.Count := 0; end; when FIELD_ROLE_NAME => declare Name : constant String := Util.Beans.Objects.To_String (Value); Role : Role_Type; begin Into.Manager.Add_Role_Type (Name, Role); end; end case; end Set_Member; package Config_Mapper is new Util.Serialize.Mappers.Record_Mapper (Element_Type => Controller_Config, Element_Type_Access => Controller_Config_Access, Fields => Config_Fields, Set_Member => Set_Member); Mapper : aliased Config_Mapper.Mapper; -- ------------------------------ -- Setup the XML parser to read the <b>role-permission</b> description. -- ------------------------------ procedure Prepare_Config (Policy : in out Role_Policy; Reader : in out Util.Serialize.IO.XML.Parser) is Config : Controller_Config_Access := new Controller_Config; begin Reader.Add_Mapping ("policy-rules", Mapper'Access); Reader.Add_Mapping ("module", Mapper'Access); Config.Manager := Policy'Unchecked_Access; Config_Mapper.Set_Context (Reader, Config); end Prepare_Config; begin Mapper.Add_Mapping ("role-permission", FIELD_ROLE_PERMISSION); Mapper.Add_Mapping ("role-permission/name", FIELD_NAME); Mapper.Add_Mapping ("role-permission/role", FIELD_ROLE); Mapper.Add_Mapping ("security-role/role-name", FIELD_ROLE_NAME); end Security.Policies.Roles;
Rename Set_Reader_Config into Prepare_Config
Rename Set_Reader_Config into Prepare_Config
Ada
apache-2.0
Letractively/ada-security
85eaf228dd4f9036c7cebf408de6543419cedcf8
src/security-policies-roles.ads
src/security-policies-roles.ads
----------------------------------------------------------------------- -- security-policies-roles -- Role based policies -- Copyright (C) 2010, 2011, 2012 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Strings.Unbounded; -- == Role Based Security Policy == -- The <tt>Security.Policies.Roles</tt> package implements a role based security policy. -- In this policy, users are assigned one or several roles and permissions are -- associated with roles. A permission is granted if the user has one of the roles required -- by the permission. -- -- === Policy creation === -- An instance of the <tt>Role_Policy</tt> must be created and registered in the policy manager. -- Get or declare the following variables: -- -- Manager : Security.Policies.Policy_Manager; -- Policy : Security.Policies.Roles.Role_Policy_Access; -- -- Create the role policy and register it in the policy manager as follows: -- -- Policy := new Role_Policy; -- Manager.Add_Policy (Policy.all'Access); -- -- === Policy Configuration === -- A role is represented by a name in security configuration files. A role based permission -- is associated with a list of roles. The permission is granted if the user has one of these -- roles. When the role based policy is registered in the policy manager, the following -- XML configuration is used: -- -- <security-role> -- <role-name>admin</role-name> -- </security-role> -- <security-role> -- <role-name>manager</role-name> -- </security-role> -- <role-permission> -- <name>create-workspace</name> -- <role>admin</role> -- <role>manager</role> -- </role-permission> -- -- This definition declares two roles: <tt>admin</tt> and <tt>manager</tt> -- It defines a permission <b>create-workspace</b> that will be granted if the -- user has either the <b>admin</b> or the <b>manager</b> role. -- -- Each role is identified by a name in the configuration file. It is represented by -- a <tt>Role_Type</tt>. To provide an efficient implementation, the <tt>Role_Type</tt> -- is represented as an integer with a limit of 64 different roles. -- -- === Assigning roles to users === -- A <tt>Security_Context</tt> must be associated with a set of roles before checking the -- permission. This is done by using the <tt>Set_Role_Context</tt> operation: -- -- Security.Policies.Roles.Set_Role_Context (Security.Contexts.Current, "admin"); -- package Security.Policies.Roles is NAME : constant String := "Role-Policy"; -- Each role is represented by a <b>Role_Type</b> number to provide a fast -- and efficient role check. type Role_Type is new Natural range 0 .. 63; for Role_Type'Size use 8; type Role_Type_Array is array (Positive range <>) of Role_Type; -- The <b>Role_Map</b> represents a set of roles which are assigned to a user. -- Each role is represented by a boolean in the map. The implementation is limited -- to 64 roles (the number of different permissions can be higher). type Role_Map is array (Role_Type'Range) of Boolean; pragma Pack (Role_Map); -- ------------------------------ -- Role principal context -- ------------------------------ -- The <tt>Role_Principal_Context</tt> interface must be implemented by the user -- <tt>Principal</tt> to be able to use the role based policy. The role based policy -- controller will first check that the <tt>Principal</tt> implements that interface. -- It uses the <tt>Get_Roles</tt> function to get the current roles assigned to the user. type Role_Principal_Context is limited interface; function Get_Roles (User : in Role_Principal_Context) return Role_Map is abstract; -- ------------------------------ -- Policy context -- ------------------------------ -- The <b>Role_Policy_Context</b> gives security context information that the role -- based policy can use to verify the permission. type Role_Policy_Context is new Policy_Context with record Roles : Role_Map; end record; type Role_Policy_Context_Access is access all Role_Policy_Context'Class; -- Set the roles which are assigned to the user in the security context. -- The role policy will use these roles to verify a permission. procedure Set_Role_Context (Context : in out Security.Contexts.Security_Context'Class; Roles : in Role_Map); -- Set the roles which are assigned to the user in the security context. -- The role policy will use these roles to verify a permission. procedure Set_Role_Context (Context : in out Security.Contexts.Security_Context'Class; Roles : in String); -- ------------------------------ -- Role based policy -- ------------------------------ type Role_Policy is new Policy with private; type Role_Policy_Access is access all Role_Policy'Class; Invalid_Name : exception; -- Get the policy name. overriding function Get_Name (From : in Role_Policy) return String; -- Find the role type associated with the role name identified by <b>Name</b>. -- Raises <b>Invalid_Name</b> if there is no role type. function Find_Role (Manager : in Role_Policy; Name : in String) return Role_Type; -- Get the role name. function Get_Role_Name (Manager : in Role_Policy; Role : in Role_Type) return String; -- Create a role procedure Create_Role (Manager : in out Role_Policy; Name : in String; Role : out Role_Type); -- Get or add a role type for the given name. procedure Add_Role_Type (Manager : in out Role_Policy; Name : in String; Result : out Role_Type); -- Set the roles specified in the <tt>Roles</tt> parameter. Each role is represented by -- its name and multiple roles are separated by ','. -- Raises Invalid_Name if a role was not found. procedure Set_Roles (Manager : in Role_Policy; Roles : in String; Into : out Role_Map); -- Setup the XML parser to read the <b>role-permission</b> description. overriding procedure Prepare_Config (Policy : in out Role_Policy; Reader : in out Util.Serialize.IO.XML.Parser); -- Finalize the policy manager. overriding procedure Finalize (Policy : in out Role_Policy); -- Get the role policy associated with the given policy manager. -- Returns the role policy instance or null if it was not registered in the policy manager. function Get_Role_Policy (Manager : in Security.Policies.Policy_Manager'Class) return Role_Policy_Access; private type Role_Name_Array is array (Role_Type'Range) of Ada.Strings.Unbounded.String_Access; type Role_Policy is new Policy with record Names : Role_Name_Array; Next_Role : Role_Type := Role_Type'First; end record; type Controller_Config is record Name : Util.Beans.Objects.Object; Roles : Role_Type_Array (1 .. Integer (Role_Type'Last)); Count : Natural := 0; Manager : Role_Policy_Access; end record; end Security.Policies.Roles;
----------------------------------------------------------------------- -- security-policies-roles -- Role based policies -- Copyright (C) 2010, 2011, 2012 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Strings.Unbounded; -- == Role Based Security Policy == -- The <tt>Security.Policies.Roles</tt> package implements a role based security policy. -- In this policy, users are assigned one or several roles and permissions are -- associated with roles. A permission is granted if the user has one of the roles required -- by the permission. -- -- === Policy creation === -- An instance of the <tt>Role_Policy</tt> must be created and registered in the policy manager. -- Get or declare the following variables: -- -- Manager : Security.Policies.Policy_Manager; -- Policy : Security.Policies.Roles.Role_Policy_Access; -- -- Create the role policy and register it in the policy manager as follows: -- -- Policy := new Role_Policy; -- Manager.Add_Policy (Policy.all'Access); -- -- === Policy Configuration === -- A role is represented by a name in security configuration files. A role based permission -- is associated with a list of roles. The permission is granted if the user has one of these -- roles. When the role based policy is registered in the policy manager, the following -- XML configuration is used: -- -- <policy-rules> -- <security-role> -- <role-name>admin</role-name> -- </security-role> -- <security-role> -- <role-name>manager</role-name> -- </security-role> -- <role-permission> -- <name>create-workspace</name> -- <role>admin</role> -- <role>manager</role> -- </role-permission> -- ... -- </policy-rules> -- -- This definition declares two roles: <tt>admin</tt> and <tt>manager</tt> -- It defines a permission <b>create-workspace</b> that will be granted if the -- user has either the <b>admin</b> or the <b>manager</b> role. -- -- Each role is identified by a name in the configuration file. It is represented by -- a <tt>Role_Type</tt>. To provide an efficient implementation, the <tt>Role_Type</tt> -- is represented as an integer with a limit of 64 different roles. -- -- === Assigning roles to users === -- A <tt>Security_Context</tt> must be associated with a set of roles before checking the -- permission. This is done by using the <tt>Set_Role_Context</tt> operation: -- -- Security.Policies.Roles.Set_Role_Context (Security.Contexts.Current, "admin"); -- package Security.Policies.Roles is NAME : constant String := "Role-Policy"; -- Each role is represented by a <b>Role_Type</b> number to provide a fast -- and efficient role check. type Role_Type is new Natural range 0 .. 63; for Role_Type'Size use 8; type Role_Type_Array is array (Positive range <>) of Role_Type; -- The <b>Role_Map</b> represents a set of roles which are assigned to a user. -- Each role is represented by a boolean in the map. The implementation is limited -- to 64 roles (the number of different permissions can be higher). type Role_Map is array (Role_Type'Range) of Boolean; pragma Pack (Role_Map); -- ------------------------------ -- Role principal context -- ------------------------------ -- The <tt>Role_Principal_Context</tt> interface must be implemented by the user -- <tt>Principal</tt> to be able to use the role based policy. The role based policy -- controller will first check that the <tt>Principal</tt> implements that interface. -- It uses the <tt>Get_Roles</tt> function to get the current roles assigned to the user. type Role_Principal_Context is limited interface; function Get_Roles (User : in Role_Principal_Context) return Role_Map is abstract; -- ------------------------------ -- Policy context -- ------------------------------ -- The <b>Role_Policy_Context</b> gives security context information that the role -- based policy can use to verify the permission. type Role_Policy_Context is new Policy_Context with record Roles : Role_Map; end record; type Role_Policy_Context_Access is access all Role_Policy_Context'Class; -- Set the roles which are assigned to the user in the security context. -- The role policy will use these roles to verify a permission. procedure Set_Role_Context (Context : in out Security.Contexts.Security_Context'Class; Roles : in Role_Map); -- Set the roles which are assigned to the user in the security context. -- The role policy will use these roles to verify a permission. procedure Set_Role_Context (Context : in out Security.Contexts.Security_Context'Class; Roles : in String); -- ------------------------------ -- Role based policy -- ------------------------------ type Role_Policy is new Policy with private; type Role_Policy_Access is access all Role_Policy'Class; Invalid_Name : exception; -- Get the policy name. overriding function Get_Name (From : in Role_Policy) return String; -- Find the role type associated with the role name identified by <b>Name</b>. -- Raises <b>Invalid_Name</b> if there is no role type. function Find_Role (Manager : in Role_Policy; Name : in String) return Role_Type; -- Get the role name. function Get_Role_Name (Manager : in Role_Policy; Role : in Role_Type) return String; -- Create a role procedure Create_Role (Manager : in out Role_Policy; Name : in String; Role : out Role_Type); -- Get or add a role type for the given name. procedure Add_Role_Type (Manager : in out Role_Policy; Name : in String; Result : out Role_Type); -- Set the roles specified in the <tt>Roles</tt> parameter. Each role is represented by -- its name and multiple roles are separated by ','. -- Raises Invalid_Name if a role was not found. procedure Set_Roles (Manager : in Role_Policy; Roles : in String; Into : out Role_Map); -- Setup the XML parser to read the <b>role-permission</b> description. overriding procedure Prepare_Config (Policy : in out Role_Policy; Reader : in out Util.Serialize.IO.XML.Parser); -- Finalize the policy manager. overriding procedure Finalize (Policy : in out Role_Policy); -- Get the role policy associated with the given policy manager. -- Returns the role policy instance or null if it was not registered in the policy manager. function Get_Role_Policy (Manager : in Security.Policies.Policy_Manager'Class) return Role_Policy_Access; private type Role_Name_Array is array (Role_Type'Range) of Ada.Strings.Unbounded.String_Access; type Role_Policy is new Policy with record Names : Role_Name_Array; Next_Role : Role_Type := Role_Type'First; end record; type Controller_Config is record Name : Util.Beans.Objects.Object; Roles : Role_Type_Array (1 .. Integer (Role_Type'Last)); Count : Natural := 0; Manager : Role_Policy_Access; end record; end Security.Policies.Roles;
Fix the XML documentation
Fix the XML documentation
Ada
apache-2.0
Letractively/ada-security
87c540bcd5b45dac30f344925e1e2489135ffe81
awa/src/awa-events.ads
awa/src/awa-events.ads
----------------------------------------------------------------------- -- awa-events -- AWA Events -- Copyright (C) 2012 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Strings; with Util.Events; with Util.Beans.Objects; with Util.Beans.Basic; with ASF.Applications; -- == Introduction == -- The <b>AWA.Events</b> package defines an event framework for modules to post events -- and have Ada bean methods be invoked when these events are dispatched. Subscription to -- events is done through configuration files. This allows to configure the modules and -- integrate them together easily at configuration time. -- -- Modules define the events that they can generate by instantiating the <b>Definition</b> -- package. This is a static definition of the event. Each event is given a unique name. -- -- package Event_New_User is new AWA.Events.Definition ("new-user"); -- -- The module can post an event to inform other modules or the system that a particular -- action occurred. The module creates the event instance of type <b>Module_Event</b> and -- populates that event with useful properties for event receivers. -- -- Event : AWA.Events.Module_Event; -- -- Event.Set_Event_Kind (Event_New_User.Kind); -- Event.Set_Parameter ("email", "[email protected]"); -- -- The module will post the event by using the <b>Send_Event</b> operation. -- -- Manager.Send_Event (Event); -- -- Modules or applications interested by a particular event will configure the event manager -- to dispatch the event to an Ada bean event action. The Ada bean is an object that must -- implement a procedure that matches the prototype: -- -- type Action_Bean is new Util.Beans.Basic.Readonly_Bean ...; -- procedure Action (Bean : in out Action_Bean; Event : in AWA.Events.Module_Event'Class); -- -- The Ada bean method and object are registered as other Ada beans. -- -- The configuration file indicates how to bind the Ada bean action and the event together. -- The action is specified using an EL Method Expression (See Ada EL or JSR 245). -- -- <on-event name="new_user"> -- <action>#{ada_bean.action}</action> -- </on-event> -- -- == Data Model == -- @include Queues.hbm.xml -- package AWA.Events is type Queue_Index is new Natural; type Event_Index is new Natural; -- ------------------------------ -- Event kind definition -- ------------------------------ -- This package must be instantiated for each event that a module can post. generic Name : String; package Definition is function Kind return Event_Index; pragma Inline_Always (Kind); end Definition; -- Exception raised if an event name is not found. Not_Found : exception; -- Identifies an invalid event. Invalid_Event : constant Event_Index := 0; -- Find the event runtime index given the event name. -- Raises Not_Found exception if the event name is not recognized. function Find_Event_Index (Name : in String) return Event_Index; -- ------------------------------ -- Module event -- ------------------------------ type Module_Event is new Util.Events.Event and Util.Beans.Basic.Readonly_Bean with private; type Module_Event_Access is access all Module_Event'Class; -- Set the event type which identifies the event. procedure Set_Event_Kind (Event : in out Module_Event; Kind : in Event_Index); -- Get the event type which identifies the event. function Get_Event_Kind (Event : in Module_Event) return Event_Index; -- Set a parameter on the message. procedure Set_Parameter (Event : in out Module_Event; Name : in String; Value : in String); -- Get the parameter with the given name. function Get_Parameter (Event : in Module_Event; Name : in String) return String; -- Get the value that corresponds to the parameter with the given name. overriding function Get_Value (Event : in Module_Event; Name : in String) return Util.Beans.Objects.Object; private type Module_Event is new Util.Events.Event and Util.Beans.Basic.Readonly_Bean with record Kind : Event_Index := Invalid_Event; Props : ASF.Applications.Config; end record; -- The index of the last event definition. Last_Event : Event_Index := 0; -- Get the event type name. function Get_Event_Type_Name (Index : in Event_Index) return Util.Strings.Name_Access; -- Make and return a copy of the event. function Copy (Event : in Module_Event) return Module_Event_Access; end AWA.Events;
----------------------------------------------------------------------- -- awa-events -- AWA Events -- Copyright (C) 2012 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Strings; with Util.Events; with Util.Beans.Objects; with Util.Beans.Basic; with ASF.Applications; -- == Introduction == -- The <b>AWA.Events</b> package defines an event framework for modules to post events -- and have Ada bean methods be invoked when these events are dispatched. Subscription to -- events is done through configuration files. This allows to configure the modules and -- integrate them together easily at configuration time. -- -- === Declaration === -- Modules define the events that they can generate by instantiating the <b>Definition</b> -- package. This is a static definition of the event. Each event is given a unique name. -- -- package Event_New_User is new AWA.Events.Definition ("new-user"); -- -- === Posting an event === -- The module can post an event to inform other modules or the system that a particular -- action occurred. The module creates the event instance of type <b>Module_Event</b> and -- populates that event with useful properties for event receivers. -- -- Event : AWA.Events.Module_Event; -- -- Event.Set_Event_Kind (Event_New_User.Kind); -- Event.Set_Parameter ("email", "[email protected]"); -- -- The module will post the event by using the <b>Send_Event</b> operation. -- -- Manager.Send_Event (Event); -- -- === Receiving an event === -- Modules or applications interested by a particular event will configure the event manager -- to dispatch the event to an Ada bean event action. The Ada bean is an object that must -- implement a procedure that matches the prototype: -- -- type Action_Bean is new Util.Beans.Basic.Readonly_Bean ...; -- procedure Action (Bean : in out Action_Bean; Event : in AWA.Events.Module_Event'Class); -- -- The Ada bean method and object are registered as other Ada beans. -- -- The configuration file indicates how to bind the Ada bean action and the event together. -- The action is specified using an EL Method Expression (See Ada EL or JSR 245). -- -- <on-event name="new_user"> -- <action>#{ada_bean.action}</action> -- </on-event> -- -- === Event queues and dispatchers === -- The *AWA.Events* framework posts events on queues and it uses a dispatcher to process them. -- There are two kinds of dispatchers: -- -- * Synchronous dispatcher process the event when it is posted. The task which posts -- the event invokes the Ada bean action. In this dispatching mode, there is no event queue. -- If the action method raises an exception, it will however be blocked. -- -- * Asynchronous dispatcher are executed by dedicated tasks. The event is put in an event -- queue. A dispatcher task processes the event and invokes the action method at a later -- time. -- -- When the event is queued, there are two types of event queues: -- -- * A Fifo memory queue manages the event and dispatches them in FIFO order. -- If the application is stopped, the events present in the Fifo queue are lost. -- -- * A persistent event queue manages the event in a similar way as the FIFO queue but -- saves them in the database. If the application is stopped, events that have not yet -- been processed will be dispatched when the application is started again. -- -- == Data Model == -- @include Queues.hbm.xml -- package AWA.Events is type Queue_Index is new Natural; type Event_Index is new Natural; -- ------------------------------ -- Event kind definition -- ------------------------------ -- This package must be instantiated for each event that a module can post. generic Name : String; package Definition is function Kind return Event_Index; pragma Inline_Always (Kind); end Definition; -- Exception raised if an event name is not found. Not_Found : exception; -- Identifies an invalid event. Invalid_Event : constant Event_Index := 0; -- Find the event runtime index given the event name. -- Raises Not_Found exception if the event name is not recognized. function Find_Event_Index (Name : in String) return Event_Index; -- ------------------------------ -- Module event -- ------------------------------ type Module_Event is new Util.Events.Event and Util.Beans.Basic.Readonly_Bean with private; type Module_Event_Access is access all Module_Event'Class; -- Set the event type which identifies the event. procedure Set_Event_Kind (Event : in out Module_Event; Kind : in Event_Index); -- Get the event type which identifies the event. function Get_Event_Kind (Event : in Module_Event) return Event_Index; -- Set a parameter on the message. procedure Set_Parameter (Event : in out Module_Event; Name : in String; Value : in String); -- Get the parameter with the given name. function Get_Parameter (Event : in Module_Event; Name : in String) return String; -- Get the value that corresponds to the parameter with the given name. overriding function Get_Value (Event : in Module_Event; Name : in String) return Util.Beans.Objects.Object; private type Module_Event is new Util.Events.Event and Util.Beans.Basic.Readonly_Bean with record Kind : Event_Index := Invalid_Event; Props : ASF.Applications.Config; end record; -- The index of the last event definition. Last_Event : Event_Index := 0; -- Get the event type name. function Get_Event_Type_Name (Index : in Event_Index) return Util.Strings.Name_Access; -- Make and return a copy of the event. function Copy (Event : in Module_Event) return Module_Event_Access; end AWA.Events;
Document the event queues and dispatchers
Document the event queues and dispatchers
Ada
apache-2.0
Letractively/ada-awa,tectronics/ada-awa,tectronics/ada-awa,Letractively/ada-awa,tectronics/ada-awa,Letractively/ada-awa
30508601eaaa3f4f338c7397eb276eeeef005d10
regtests/util-texts-builders_tests.ads
regtests/util-texts-builders_tests.ads
----------------------------------------------------------------------- -- util-texts-builders_tests -- Unit tests for text builders -- Copyright (C) 2013, 2016 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Tests; package Util.Texts.Builders_Tests is procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite); type Test is new Util.Tests.Test with null record; -- Test the length operation. procedure Test_Length (T : in out Test); -- Test the append operation. procedure Test_Append (T : in out Test); -- Test the iterate operation. procedure Test_Iterate (T : in out Test); -- Test the clear operation. procedure Test_Clear (T : in out Test); -- Test the tail operation. procedure Test_Tail (T : in out Test); -- Test the append and iterate performance. procedure Test_Perf (T : in out Test); end Util.Texts.Builders_Tests;
----------------------------------------------------------------------- -- util-texts-builders_tests -- Unit tests for text builders -- Copyright (C) 2013, 2016, 2022 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Tests; package Util.Texts.Builders_Tests is procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite); type Test is new Util.Tests.Test with null record; -- Test the length operation. procedure Test_Length (T : in out Test); -- Test the append operation. procedure Test_Append (T : in out Test); -- Test the iterate operation. procedure Test_Iterate (T : in out Test); -- Test the iterate operation. procedure Test_Inline_Iterate (T : in out Test); -- Test the clear operation. procedure Test_Clear (T : in out Test); -- Test the tail operation. procedure Test_Tail (T : in out Test); -- Test the append and iterate performance. procedure Test_Perf (T : in out Test); end Util.Texts.Builders_Tests;
Declare Test_Inline_Iterate procedure
Declare Test_Inline_Iterate procedure
Ada
apache-2.0
stcarrez/ada-util,stcarrez/ada-util
6ce2ccd08399ff7c0635bbdddd02c17e9fa2d3c7
mat/src/memory/mat-memory-tools.ads
mat/src/memory/mat-memory-tools.ads
----------------------------------------------------------------------- -- mat-memory-tools - Tools for memory maps -- Copyright (C) 2014 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Containers.Ordered_Maps; package MAT.Memory.Tools is type Size_Info_Type is record Count : Natural; end record; use type MAT.Types.Target_Size; package Size_Info_Maps is new Ada.Containers.Ordered_Maps (Key_Type => MAT.Types.Target_Size, Element_Type => Size_Info_Type); subtype Size_Info_Map is Size_Info_Maps.Map; subtype Size_Info_Cursor is Size_Info_Maps.Cursor; -- Collect the information about memory slot sizes for the memory slots in the map. procedure Size_Information (Memory : in MAT.Memory.Allocation_Map; Sizes : in out Size_Info_Map); -- Find from the <tt>Memory</tt> map the memory slots whose address intersects -- the region [From .. To] and add the memory slot in the <tt>Into</tt> list if -- it does not already contains the memory slot. procedure Find (Memory : in MAT.Memory.Allocation_Map; From : in MAT.Types.Target_Addr; To : in MAT.Types.Target_Addr; Into : in out MAT.Memory.Allocation_Map); end MAT.Memory.Tools;
----------------------------------------------------------------------- -- mat-memory-tools - Tools for memory maps -- Copyright (C) 2014 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Containers.Ordered_Maps; package MAT.Memory.Tools is type Size_Info_Type is record Count : Natural; end record; package Size_Info_Maps is new Ada.Containers.Ordered_Maps (Key_Type => MAT.Types.Target_Size, Element_Type => Size_Info_Type); subtype Size_Info_Map is Size_Info_Maps.Map; subtype Size_Info_Cursor is Size_Info_Maps.Cursor; -- Collect the information about memory slot sizes for the memory slots in the map. procedure Size_Information (Memory : in MAT.Memory.Allocation_Map; Sizes : in out Size_Info_Map); -- Find from the <tt>Memory</tt> map the memory slots whose address intersects -- the region [From .. To] and add the memory slot in the <tt>Into</tt> list if -- it does not already contains the memory slot. procedure Find (Memory : in MAT.Memory.Allocation_Map; From : in MAT.Types.Target_Addr; To : in MAT.Types.Target_Addr; Into : in out MAT.Memory.Allocation_Map); end MAT.Memory.Tools;
Fix compilation warning
Fix compilation warning
Ada
apache-2.0
stcarrez/mat,stcarrez/mat,stcarrez/mat
c40076ecf0ad5002d8dfefd625992f5497c1eee9
matp/regtests/mat-targets-tests.adb
matp/regtests/mat-targets-tests.adb
----------------------------------------------------------------------- -- mat-readers-tests -- Unit tests for MAT readers -- Copyright (C) 2014, 2015, 2019 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Test_Caller; with MAT.Readers.Streams.Files; package body MAT.Targets.Tests is package Caller is new Util.Test_Caller (Test, "Files"); procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is begin Caller.Add_Test (Suite, "Test MAT.Targets.Read_File", Test_Read_File'Access); Caller.Add_Test (Suite, "Test MAT.Types.Tick_Value", Test_Conversions'Access); end Add_Tests; -- ------------------------------ -- Test reading a file into a string -- Reads this ada source file and checks we have read it correctly -- ------------------------------ procedure Test_Read_File (T : in out Test) is pragma Unreferenced (T); Path : constant String := Util.Tests.Get_Test_Path ("regtests/files/file-v1.dat"); Target : MAT.Targets.Target_Type; Reader : MAT.Readers.Streams.Files.File_Reader_Type; begin Target.Initialize (Reader); Reader.Open (Path); Reader.Read_All; end Test_Read_File; -- ------------------------------ -- Test various type conversions. -- ------------------------------ procedure Test_Conversions (T : in out Test) is use MAT.Types; Time : MAT.Types.Target_Tick_Ref; begin Time := MAT.Types.Tick_Value ("1.1"); Util.Tests.Assert_Equals (T, 1, Natural (Time / 1_000000), "Invalid Tick_Value conversion"); Util.Tests.Assert_Equals (T, 100_000, Natural (Time mod 1_000000), "Invalid Tick_Value conversion"); Time := MAT.Types.Tick_Value ("12.001234"); Util.Tests.Assert_Equals (T, 12, Natural (Time / 1_000000), "Invalid Tick_Value conversion"); Util.Tests.Assert_Equals (T, 1_234, Natural (Time mod 1_000000), "Invalid Tick_Value conversion"); end Test_Conversions; end MAT.Targets.Tests;
----------------------------------------------------------------------- -- mat-readers-tests -- Unit tests for MAT readers -- Copyright (C) 2014, 2015, 2019, 2021 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Test_Caller; with MAT.Readers.Streams.Files; package body MAT.Targets.Tests is package Caller is new Util.Test_Caller (Test, "Files"); procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is begin Caller.Add_Test (Suite, "Test MAT.Targets.Read_File", Test_Read_File'Access); Caller.Add_Test (Suite, "Test MAT.Types.Tick_Value", Test_Conversions'Access); end Add_Tests; -- ------------------------------ -- Test reading a file into a string -- Reads this ada source file and checks we have read it correctly -- ------------------------------ procedure Test_Read_File (T : in out Test) is pragma Unreferenced (T); Path : constant String := Util.Tests.Get_Path ("regtests/files/file-v1.dat"); Target : MAT.Targets.Target_Type; Reader : MAT.Readers.Streams.Files.File_Reader_Type; begin Target.Initialize (Reader); Reader.Open (Path); Reader.Read_All; end Test_Read_File; -- ------------------------------ -- Test various type conversions. -- ------------------------------ procedure Test_Conversions (T : in out Test) is use MAT.Types; Time : MAT.Types.Target_Tick_Ref; begin Time := MAT.Types.Tick_Value ("1.1"); Util.Tests.Assert_Equals (T, 1, Natural (Time / 1_000000), "Invalid Tick_Value conversion"); Util.Tests.Assert_Equals (T, 100_000, Natural (Time mod 1_000000), "Invalid Tick_Value conversion"); Time := MAT.Types.Tick_Value ("12.001234"); Util.Tests.Assert_Equals (T, 12, Natural (Time / 1_000000), "Invalid Tick_Value conversion"); Util.Tests.Assert_Equals (T, 1_234, Natural (Time mod 1_000000), "Invalid Tick_Value conversion"); end Test_Conversions; end MAT.Targets.Tests;
Replace Get_Test_Path by Get_Path
Replace Get_Test_Path by Get_Path
Ada
apache-2.0
stcarrez/mat,stcarrez/mat,stcarrez/mat
7a3617b781f05e6f5017c6c8f7e3ced66aacb781
mat/src/events/mat-events-targets.ads
mat/src/events/mat-events-targets.ads
----------------------------------------------------------------------- -- mat-events-targets - Events received and collected from a target -- Copyright (C) 2014 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Containers.Ordered_Maps; with Ada.Containers.Vectors; with Util.Concurrent.Counters; with MAT.Frames; package MAT.Events.Targets is Not_Found : exception; type Event_Type is mod 16; type Probe_Index_Type is mod 16; type Event_Id_Type is new Natural; type Probe_Event_Type is record Id : Event_Id_Type; Event : MAT.Types.Uint16; Index : Probe_Index_Type; Time : MAT.Types.Target_Time; Thread : MAT.Types.Target_Thread_Ref; Frame : MAT.Frames.Frame_Type; Addr : MAT.Types.Target_Addr; Size : MAT.Types.Target_Size; Old_Addr : MAT.Types.Target_Addr; end record; subtype Target_Event is Probe_Event_Type; package Target_Event_Vectors is new Ada.Containers.Vectors (Positive, Target_Event); subtype Target_Event_Vector is Target_Event_Vectors.Vector; subtype Target_Event_Cursor is Target_Event_Vectors.Cursor; type Target_Events is tagged limited private; type Target_Events_Access is access all Target_Events'Class; -- Add the event in the list of events and increment the event counter. procedure Insert (Target : in out Target_Events; Event : in Probe_Event_Type); procedure Get_Events (Target : in out Target_Events; Start : in MAT.Types.Target_Time; Finish : in MAT.Types.Target_Time; Into : in out Target_Event_Vector); -- Get the start and finish time for the events that have been received. procedure Get_Time_Range (Target : in out Target_Events; Start : out MAT.Types.Target_Time; Finish : out MAT.Types.Target_Time); -- Get the current event counter. function Get_Event_Counter (Target : in Target_Events) return Integer; private EVENT_BLOCK_SIZE : constant Event_Id_Type := 1024; type Probe_Event_Array is array (1 .. EVENT_BLOCK_SIZE) of Probe_Event_Type; type Event_Block is record Start : MAT.Types.Target_Time; Finish : MAT.Types.Target_Time; Count : Event_Id_Type := 0; Events : Probe_Event_Array; end record; type Event_Block_Access is access all Event_Block; use type MAT.Types.Target_Time; package Event_Maps is new Ada.Containers.Ordered_Maps (Key_Type => MAT.Types.Target_Time, Element_Type => Event_Block_Access); subtype Event_Map is Event_Maps.Map; subtype Event_Cursor is Event_Maps.Cursor; package Event_Id_Maps is new Ada.Containers.Ordered_Maps (Key_Type => Event_Id_Type, Element_Type => Event_Block_Access); subtype Event_Id_Map is Event_Id_Maps.Map; subtype Event_Id_Cursor is Event_Id_Maps.Cursor; protected type Event_Collector is -- Add the event in the list of events. procedure Insert (Event : in Probe_Event_Type); procedure Get_Events (Start : in MAT.Types.Target_Time; Finish : in MAT.Types.Target_Time; Into : in out Target_Event_Vector); -- Get the start and finish time for the events that have been received. procedure Get_Time_Range (Start : out MAT.Types.Target_Time; Finish : out MAT.Types.Target_Time); -- Get the probe event with the given allocated unique id. function Get_Event (Id : in Event_Id_Type) return Probe_Event_Type; private Current : Event_Block_Access := null; Events : Event_Map; Ids : Event_Id_Map; Last_Id : Event_Id_Type := 0; end Event_Collector; type Target_Events is tagged limited record Events : Event_Collector; Event_Count : Util.Concurrent.Counters.Counter; end record; end MAT.Events.Targets;
----------------------------------------------------------------------- -- mat-events-targets - Events received and collected from a target -- Copyright (C) 2014 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Containers.Ordered_Maps; with Ada.Containers.Vectors; with Util.Concurrent.Counters; with MAT.Frames; package MAT.Events.Targets is Not_Found : exception; type Event_Type is mod 16; type Probe_Index_Type is mod 16; type Event_Id_Type is new Natural; type Probe_Event_Type is record Id : Event_Id_Type; Event : MAT.Types.Uint16; Index : Probe_Index_Type; Time : MAT.Types.Target_Time; Thread : MAT.Types.Target_Thread_Ref; Frame : MAT.Frames.Frame_Type; Addr : MAT.Types.Target_Addr; Size : MAT.Types.Target_Size; Old_Addr : MAT.Types.Target_Addr; end record; subtype Target_Event is Probe_Event_Type; package Target_Event_Vectors is new Ada.Containers.Vectors (Positive, Target_Event); subtype Target_Event_Vector is Target_Event_Vectors.Vector; subtype Target_Event_Cursor is Target_Event_Vectors.Cursor; type Target_Events is tagged limited private; type Target_Events_Access is access all Target_Events'Class; -- Add the event in the list of events and increment the event counter. procedure Insert (Target : in out Target_Events; Event : in Probe_Event_Type); procedure Get_Events (Target : in out Target_Events; Start : in MAT.Types.Target_Time; Finish : in MAT.Types.Target_Time; Into : in out Target_Event_Vector); -- Get the start and finish time for the events that have been received. procedure Get_Time_Range (Target : in out Target_Events; Start : out MAT.Types.Target_Time; Finish : out MAT.Types.Target_Time); -- Get the probe event with the given allocated unique id. function Get_Event (Target : in Target_Events; Id : in Event_Id_Type) return Probe_Event_Type; -- Get the current event counter. function Get_Event_Counter (Target : in Target_Events) return Integer; private EVENT_BLOCK_SIZE : constant Event_Id_Type := 1024; type Probe_Event_Array is array (1 .. EVENT_BLOCK_SIZE) of Probe_Event_Type; type Event_Block is record Start : MAT.Types.Target_Time; Finish : MAT.Types.Target_Time; Count : Event_Id_Type := 0; Events : Probe_Event_Array; end record; type Event_Block_Access is access all Event_Block; use type MAT.Types.Target_Time; package Event_Maps is new Ada.Containers.Ordered_Maps (Key_Type => MAT.Types.Target_Time, Element_Type => Event_Block_Access); subtype Event_Map is Event_Maps.Map; subtype Event_Cursor is Event_Maps.Cursor; package Event_Id_Maps is new Ada.Containers.Ordered_Maps (Key_Type => Event_Id_Type, Element_Type => Event_Block_Access); subtype Event_Id_Map is Event_Id_Maps.Map; subtype Event_Id_Cursor is Event_Id_Maps.Cursor; protected type Event_Collector is -- Add the event in the list of events. procedure Insert (Event : in Probe_Event_Type); procedure Get_Events (Start : in MAT.Types.Target_Time; Finish : in MAT.Types.Target_Time; Into : in out Target_Event_Vector); -- Get the start and finish time for the events that have been received. procedure Get_Time_Range (Start : out MAT.Types.Target_Time; Finish : out MAT.Types.Target_Time); -- Get the probe event with the given allocated unique id. function Get_Event (Id : in Event_Id_Type) return Probe_Event_Type; private Current : Event_Block_Access := null; Events : Event_Map; Ids : Event_Id_Map; Last_Id : Event_Id_Type := 0; end Event_Collector; type Target_Events is tagged limited record Events : Event_Collector; Event_Count : Util.Concurrent.Counters.Counter; end record; end MAT.Events.Targets;
Define the Get_Event function
Define the Get_Event function
Ada
apache-2.0
stcarrez/mat,stcarrez/mat,stcarrez/mat
3bfbed1ffd04bbea6017420cdfdafb3c0078ec4e
src/asf-applications.adb
src/asf-applications.adb
----------------------------------------------------------------------- -- applications -- Ada Web Application -- Copyright (C) 2009, 2010, 2013, 2015 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Properties.Basic; package body ASF.Applications is -- ------------------------------ -- Get the configuration parameter; -- ------------------------------ function Get (Self : Config; Param : Config_Param) return String is begin return Self.Get (Param.Name.all, Param.Default.all); end Get; -- ------------------------------ -- Get the configuration parameter; -- ------------------------------ function Get (Self : Config; Param : Config_Param) return Ada.Strings.Unbounded.Unbounded_String is begin if Self.Exists (Param.Name.all) then return Self.Get (Param.Name.all); else return Ada.Strings.Unbounded.To_Unbounded_String (Param.Default.all); end if; end Get; -- ------------------------------ -- Get the configuration parameter; -- ------------------------------ function Get (Self : Config; Param : Config_Param) return Boolean is use Util.Properties.Basic.Boolean_Property; begin return Get (Self, Param.Name.all, Boolean'Value (Param.Default.all)); end Get; -- ------------------------------ -- Create the configuration parameter definition instance. -- ------------------------------ package body Parameter is Param : constant Config_Param := ASF.Applications.P '(Name => PARAM_NAME'Access, Default => PARAM_VALUE'Access); -- ------------------------------ -- Returns the configuration parameter. -- ------------------------------ function P return Config_Param is begin return Param; end P; end Parameter; end ASF.Applications;
----------------------------------------------------------------------- -- applications -- Ada Web Application -- Copyright (C) 2009, 2010, 2013, 2015, 2020 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Properties.Basic; package body ASF.Applications is -- ------------------------------ -- Get the configuration parameter; -- ------------------------------ function Get (Self : Config; Param : Config_Param) return String is begin return Self.Get (Param.Name.all, Param.Default.all); end Get; -- ------------------------------ -- Get the configuration parameter; -- ------------------------------ function Get (Self : Config; Param : Config_Param) return Ada.Strings.Unbounded.Unbounded_String is begin if Self.Exists (Param.Name.all) then return Self.Get (Param.Name.all); else return Ada.Strings.Unbounded.To_Unbounded_String (Param.Default.all); end if; end Get; -- ------------------------------ -- Get the configuration parameter; -- ------------------------------ function Get (Self : Config; Param : Config_Param) return Boolean is use Util.Properties.Basic.Boolean_Property; begin return Get (Self, Param.Name.all, Boolean'Value (Param.Default.all)); end Get; function Get (Self : Config; Param : Config_Param) return Integer is use Util.Properties.Basic.Integer_Property; begin return Get (Self, Param.Name.all, Integer'Value (Param.Default.all)); end Get; -- ------------------------------ -- Create the configuration parameter definition instance. -- ------------------------------ package body Parameter is Param : constant Config_Param := ASF.Applications.P '(Name => PARAM_NAME'Access, Default => PARAM_VALUE'Access); -- ------------------------------ -- Returns the configuration parameter. -- ------------------------------ function P return Config_Param is begin return Param; end P; end Parameter; end ASF.Applications;
Implement the Get function returning integer
Implement the Get function returning integer
Ada
apache-2.0
stcarrez/ada-asf,stcarrez/ada-asf,stcarrez/ada-asf
2e0dd4ef19176512545f308583f5cc9b48e5cdf5
matp/src/mat-targets.adb
matp/src/mat-targets.adb
----------------------------------------------------------------------- -- Clients - Abstract representation of client information -- Copyright (C) 2014, 2015 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Text_IO; with Ada.Command_Line; with Ada.IO_Exceptions; with Ada.Unchecked_Deallocation; with GNAT.Command_Line; with Readline; with Util.Strings; with Util.Properties; with Util.Log.Loggers; with MAT.Commands; with MAT.Interrupts; with MAT.Targets.Probes; package body MAT.Targets is procedure Free is new Ada.Unchecked_Deallocation (MAT.Events.Targets.Target_Events'Class, MAT.Events.Targets.Target_Events_Access); procedure Free is new Ada.Unchecked_Deallocation (MAT.Frames.Targets.Target_Frames'Class, MAT.Frames.Targets.Target_Frames_Access); procedure Free is new Ada.Unchecked_Deallocation (Target_Process_Type'Class, Target_Process_Type_Access); -- Configure the log managers used by mat. procedure Initialize_Logs (Path : in String); -- ------------------------------ -- Release the target process instance. -- ------------------------------ overriding procedure Finalize (Target : in out Target_Process_Type) is begin Free (Target.Events); Free (Target.Frames); end Finalize; -- ------------------------------ -- Find the region that matches the given name. -- ------------------------------ overriding function Find_Region (Resolver : in Target_Process_Type; Name : in String) return MAT.Memory.Region_Info is begin return Resolver.Memory.Find_Region (Name); end Find_Region; -- ------------------------------ -- Find the symbol in the symbol table and return the start and end address. -- ------------------------------ overriding function Find_Symbol (Resolver : in Target_Process_Type; Name : in String) return MAT.Memory.Region_Info is Region : MAT.Memory.Region_Info; begin if Resolver.Symbols.Is_Null then raise MAT.Memory.Targets.Not_Found; end if; Resolver.Symbols.Value.Find_Symbol_Range (Name, Region.Start_Addr, Region.End_Addr); return Region; end Find_Symbol; -- ------------------------------ -- Get the start time for the tick reference. -- ------------------------------ overriding function Get_Start_Time (Resolver : in Target_Process_Type) return MAT.Types.Target_Tick_Ref is Start : MAT.Types.Target_Tick_Ref; Finish : MAT.Types.Target_Tick_Ref; begin Resolver.Events.Get_Time_Range (Start, Finish); return Start; end Get_Start_Time; -- ------------------------------ -- Get the console instance. -- ------------------------------ function Console (Target : in Target_Type) return MAT.Consoles.Console_Access is begin return Target.Console; end Console; -- ------------------------------ -- Set the console instance. -- ------------------------------ procedure Console (Target : in out Target_Type; Console : in MAT.Consoles.Console_Access) is begin Target.Console := Console; end Console; -- ------------------------------ -- Get the current process instance. -- ------------------------------ function Process (Target : in Target_Type) return Target_Process_Type_Access is begin return Target.Current; end Process; -- ------------------------------ -- Initialize the target object to manage the memory slots, the stack frames -- and setup the reader to analyze the memory and other events. -- ------------------------------ procedure Initialize (Target : in out Target_Type; Reader : in out MAT.Events.Probes.Probe_Manager_Type'Class) is begin MAT.Targets.Probes.Initialize (Target => Target, Manager => Reader); end Initialize; -- ------------------------------ -- Create a process instance to hold and keep track of memory and other information about -- the given process ID. -- ------------------------------ procedure Create_Process (Target : in out Target_Type; Pid : in MAT.Types.Target_Process_Ref; Path : in Ada.Strings.Unbounded.Unbounded_String; Process : out Target_Process_Type_Access) is Path_String : constant String := Ada.Strings.Unbounded.To_String (Path); begin Process := Target.Find_Process (Pid); if Process = null then Process := new Target_Process_Type; Process.Pid := Pid; Process.Path := Path; Process.Symbols := MAT.Symbols.Targets.Target_Symbols_Refs.Create; Process.Symbols.Value.Console := Target.Console; Process.Symbols.Value.Search_Path := Target.Options.Search_Path; Target.Processes.Insert (Pid, Process); Target.Console.Notice (MAT.Consoles.N_PID_INFO, "Process" & MAT.Types.Target_Process_Ref'Image (Pid) & " created"); Target.Console.Notice (MAT.Consoles.N_PATH_INFO, "Path " & Path_String); end if; if Target.Current = null then Target.Current := Process; end if; end Create_Process; -- ------------------------------ -- Find the process instance from the process ID. -- ------------------------------ function Find_Process (Target : in Target_Type; Pid : in MAT.Types.Target_Process_Ref) return Target_Process_Type_Access is Pos : constant Process_Cursor := Target.Processes.Find (Pid); begin if Process_Maps.Has_Element (Pos) then return Process_Maps.Element (Pos); else return null; end if; end Find_Process; -- ------------------------------ -- Iterate over the list of connected processes and execute the <tt>Process</tt> procedure. -- ------------------------------ procedure Iterator (Target : in Target_Type; Process : access procedure (Proc : in Target_Process_Type'Class)) is Iter : Process_Cursor := Target.Processes.First; begin while Process_Maps.Has_Element (Iter) loop Process (Process_Maps.Element (Iter).all); Process_Maps.Next (Iter); end loop; end Iterator; -- ------------------------------ -- Convert the string to a socket address. The string can have two forms: -- port -- host:port -- ------------------------------ function To_Sock_Addr_Type (Param : in String) return GNAT.Sockets.Sock_Addr_Type is Pos : constant Natural := Util.Strings.Index (Param, ':'); Result : GNAT.Sockets.Sock_Addr_Type; begin if Pos > 0 then Result.Port := GNAT.Sockets.Port_Type'Value (Param (Pos + 1 .. Param'Last)); Result.Addr := GNAT.Sockets.Inet_Addr (Param (Param'First .. Pos - 1)); else Result.Port := GNAT.Sockets.Port_Type'Value (Param); Result.Addr := GNAT.Sockets.Any_Inet_Addr; end if; return Result; end To_Sock_Addr_Type; -- ------------------------------ -- Print the application usage. -- ------------------------------ procedure Usage is use Ada.Text_IO; begin Put_Line ("Usage: mat [-i] [-e] [-nw] [-ns] [-s] [-b [ip:]port] [-d path] [file.mat]"); Put_Line ("-i Enable the interactive mode"); Put_Line ("-e Print the probe events as they are received"); Put_Line ("-nw Disable the graphical mode"); Put_Line ("-s Start the TCP/IP server to receive events"); Put_Line ("-b [ip:]port Define the port and local address to bind"); Put_Line ("-ns Disable the automatic symbols loading"); Put_Line ("-d path Search path to find shared libraries and load their symbols"); Ada.Command_Line.Set_Exit_Status (2); raise Usage_Error; end Usage; -- ------------------------------ -- Add a search path for the library and symbol loader. -- ------------------------------ procedure Add_Search_Path (Target : in out MAT.Targets.Target_Type; Path : in String) is begin if Ada.Strings.Unbounded.Length (Target.Options.Search_Path) > 0 then Ada.Strings.Unbounded.Append (Target.Options.Search_Path, ";"); Ada.Strings.Unbounded.Append (Target.Options.Search_Path, Path); else Target.Options.Search_Path := Ada.Strings.Unbounded.To_Unbounded_String (Path); end if; end Add_Search_Path; -- ------------------------------ -- Configure the log managers used by mat. -- ------------------------------ procedure Initialize_Logs (Path : in String) is Props : Util.Properties.Manager; begin begin Props.Load_Properties (Path); exception when Ada.IO_Exceptions.Name_Error => -- Default log configuration. Props.Set ("log4j.rootCategory", "INFO,console,mat"); Props.Set ("log4j.appender.console", "Console"); Props.Set ("log4j.appender.console.level", "WARN"); Props.Set ("log4j.appender.console.layout", "level-message"); Props.Set ("log4j.appender.mat", "File"); Props.Set ("log4j.appender.mat.File", "mat.log"); end; Util.Log.Loggers.Initialize (Props); end Initialize_Logs; -- ------------------------------ -- Parse the command line arguments and configure the target instance. -- ------------------------------ procedure Initialize_Options (Target : in out MAT.Targets.Target_Type) is begin Initialize_Logs ("matp.properties"); GNAT.Command_Line.Initialize_Option_Scan (Stop_At_First_Non_Switch => True, Section_Delimiters => "targs"); loop case GNAT.Command_Line.Getopt ("i e s nw ns b: d:") is when ASCII.NUL => exit; when 'i' => Target.Options.Interactive := True; when 'e' => Target.Options.Print_Events := True; when 's' => Target.Options.Server_Mode := True; when 'b' => Target.Options.Server_Mode := True; Target.Options.Address := To_Sock_Addr_Type (GNAT.Command_Line.Parameter); when 'n' => if GNAT.Command_Line.Full_Switch = "nw" then Target.Options.Graphical := False; else Target.Options.Load_Symbols := False; end if; when 'd' => Add_Search_Path (Target, GNAT.Command_Line.Parameter); when '*' => exit; when others => Usage; end case; end loop; exception when Usage_Error => raise; when others => Usage; end Initialize_Options; -- ------------------------------ -- Enter in the interactive loop reading the commands from the standard input -- and executing the commands. -- ------------------------------ procedure Interactive (Target : in out MAT.Targets.Target_Type) is begin MAT.Interrupts.Install; loop declare Line : constant String := Readline.Get_Line ("mat>"); begin MAT.Interrupts.Clear; MAT.Commands.Execute (Target, Line); exception when MAT.Commands.Stop_Interp => exit; end; end loop; end Interactive; -- ------------------------------ -- Start the server to listen to MAT event socket streams. -- ------------------------------ procedure Start (Target : in out Target_Type) is begin if Target.Options.Server_Mode then Target.Server.Start (Target'Unchecked_Access, Target.Options.Address); end if; end Start; -- ------------------------------ -- Stop the server thread. -- ------------------------------ procedure Stop (Target : in out Target_Type) is begin if Target.Options.Server_Mode then Target.Server.Stop; end if; end Stop; -- ------------------------------ -- Release the storage used by the target object. -- ------------------------------ overriding procedure Finalize (Target : in out Target_Type) is begin while not Target.Processes.Is_Empty loop declare Process : Target_Process_Type_Access := Target.Processes.First_Element; begin Free (Process); Target.Processes.Delete_First; end; end loop; end Finalize; end MAT.Targets;
----------------------------------------------------------------------- -- Clients - Abstract representation of client information -- Copyright (C) 2014, 2015 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Text_IO; with Ada.Command_Line; with Ada.IO_Exceptions; with Ada.Unchecked_Deallocation; with GNAT.Command_Line; with Readline; with Util.Strings; with Util.Properties; with Util.Log.Loggers; with MAT.Commands; with MAT.Interrupts; with MAT.Targets.Probes; package body MAT.Targets is procedure Free is new Ada.Unchecked_Deallocation (MAT.Events.Targets.Target_Events'Class, MAT.Events.Targets.Target_Events_Access); procedure Free is new Ada.Unchecked_Deallocation (MAT.Frames.Targets.Target_Frames'Class, MAT.Frames.Targets.Target_Frames_Access); procedure Free is new Ada.Unchecked_Deallocation (Target_Process_Type'Class, Target_Process_Type_Access); -- Configure the log managers used by mat. procedure Initialize_Logs (Path : in String); -- ------------------------------ -- Release the target process instance. -- ------------------------------ overriding procedure Finalize (Target : in out Target_Process_Type) is begin Free (Target.Events); Free (Target.Frames); end Finalize; -- ------------------------------ -- Find the region that matches the given name. -- ------------------------------ overriding function Find_Region (Resolver : in Target_Process_Type; Name : in String) return MAT.Memory.Region_Info is begin return Resolver.Memory.Find_Region (Name); end Find_Region; -- ------------------------------ -- Find the symbol in the symbol table and return the start and end address. -- ------------------------------ overriding function Find_Symbol (Resolver : in Target_Process_Type; Name : in String) return MAT.Memory.Region_Info is Region : MAT.Memory.Region_Info; begin if Resolver.Symbols.Is_Null then raise MAT.Memory.Targets.Not_Found; end if; Resolver.Symbols.Value.Find_Symbol_Range (Name, Region.Start_Addr, Region.End_Addr); return Region; end Find_Symbol; -- ------------------------------ -- Find the symbol region in the symbol table that contains the given address -- and return the start and end address of that region. -- ------------------------------ overriding function Find_Symbol (Resolver : in Target_Process_Type; Addr : in MAT.Types.Target_Addr) return MAT.Memory.Region_Info is Region : MAT.Memory.Region_Info; begin if Resolver.Symbols.Is_Null then Region.Start_Addr := Addr; Region.End_Addr := Addr; else Resolver.Symbols.Value.Find_Symbol_Range (Addr, Region.Start_Addr, Region.End_Addr); end if; return Region; end Find_Symbol; -- ------------------------------ -- Get the start time for the tick reference. -- ------------------------------ overriding function Get_Start_Time (Resolver : in Target_Process_Type) return MAT.Types.Target_Tick_Ref is Start : MAT.Types.Target_Tick_Ref; Finish : MAT.Types.Target_Tick_Ref; begin Resolver.Events.Get_Time_Range (Start, Finish); return Start; end Get_Start_Time; -- ------------------------------ -- Get the console instance. -- ------------------------------ function Console (Target : in Target_Type) return MAT.Consoles.Console_Access is begin return Target.Console; end Console; -- ------------------------------ -- Set the console instance. -- ------------------------------ procedure Console (Target : in out Target_Type; Console : in MAT.Consoles.Console_Access) is begin Target.Console := Console; end Console; -- ------------------------------ -- Get the current process instance. -- ------------------------------ function Process (Target : in Target_Type) return Target_Process_Type_Access is begin return Target.Current; end Process; -- ------------------------------ -- Initialize the target object to manage the memory slots, the stack frames -- and setup the reader to analyze the memory and other events. -- ------------------------------ procedure Initialize (Target : in out Target_Type; Reader : in out MAT.Events.Probes.Probe_Manager_Type'Class) is begin MAT.Targets.Probes.Initialize (Target => Target, Manager => Reader); end Initialize; -- ------------------------------ -- Create a process instance to hold and keep track of memory and other information about -- the given process ID. -- ------------------------------ procedure Create_Process (Target : in out Target_Type; Pid : in MAT.Types.Target_Process_Ref; Path : in Ada.Strings.Unbounded.Unbounded_String; Process : out Target_Process_Type_Access) is Path_String : constant String := Ada.Strings.Unbounded.To_String (Path); begin Process := Target.Find_Process (Pid); if Process = null then Process := new Target_Process_Type; Process.Pid := Pid; Process.Path := Path; Process.Symbols := MAT.Symbols.Targets.Target_Symbols_Refs.Create; Process.Symbols.Value.Console := Target.Console; Process.Symbols.Value.Search_Path := Target.Options.Search_Path; Target.Processes.Insert (Pid, Process); Target.Console.Notice (MAT.Consoles.N_PID_INFO, "Process" & MAT.Types.Target_Process_Ref'Image (Pid) & " created"); Target.Console.Notice (MAT.Consoles.N_PATH_INFO, "Path " & Path_String); end if; if Target.Current = null then Target.Current := Process; end if; end Create_Process; -- ------------------------------ -- Find the process instance from the process ID. -- ------------------------------ function Find_Process (Target : in Target_Type; Pid : in MAT.Types.Target_Process_Ref) return Target_Process_Type_Access is Pos : constant Process_Cursor := Target.Processes.Find (Pid); begin if Process_Maps.Has_Element (Pos) then return Process_Maps.Element (Pos); else return null; end if; end Find_Process; -- ------------------------------ -- Iterate over the list of connected processes and execute the <tt>Process</tt> procedure. -- ------------------------------ procedure Iterator (Target : in Target_Type; Process : access procedure (Proc : in Target_Process_Type'Class)) is Iter : Process_Cursor := Target.Processes.First; begin while Process_Maps.Has_Element (Iter) loop Process (Process_Maps.Element (Iter).all); Process_Maps.Next (Iter); end loop; end Iterator; -- ------------------------------ -- Convert the string to a socket address. The string can have two forms: -- port -- host:port -- ------------------------------ function To_Sock_Addr_Type (Param : in String) return GNAT.Sockets.Sock_Addr_Type is Pos : constant Natural := Util.Strings.Index (Param, ':'); Result : GNAT.Sockets.Sock_Addr_Type; begin if Pos > 0 then Result.Port := GNAT.Sockets.Port_Type'Value (Param (Pos + 1 .. Param'Last)); Result.Addr := GNAT.Sockets.Inet_Addr (Param (Param'First .. Pos - 1)); else Result.Port := GNAT.Sockets.Port_Type'Value (Param); Result.Addr := GNAT.Sockets.Any_Inet_Addr; end if; return Result; end To_Sock_Addr_Type; -- ------------------------------ -- Print the application usage. -- ------------------------------ procedure Usage is use Ada.Text_IO; begin Put_Line ("Usage: mat [-i] [-e] [-nw] [-ns] [-s] [-b [ip:]port] [-d path] [file.mat]"); Put_Line ("-i Enable the interactive mode"); Put_Line ("-e Print the probe events as they are received"); Put_Line ("-nw Disable the graphical mode"); Put_Line ("-s Start the TCP/IP server to receive events"); Put_Line ("-b [ip:]port Define the port and local address to bind"); Put_Line ("-ns Disable the automatic symbols loading"); Put_Line ("-d path Search path to find shared libraries and load their symbols"); Ada.Command_Line.Set_Exit_Status (2); raise Usage_Error; end Usage; -- ------------------------------ -- Add a search path for the library and symbol loader. -- ------------------------------ procedure Add_Search_Path (Target : in out MAT.Targets.Target_Type; Path : in String) is begin if Ada.Strings.Unbounded.Length (Target.Options.Search_Path) > 0 then Ada.Strings.Unbounded.Append (Target.Options.Search_Path, ";"); Ada.Strings.Unbounded.Append (Target.Options.Search_Path, Path); else Target.Options.Search_Path := Ada.Strings.Unbounded.To_Unbounded_String (Path); end if; end Add_Search_Path; -- ------------------------------ -- Configure the log managers used by mat. -- ------------------------------ procedure Initialize_Logs (Path : in String) is Props : Util.Properties.Manager; begin begin Props.Load_Properties (Path); exception when Ada.IO_Exceptions.Name_Error => -- Default log configuration. Props.Set ("log4j.rootCategory", "INFO,console,mat"); Props.Set ("log4j.appender.console", "Console"); Props.Set ("log4j.appender.console.level", "WARN"); Props.Set ("log4j.appender.console.layout", "level-message"); Props.Set ("log4j.appender.mat", "File"); Props.Set ("log4j.appender.mat.File", "mat.log"); end; Util.Log.Loggers.Initialize (Props); end Initialize_Logs; -- ------------------------------ -- Parse the command line arguments and configure the target instance. -- ------------------------------ procedure Initialize_Options (Target : in out MAT.Targets.Target_Type) is begin Initialize_Logs ("matp.properties"); GNAT.Command_Line.Initialize_Option_Scan (Stop_At_First_Non_Switch => True, Section_Delimiters => "targs"); loop case GNAT.Command_Line.Getopt ("i e s nw ns b: d:") is when ASCII.NUL => exit; when 'i' => Target.Options.Interactive := True; when 'e' => Target.Options.Print_Events := True; when 's' => Target.Options.Server_Mode := True; when 'b' => Target.Options.Server_Mode := True; Target.Options.Address := To_Sock_Addr_Type (GNAT.Command_Line.Parameter); when 'n' => if GNAT.Command_Line.Full_Switch = "nw" then Target.Options.Graphical := False; else Target.Options.Load_Symbols := False; end if; when 'd' => Add_Search_Path (Target, GNAT.Command_Line.Parameter); when '*' => exit; when others => Usage; end case; end loop; exception when Usage_Error => raise; when others => Usage; end Initialize_Options; -- ------------------------------ -- Enter in the interactive loop reading the commands from the standard input -- and executing the commands. -- ------------------------------ procedure Interactive (Target : in out MAT.Targets.Target_Type) is begin MAT.Interrupts.Install; loop declare Line : constant String := Readline.Get_Line ("mat>"); begin MAT.Interrupts.Clear; MAT.Commands.Execute (Target, Line); exception when MAT.Commands.Stop_Interp => exit; end; end loop; end Interactive; -- ------------------------------ -- Start the server to listen to MAT event socket streams. -- ------------------------------ procedure Start (Target : in out Target_Type) is begin if Target.Options.Server_Mode then Target.Server.Start (Target'Unchecked_Access, Target.Options.Address); end if; end Start; -- ------------------------------ -- Stop the server thread. -- ------------------------------ procedure Stop (Target : in out Target_Type) is begin if Target.Options.Server_Mode then Target.Server.Stop; end if; end Stop; -- ------------------------------ -- Release the storage used by the target object. -- ------------------------------ overriding procedure Finalize (Target : in out Target_Type) is begin while not Target.Processes.Is_Empty loop declare Process : Target_Process_Type_Access := Target.Processes.First_Element; begin Free (Process); Target.Processes.Delete_First; end; end loop; end Finalize; end MAT.Targets;
Implement the new Find_Symbol by using the Find_Symbol_Range operation
Implement the new Find_Symbol by using the Find_Symbol_Range operation
Ada
apache-2.0
stcarrez/mat,stcarrez/mat,stcarrez/mat
89c9d4c9137b3d99ca138444f239be792d38fb8a
src/gen-model-tables.ads
src/gen-model-tables.ads
----------------------------------------------------------------------- -- gen-model-tables -- Database table model representation -- Copyright (C) 2009, 2010, 2011, 2012, 2013, 2014, 2015, 2016, 2017, 2018 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Containers.Hashed_Maps; with Ada.Containers.Vectors; with Ada.Strings.Unbounded; with Ada.Strings.Unbounded.Hash; with Util.Beans.Objects; with Gen.Model.List; with Gen.Model.Packages; with Gen.Model.Mappings; with Gen.Model.Operations; package Gen.Model.Tables is use Ada.Strings.Unbounded; type Table_Definition; type Table_Definition_Access is access all Table_Definition'Class; -- ------------------------------ -- Column Definition -- ------------------------------ type Column_Definition is new Definition with record Number : Natural := 0; Table : Table_Definition_Access; Bean : Util.Beans.Objects.Object; -- The column type name. Type_Name : Unbounded_String; -- The SQL type associated with the column. Sql_Type : Unbounded_String; -- The SQL name associated with the column. Sql_Name : Unbounded_String; -- The SQL length for strings. Sql_Length : Positive := 255; -- Whether the column must not be null in the database Not_Null : Boolean := False; -- Whether the column must be unique Unique : Boolean := False; -- True if this column is the optimistic locking version column. Is_Version : Boolean := False; -- True if this column is the primary key column. Is_Key : Boolean := False; -- True if the column can be read by the application. Is_Readable : Boolean := True; -- True if the column is included in the insert statement Is_Inserted : Boolean := True; -- True if the column is included in the update statement Is_Updated : Boolean := True; -- True if the column is auditable (generate code to track changes). Is_Auditable : Boolean := False; -- True if the Ada mapping must use the foreign key type. Use_Foreign_Key_Type : Boolean := False; -- The class generator to use for this column. Generator : Util.Beans.Objects.Object; -- The type mapping of the column. Type_Mapping : Gen.Model.Mappings.Mapping_Definition_Access; end record; type Column_Definition_Access is access all Column_Definition'Class; -- Get the value identified by the name. -- If the name cannot be found, the method should return the Null object. overriding function Get_Value (From : Column_Definition; Name : String) return Util.Beans.Objects.Object; -- Prepare the generation of the model. overriding procedure Prepare (O : in out Column_Definition); -- Validate the definition by checking and reporting problems to the logger interface. overriding procedure Validate (Def : in out Column_Definition; Log : in out Util.Log.Logging'Class); -- Returns true if the column type is a basic type. function Is_Basic_Type (From : Column_Definition) return Boolean; -- Returns true if the column is using a variable length (ex: a string). function Is_Variable_Length (From : Column_Definition) return Boolean; -- Returns the column type. function Get_Type (From : Column_Definition) return String; -- Set the column type. procedure Set_Type (Into : in out Column_Definition; Name : in String); -- Returns the column type mapping. function Get_Type_Mapping (From : in Column_Definition) return Gen.Model.Mappings.Mapping_Definition_Access; package Column_List is new Gen.Model.List (T => Column_Definition, T_Access => Column_Definition_Access); -- ------------------------------ -- Association Definition -- ------------------------------ type Association_Definition is new Column_Definition with private; type Association_Definition_Access is access all Association_Definition'Class; -- Get the value identified by the name. -- If the name cannot be found, the method should return the Null object. overriding function Get_Value (From : Association_Definition; Name : String) return Util.Beans.Objects.Object; -- Prepare the generation of the model. overriding procedure Prepare (O : in out Association_Definition); package Operation_List is new Gen.Model.List (T => Gen.Model.Operations.Operation_Definition, T_Access => Gen.Model.Operations.Operation_Definition_Access); package Table_Vectors is new Ada.Containers.Vectors (Index_Type => Positive, Element_Type => Table_Definition_Access); -- ------------------------------ -- Table Definition -- ------------------------------ type Table_Definition is new Mappings.Mapping_Definition with record Members : aliased Column_List.List_Definition; Members_Bean : Util.Beans.Objects.Object; Operations : aliased Operation_List.List_Definition; Operations_Bean : Util.Beans.Objects.Object; Parent : Table_Definition_Access; Parent_Name : Unbounded_String; Package_Def : Gen.Model.Packages.Package_Definition_Access; Type_Name : Unbounded_String; Pkg_Name : Unbounded_String; Table_Name : Unbounded_String; Version_Column : Column_Definition_Access; Id_Column : Column_Definition_Access; -- The number of <<PK>> columns found. Key_Count : Natural := 0; Has_Associations : Boolean := False; -- The list of tables that this table depends on. Dependencies : Table_Vectors.Vector; -- Controls whether the <tt>Vector</tt> type and the <tt>List</tt> procedure must -- be generated. Has_List : Boolean := True; -- Mark flag used by the dependency calculation. Has_Mark : Boolean := False; -- Whether the bean type is a limited type or not. Is_Limited : Boolean := False; -- Whether the serialization operation have to be generated. Is_Serializable : Boolean := False; end record; -- Get the value identified by the name. -- If the name cannot be found, the method should return the Null object. overriding function Get_Value (From : Table_Definition; Name : String) return Util.Beans.Objects.Object; -- Prepare the generation of the model. overriding procedure Prepare (O : in out Table_Definition); -- Validate the definition by checking and reporting problems to the logger interface. overriding procedure Validate (Def : in out Table_Definition; Log : in out Util.Log.Logging'Class); -- Initialize the table definition instance. overriding procedure Initialize (O : in out Table_Definition); -- Collect the dependencies to other tables. procedure Collect_Dependencies (O : in out Table_Definition); type Dependency_Type is (NONE, FORWARD, BACKWARD); -- CIRCULAR is not yet managed. -- Get the dependency between the two tables. -- Returns NONE if both table don't depend on each other. -- Returns FORWARD if the <tt>Left</tt> table depends on <tt>Right</tt>. -- Returns BACKWARD if the <tt>Right</tt> table depends on <tt>Left</tt>. function Depends_On (Left, Right : in Table_Definition_Access) return Dependency_Type; -- Create a table with the given name. function Create_Table (Name : in Unbounded_String) return Table_Definition_Access; -- Create a table column with the given name and add it to the table. procedure Add_Column (Table : in out Table_Definition; Name : in Unbounded_String; Column : out Column_Definition_Access); -- Create a table association with the given name and add it to the table. procedure Add_Association (Table : in out Table_Definition; Name : in Unbounded_String; Assoc : out Association_Definition_Access); -- Create an operation with the given name and add it to the table. procedure Add_Operation (Table : in out Table_Definition; Name : in Unbounded_String; Operation : out Model.Operations.Operation_Definition_Access); -- Set the table name and determines the package name. procedure Set_Table_Name (Table : in out Table_Definition; Name : in String); package Table_Map is new Ada.Containers.Hashed_Maps (Key_Type => Unbounded_String, Element_Type => Table_Definition_Access, Hash => Ada.Strings.Unbounded.Hash, Equivalent_Keys => "="); subtype Table_Cursor is Table_Map.Cursor; -- Returns true if the table cursor contains a valid table function Has_Element (Position : Table_Cursor) return Boolean renames Table_Map.Has_Element; -- Returns the table definition. function Element (Position : Table_Cursor) return Table_Definition_Access renames Table_Map.Element; -- Move the iterator to the next table definition. procedure Next (Position : in out Table_Cursor) renames Table_Map.Next; package Table_List is new Gen.Model.List (T => Definition, T_Access => Definition_Access); private type Association_Definition is new Column_Definition with null record; end Gen.Model.Tables;
----------------------------------------------------------------------- -- gen-model-tables -- Database table model representation -- Copyright (C) 2009, 2010, 2011, 2012, 2013, 2014, 2015, 2016, 2017, 2018 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Containers.Hashed_Maps; with Ada.Containers.Vectors; with Ada.Strings.Unbounded; with Ada.Strings.Unbounded.Hash; with Util.Beans.Objects; with Gen.Model.List; with Gen.Model.Packages; with Gen.Model.Mappings; with Gen.Model.Operations; package Gen.Model.Tables is use Ada.Strings.Unbounded; type Table_Definition; type Table_Definition_Access is access all Table_Definition'Class; -- ------------------------------ -- Column Definition -- ------------------------------ type Column_Definition is new Definition with record Number : Natural := 0; Table : Table_Definition_Access; Bean : Util.Beans.Objects.Object; -- The column type name. Type_Name : Unbounded_String; -- The SQL type associated with the column. Sql_Type : Unbounded_String; -- The SQL name associated with the column. Sql_Name : Unbounded_String; -- The SQL length for strings. Sql_Length : Positive := 255; -- Whether the column must not be null in the database Not_Null : Boolean := False; -- Whether the column must be unique Unique : Boolean := False; -- True if this column is the optimistic locking version column. Is_Version : Boolean := False; -- True if this column is the primary key column. Is_Key : Boolean := False; -- True if the column can be read by the application. Is_Readable : Boolean := True; -- True if the column is included in the insert statement Is_Inserted : Boolean := True; -- True if the column is included in the update statement Is_Updated : Boolean := True; -- True if the column is auditable (generate code to track changes). Is_Auditable : Boolean := False; -- True if the Ada mapping must use the foreign key type. Use_Foreign_Key_Type : Boolean := False; -- The class generator to use for this column. Generator : Util.Beans.Objects.Object; -- The type mapping of the column. Type_Mapping : Gen.Model.Mappings.Mapping_Definition_Access; end record; type Column_Definition_Access is access all Column_Definition'Class; -- Get the value identified by the name. -- If the name cannot be found, the method should return the Null object. overriding function Get_Value (From : Column_Definition; Name : String) return Util.Beans.Objects.Object; -- Prepare the generation of the model. overriding procedure Prepare (O : in out Column_Definition); -- Validate the definition by checking and reporting problems to the logger interface. overriding procedure Validate (Def : in out Column_Definition; Log : in out Util.Log.Logging'Class); -- Returns true if the column type is a basic type. function Is_Basic_Type (From : Column_Definition) return Boolean; -- Returns true if the column is using a variable length (ex: a string). function Is_Variable_Length (From : Column_Definition) return Boolean; -- Returns the column type. function Get_Type (From : Column_Definition) return String; -- Set the column type. procedure Set_Type (Into : in out Column_Definition; Name : in String); -- Set the SQL length of the column. procedure Set_Sql_Length (Into : in out Column_Definition; Value : in String; Log : in out Util.Log.Logging'Class); -- Returns the column type mapping. function Get_Type_Mapping (From : in Column_Definition) return Gen.Model.Mappings.Mapping_Definition_Access; package Column_List is new Gen.Model.List (T => Column_Definition, T_Access => Column_Definition_Access); -- ------------------------------ -- Association Definition -- ------------------------------ type Association_Definition is new Column_Definition with private; type Association_Definition_Access is access all Association_Definition'Class; -- Get the value identified by the name. -- If the name cannot be found, the method should return the Null object. overriding function Get_Value (From : Association_Definition; Name : String) return Util.Beans.Objects.Object; -- Prepare the generation of the model. overriding procedure Prepare (O : in out Association_Definition); package Operation_List is new Gen.Model.List (T => Gen.Model.Operations.Operation_Definition, T_Access => Gen.Model.Operations.Operation_Definition_Access); package Table_Vectors is new Ada.Containers.Vectors (Index_Type => Positive, Element_Type => Table_Definition_Access); -- ------------------------------ -- Table Definition -- ------------------------------ type Table_Definition is new Mappings.Mapping_Definition with record Members : aliased Column_List.List_Definition; Members_Bean : Util.Beans.Objects.Object; Operations : aliased Operation_List.List_Definition; Operations_Bean : Util.Beans.Objects.Object; Parent : Table_Definition_Access; Parent_Name : Unbounded_String; Package_Def : Gen.Model.Packages.Package_Definition_Access; Type_Name : Unbounded_String; Pkg_Name : Unbounded_String; Table_Name : Unbounded_String; Version_Column : Column_Definition_Access; Id_Column : Column_Definition_Access; -- The number of <<PK>> columns found. Key_Count : Natural := 0; Has_Associations : Boolean := False; -- The list of tables that this table depends on. Dependencies : Table_Vectors.Vector; -- Controls whether the <tt>Vector</tt> type and the <tt>List</tt> procedure must -- be generated. Has_List : Boolean := True; -- Mark flag used by the dependency calculation. Has_Mark : Boolean := False; -- Whether the bean type is a limited type or not. Is_Limited : Boolean := False; -- Whether the serialization operation have to be generated. Is_Serializable : Boolean := False; end record; -- Get the value identified by the name. -- If the name cannot be found, the method should return the Null object. overriding function Get_Value (From : Table_Definition; Name : String) return Util.Beans.Objects.Object; -- Prepare the generation of the model. overriding procedure Prepare (O : in out Table_Definition); -- Validate the definition by checking and reporting problems to the logger interface. overriding procedure Validate (Def : in out Table_Definition; Log : in out Util.Log.Logging'Class); -- Initialize the table definition instance. overriding procedure Initialize (O : in out Table_Definition); -- Collect the dependencies to other tables. procedure Collect_Dependencies (O : in out Table_Definition); type Dependency_Type is (NONE, FORWARD, BACKWARD); -- CIRCULAR is not yet managed. -- Get the dependency between the two tables. -- Returns NONE if both table don't depend on each other. -- Returns FORWARD if the <tt>Left</tt> table depends on <tt>Right</tt>. -- Returns BACKWARD if the <tt>Right</tt> table depends on <tt>Left</tt>. function Depends_On (Left, Right : in Table_Definition_Access) return Dependency_Type; -- Create a table with the given name. function Create_Table (Name : in Unbounded_String) return Table_Definition_Access; -- Create a table column with the given name and add it to the table. procedure Add_Column (Table : in out Table_Definition; Name : in Unbounded_String; Column : out Column_Definition_Access); -- Create a table association with the given name and add it to the table. procedure Add_Association (Table : in out Table_Definition; Name : in Unbounded_String; Assoc : out Association_Definition_Access); -- Create an operation with the given name and add it to the table. procedure Add_Operation (Table : in out Table_Definition; Name : in Unbounded_String; Operation : out Model.Operations.Operation_Definition_Access); -- Set the table name and determines the package name. procedure Set_Table_Name (Table : in out Table_Definition; Name : in String); package Table_Map is new Ada.Containers.Hashed_Maps (Key_Type => Unbounded_String, Element_Type => Table_Definition_Access, Hash => Ada.Strings.Unbounded.Hash, Equivalent_Keys => "="); subtype Table_Cursor is Table_Map.Cursor; -- Returns true if the table cursor contains a valid table function Has_Element (Position : Table_Cursor) return Boolean renames Table_Map.Has_Element; -- Returns the table definition. function Element (Position : Table_Cursor) return Table_Definition_Access renames Table_Map.Element; -- Move the iterator to the next table definition. procedure Next (Position : in out Table_Cursor) renames Table_Map.Next; package Table_List is new Gen.Model.List (T => Definition, T_Access => Definition_Access); private type Association_Definition is new Column_Definition with null record; end Gen.Model.Tables;
Declare Set_Sql_Length procedure to set/verify the sql length of a column
Declare Set_Sql_Length procedure to set/verify the sql length of a column
Ada
apache-2.0
stcarrez/dynamo,stcarrez/dynamo,stcarrez/dynamo
ef431c676e93d26043651a898b0362ffc034b593
src/natools-cron.adb
src/natools-cron.adb
------------------------------------------------------------------------------ -- Copyright (c) 2014-2017, Natacha Porté -- -- -- -- Permission to use, copy, modify, and distribute this software for any -- -- purpose with or without fee is hereby granted, provided that the above -- -- copyright notice and this permission notice appear in all copies. -- -- -- -- THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES -- -- WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF -- -- MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR -- -- ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES -- -- WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN -- -- ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF -- -- OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. -- ------------------------------------------------------------------------------ ------------------------------------------------------------------------------ -- IMPLEMENTATION NOTE: -- -- In case of synchronized callbacks (same Origin and Period), there is a -- -- collision on the internal map key. Since it is not expected to happen -- -- often, a simple but not-so-efficient solution is used: -- -- When a collision is encountered, the callback is replaced by an -- -- Event_List callback seeded with the existing callback and the new one. -- -- When removing a callback, if it's not found directly, and second linear -- -- is performed, looking for Event_List objects and removing it from them. -- ------------------------------------------------------------------------------ package body Natools.Cron is function Create_Event_List (Ref_1, Ref_2 : Callback_Refs.Reference) return Callback_Refs.Reference; -- Create an Event_List object containing Ref_1 and Ref_2, -- and return a reference to it. ------------------------ -- Helper Subprograms -- ------------------------ function "<" (Left, Right : Periodic_Time) return Boolean is use type Ada.Calendar.Time; begin return Left.Origin < Right.Origin or else (Left.Origin = Right.Origin and then Left.Period < Right.Period); end "<"; function Create_Event_List (Ref_1, Ref_2 : Callback_Refs.Reference) return Callback_Refs.Reference is function Create return Callback'Class; function Create return Callback'Class is Result : Event_List; begin Result.Append (Ref_1); Result.Append (Ref_2); return Result; end Create; begin return Callback_Refs.Create (Create'Access); end Create_Event_List; ---------------------- -- Public Interface -- ---------------------- function Create (Time : in Periodic_Time; Callback : in Cron.Callback'Class) return Cron_Entry is begin return Result : Cron_Entry do Result.Set (Time, Callback); end return; end Create; function Create (Origin : in Ada.Calendar.Time; Callback : in Cron.Callback'Class) return Cron_Entry is begin return Result : Cron_Entry do Result.Set (Origin, Callback); end return; end Create; function Create (Period : in Duration; Callback : in Cron.Callback'Class) return Cron_Entry is begin return Result : Cron_Entry do Result.Set (Period, Callback); end return; end Create; procedure Set (Self : in out Cron_Entry; Time : in Periodic_Time; Callback : in Cron.Callback'Class) is function Create return Cron.Callback'Class; function Create return Cron.Callback'Class is begin return Callback; end Create; begin Self.Reset; Self.Callback.Replace (Create'Access); Database.Insert (Time, Self.Callback); end Set; procedure Set (Self : in out Cron_Entry; Origin : in Ada.Calendar.Time; Callback : in Cron.Callback'Class) is begin Set (Self, (Origin, 0.0), Callback); end Set; procedure Set (Self : in out Cron_Entry; Period : in Duration; Callback : in Cron.Callback'Class) is begin Set (Self, (Ada.Calendar.Clock, Period), Callback); end Set; overriding procedure Finalize (Object : in out Cron_Entry) is begin if not Object.Callback.Is_Empty then Object.Reset; end if; end Finalize; procedure Reset (Self : in out Cron_Entry) is begin if not Self.Callback.Is_Empty then Database.Remove (Self.Callback); Self.Callback.Reset; end if; end Reset; ------------------------ -- Protected Database -- ------------------------ protected body Database is procedure Insert (Time : in Periodic_Time; Callback : in Callback_Refs.Reference) is use type Ada.Calendar.Time; Now : constant Ada.Calendar.Time := Ada.Calendar.Clock; Actual_Time : Periodic_Time := Time; begin if Actual_Time.Period > 0.0 then while Actual_Time.Origin < Now loop Actual_Time.Origin := Actual_Time.Origin + Actual_Time.Period; end loop; end if; if Map.Is_Empty then if Global_Worker /= null and then Global_Worker.all'Terminated then Unchecked_Free (Global_Worker); end if; if Global_Worker = null then Global_Worker := new Worker; end if; else if Actual_Time < Map.First_Key then First_Changed := True; end if; end if; declare Position : Entry_Maps.Cursor; Inserted : Boolean; Previous : Callback_Refs.Reference; begin Map.Insert (Actual_Time, Callback, Position, Inserted); if not Inserted then Previous := Entry_Maps.Element (Position); if Previous.Update.Data.all in Event_List then Append (Event_List (Previous.Update.Data.all), Callback); else Map.Replace_Element (Position, Create_Event_List (Previous, Callback)); end if; end if; end; end Insert; procedure Remove (Callback : in Callback_Refs.Reference) is use type Callback_Refs.Reference; Cursor : Entry_Maps.Cursor := Map.First; Is_First : Boolean := True; begin while Entry_Maps.Has_Element (Cursor) loop if Entry_Maps.Element (Cursor) = Callback then Map.Delete (Cursor); if Is_First then First_Changed := True; end if; return; end if; Entry_Maps.Next (Cursor); Is_First := False; end loop; Is_First := True; Cursor := Map.First; while Entry_Maps.Has_Element (Cursor) loop if Entry_Maps.Element (Cursor).Update.Data.all in Event_List then declare Mutator : constant Callback_Refs.Mutator := Entry_Maps.Element (Cursor).Update; List : Event_List renames Event_List (Mutator.Data.all); Removed : Boolean; begin List.Remove (Callback, Removed); if Removed then if List.Is_Empty then Map.Delete (Cursor); if Is_First then First_Changed := True; end if; end if; return; end if; end; end if; Entry_Maps.Next (Cursor); Is_First := False; end loop; end Remove; procedure Update (Callback : in Callback_Refs.Reference) is use type Callback_Refs.Reference; Cursor : Entry_Maps.Cursor := Map.First; begin Search : while Entry_Maps.Has_Element (Cursor) loop if Entry_Maps.Element (Cursor) = Callback then declare Old_Time : constant Periodic_Time := Entry_Maps.Key (Cursor); begin Map.Delete (Cursor); if Old_Time.Period > 0.0 then Insert (Old_Time, Callback); end if; end; exit Search; end if; Entry_Maps.Next (Cursor); end loop Search; end Update; procedure Get_First (Time : out Periodic_Time; Callback : out Callback_Refs.Reference) is Cursor : constant Entry_Maps.Cursor := Map.First; begin if Entry_Maps.Has_Element (Cursor) then Time := Entry_Maps.Key (Cursor); Callback := Entry_Maps.Element (Cursor); else Callback := Callback_Refs.Null_Reference; end if; First_Changed := False; end Get_First; procedure Get_Event_List (Source : in Event_List; List : out Event_Lists.List) is begin List := Source.List; end Get_Event_List; entry Update_Notification when First_Changed is begin null; end Update_Notification; end Database; ----------------- -- Worker Task -- ----------------- task body Worker is Time : Periodic_Time; Callback : Callback_Refs.Reference; Waiting : Boolean; begin Main : loop Waiting := True; Wait_Loop : while Waiting loop Database.Get_First (Time, Callback); exit Main when Callback.Is_Empty; select Database.Update_Notification; or delay until Time.Origin; Waiting := False; end select; end loop Wait_Loop; Callback.Update.Data.Run; Database.Update (Callback); end loop Main; end Worker; ---------------- -- Event List -- ---------------- overriding procedure Run (Self : in out Event_List) is Local_List : Event_Lists.List; begin Database.Get_Event_List (Self, Local_List); for Ref of Local_List loop Ref.Update.Data.Run; end loop; end Run; procedure Append (Self : in out Event_List; Ref : in Callback_Refs.Reference) is begin Self.List.Append (Ref); end Append; procedure Remove (Self : in out Event_List; Ref : in Callback_Refs.Reference; Removed : out Boolean) is use type Callback_Refs.Reference; Cursor : Event_Lists.Cursor := Self.List.First; begin Removed := False; while Event_Lists.Has_Element (Cursor) loop if Event_Lists.Element (Cursor) = Ref then Self.List.Delete (Cursor); Removed := True; return; end if; Event_Lists.Next (Cursor); end loop; end Remove; function Is_Empty (Self : Event_List) return Boolean is begin return Self.List.Is_Empty; end Is_Empty; end Natools.Cron;
------------------------------------------------------------------------------ -- Copyright (c) 2014-2017, Natacha Porté -- -- -- -- Permission to use, copy, modify, and distribute this software for any -- -- purpose with or without fee is hereby granted, provided that the above -- -- copyright notice and this permission notice appear in all copies. -- -- -- -- THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES -- -- WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF -- -- MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR -- -- ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES -- -- WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN -- -- ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF -- -- OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. -- ------------------------------------------------------------------------------ ------------------------------------------------------------------------------ -- IMPLEMENTATION NOTE: -- -- In case of synchronized callbacks (same Origin and Period), there is a -- -- collision on the internal map key. Since it is not expected to happen -- -- often, a simple but not-so-efficient solution is used: -- -- When a collision is encountered, the callback is replaced by an -- -- Event_List callback seeded with the existing callback and the new one. -- -- When removing a callback, if it's not found directly, and second linear -- -- is performed, looking for Event_List objects and removing it from them. -- ------------------------------------------------------------------------------ package body Natools.Cron is function Create_Event_List (Ref_1, Ref_2 : Callback_Refs.Reference) return Callback_Refs.Reference; -- Create an Event_List object containing Ref_1 and Ref_2, -- and return a reference to it. ------------------------ -- Helper Subprograms -- ------------------------ function "<" (Left, Right : Periodic_Time) return Boolean is use type Ada.Calendar.Time; begin return Left.Origin < Right.Origin or else (Left.Origin = Right.Origin and then Left.Period < Right.Period); end "<"; function Create_Event_List (Ref_1, Ref_2 : Callback_Refs.Reference) return Callback_Refs.Reference is function Create return Callback'Class; function Create return Callback'Class is Result : Event_List; begin Result.Append (Ref_1); Result.Append (Ref_2); return Result; end Create; begin return Callback_Refs.Create (Create'Access); end Create_Event_List; ---------------------- -- Public Interface -- ---------------------- function Create (Time : in Periodic_Time; Callback : in Cron.Callback'Class) return Cron_Entry is begin return Result : Cron_Entry do Result.Set (Time, Callback); end return; end Create; function Create (Origin : in Ada.Calendar.Time; Callback : in Cron.Callback'Class) return Cron_Entry is begin return Result : Cron_Entry do Result.Set (Origin, Callback); end return; end Create; function Create (Period : in Duration; Callback : in Cron.Callback'Class) return Cron_Entry is begin return Result : Cron_Entry do Result.Set (Period, Callback); end return; end Create; procedure Set (Self : in out Cron_Entry; Time : in Periodic_Time; Callback : in Cron.Callback'Class) is function Create return Cron.Callback'Class; function Create return Cron.Callback'Class is begin return Callback; end Create; begin Self.Reset; Self.Callback.Replace (Create'Access); Database.Insert (Time, Self.Callback); end Set; procedure Set (Self : in out Cron_Entry; Origin : in Ada.Calendar.Time; Callback : in Cron.Callback'Class) is begin Set (Self, (Origin, 0.0), Callback); end Set; procedure Set (Self : in out Cron_Entry; Period : in Duration; Callback : in Cron.Callback'Class) is begin Set (Self, (Ada.Calendar.Clock, Period), Callback); end Set; overriding procedure Finalize (Object : in out Cron_Entry) is begin if not Object.Callback.Is_Empty then Object.Reset; end if; end Finalize; procedure Reset (Self : in out Cron_Entry) is begin if not Self.Callback.Is_Empty then Database.Remove (Self.Callback); Self.Callback.Reset; end if; end Reset; ------------------------ -- Protected Database -- ------------------------ protected body Database is procedure Insert (Time : in Periodic_Time; Callback : in Callback_Refs.Reference) is use type Ada.Calendar.Time; Now : constant Ada.Calendar.Time := Ada.Calendar.Clock; Actual_Time : Periodic_Time := Time; begin if Actual_Time.Period > 0.0 then while Actual_Time.Origin < Now loop Actual_Time.Origin := Actual_Time.Origin + Actual_Time.Period; end loop; end if; if Map.Is_Empty then if Global_Worker /= null and then Global_Worker.all'Terminated then Unchecked_Free (Global_Worker); end if; if Global_Worker = null then Global_Worker := new Worker; end if; else if Actual_Time < Map.First_Key then First_Changed := True; end if; end if; declare Position : Entry_Maps.Cursor; Inserted : Boolean; Previous : Callback_Refs.Reference; begin Map.Insert (Actual_Time, Callback, Position, Inserted); if not Inserted then Previous := Entry_Maps.Element (Position); if Previous.Query.Data.all in Event_List then if Callback.Query.Data.all in Event_List then for I of Event_List (Callback.Query.Data.all).List loop Append (Event_List (Previous.Update.Data.all), I); end loop; else Append (Event_List (Previous.Update.Data.all), Callback); end if; elsif Callback.Query.Data.all in Event_List then Append (Event_List (Callback.Update.Data.all), Previous); Map.Replace_Element (Position, Callback); else Map.Replace_Element (Position, Create_Event_List (Previous, Callback)); end if; end if; end; end Insert; procedure Remove (Callback : in Callback_Refs.Reference) is use type Callback_Refs.Reference; Cursor : Entry_Maps.Cursor := Map.First; Is_First : Boolean := True; begin while Entry_Maps.Has_Element (Cursor) loop if Entry_Maps.Element (Cursor) = Callback then Map.Delete (Cursor); if Is_First then First_Changed := True; end if; return; end if; Entry_Maps.Next (Cursor); Is_First := False; end loop; Is_First := True; Cursor := Map.First; while Entry_Maps.Has_Element (Cursor) loop if Entry_Maps.Element (Cursor).Update.Data.all in Event_List then declare Mutator : constant Callback_Refs.Mutator := Entry_Maps.Element (Cursor).Update; List : Event_List renames Event_List (Mutator.Data.all); Removed : Boolean; begin List.Remove (Callback, Removed); if Removed then if List.Is_Empty then Map.Delete (Cursor); if Is_First then First_Changed := True; end if; end if; return; end if; end; end if; Entry_Maps.Next (Cursor); Is_First := False; end loop; end Remove; procedure Update (Callback : in Callback_Refs.Reference) is use type Callback_Refs.Reference; Cursor : Entry_Maps.Cursor := Map.First; begin Search : while Entry_Maps.Has_Element (Cursor) loop if Entry_Maps.Element (Cursor) = Callback then declare Old_Time : constant Periodic_Time := Entry_Maps.Key (Cursor); begin Map.Delete (Cursor); if Old_Time.Period > 0.0 then Insert (Old_Time, Callback); end if; end; exit Search; end if; Entry_Maps.Next (Cursor); end loop Search; end Update; procedure Get_First (Time : out Periodic_Time; Callback : out Callback_Refs.Reference) is Cursor : constant Entry_Maps.Cursor := Map.First; begin if Entry_Maps.Has_Element (Cursor) then Time := Entry_Maps.Key (Cursor); Callback := Entry_Maps.Element (Cursor); else Callback := Callback_Refs.Null_Reference; end if; First_Changed := False; end Get_First; procedure Get_Event_List (Source : in Event_List; List : out Event_Lists.List) is begin List := Source.List; end Get_Event_List; entry Update_Notification when First_Changed is begin null; end Update_Notification; end Database; ----------------- -- Worker Task -- ----------------- task body Worker is Time : Periodic_Time; Callback : Callback_Refs.Reference; Waiting : Boolean; begin Main : loop Waiting := True; Wait_Loop : while Waiting loop Database.Get_First (Time, Callback); exit Main when Callback.Is_Empty; select Database.Update_Notification; or delay until Time.Origin; Waiting := False; end select; end loop Wait_Loop; Callback.Update.Data.Run; Database.Update (Callback); end loop Main; end Worker; ---------------- -- Event List -- ---------------- overriding procedure Run (Self : in out Event_List) is Local_List : Event_Lists.List; begin Database.Get_Event_List (Self, Local_List); for Ref of Local_List loop Ref.Update.Data.Run; end loop; end Run; procedure Append (Self : in out Event_List; Ref : in Callback_Refs.Reference) is begin Self.List.Append (Ref); end Append; procedure Remove (Self : in out Event_List; Ref : in Callback_Refs.Reference; Removed : out Boolean) is use type Callback_Refs.Reference; Cursor : Event_Lists.Cursor := Self.List.First; begin Removed := False; while Event_Lists.Has_Element (Cursor) loop if Event_Lists.Element (Cursor) = Ref then Self.List.Delete (Cursor); Removed := True; return; end if; Event_Lists.Next (Cursor); end loop; end Remove; function Is_Empty (Self : Event_List) return Boolean is begin return Self.List.Is_Empty; end Is_Empty; end Natools.Cron;
fix fusion of even list
cron: fix fusion of even list
Ada
isc
faelys/natools
8ef37c8207d0a322a4577cc8ab7496c5cc2bc9e7
tests/src/generic_test_transforms_quaternions.adb
tests/src/generic_test_transforms_quaternions.adb
-- SPDX-License-Identifier: Apache-2.0 -- -- Copyright (c) 2017 onox <[email protected]> -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. with Ada.Numerics.Generic_Elementary_Functions; with AUnit.Assertions; with AUnit.Test_Caller; with AUnit.Test_Fixtures; package body Generic_Test_Transforms_Quaternions is use Orka; use Quaternions; use AUnit.Assertions; use type Vector4; subtype Element_Type is Vectors.Element_Type; use type Element_Type; package EF is new Ada.Numerics.Generic_Elementary_Functions (Element_Type); function To_Radians (Angle : Element_Type) return Element_Type renames Vectors.To_Radians; function Is_Equivalent (Expected, Result : Element_Type) return Boolean is (abs (Result - Expected) <= 2.0 * Element_Type'Model_Epsilon); procedure Assert_Equivalent (Expected, Result : Vector4) is begin for I in Index_4D loop Assert (Is_Equivalent (Expected (I), Result (I)), "Unexpected element " & Expected (I)'Image & " instead of " & Result (I)'Image & " at " & I'Image); end loop; end Assert_Equivalent; procedure Assert_Equivalent (Expected, Result : Quaternion) is begin for I in Index_4D loop Assert (Is_Equivalent (Expected (I), Result (I)), "Unexpected element " & Expected (I)'Image & " instead of " & Result (I)'Image & " at " & I'Image); end loop; end Assert_Equivalent; type Test is new AUnit.Test_Fixtures.Test_Fixture with null record; procedure Test_Multiplication (Object : in out Test) is Half_Angle : constant Element_Type := 45.0; begin declare Axis : constant Vector4 := Vectors.Normalize ((1.0, 2.0, 3.0, 0.0)); Sin_Value : constant Element_Type := EF.Sin (Half_Angle, 360.0); Cos_Value : constant Element_Type := EF.Cos (Half_Angle, 360.0); Result : constant Quaternion := R (Axis, To_Radians (Half_Angle)) * R (Axis, To_Radians (Half_Angle)); Expected : constant Quaternion := (Axis (X) * Sin_Value, Axis (Y) * Sin_Value, Axis (Z) * Sin_Value, Cos_Value); begin Assert_Equivalent (Expected, Result); Assert (Normalized (Result), "Result not normalized"); end; declare Axis : constant Vector4 := (1.0, 0.0, 0.0, 0.0); Angle_Radians : constant Element_Type := To_Radians (30.0); Rotation : constant Quaternion := R (Axis, Angle_Radians) * R (Axis, Angle_Radians) * R (Axis, Angle_Radians); Expected : constant Vector4 := (0.0, 0.0, 1.0, 0.0); Result : constant Vector4 := Rotate ((0.0, 1.0, 0.0, 0.0), Rotation); begin Assert_Equivalent (Expected, Result); end; end Test_Multiplication; procedure Test_Conjugate (Object : in out Test) is Elements : constant Quaternion := (1.0, 2.0, 3.0, 4.0); Expected : constant Quaternion := (-1.0, -2.0, -3.0, 4.0); Result : constant Quaternion := Conjugate (Elements); begin Assert_Equivalent (Expected, Result); end Test_Conjugate; procedure Test_Norm (Object : in out Test) is Elements_1 : constant Quaternion := (1.0, 2.0, 3.0, 4.0); Elements_2 : constant Quaternion := (-1.0, 2.0, -3.0, 4.0); Elements_3 : constant Quaternion := (0.0, 0.0, 0.0, 0.0); Result_1 : constant Element_Type := Norm (Elements_1); Result_2 : constant Element_Type := Norm (Elements_2); Result_3 : constant Element_Type := Norm (Elements_3); Expected_1 : constant Element_Type := EF.Sqrt (30.0); Expected_2 : constant Element_Type := EF.Sqrt (30.0); Expected_3 : constant Element_Type := 0.0; begin Assert (Is_Equivalent (Expected_1, Result_1), "Unexpected Single " & Result_1'Image); Assert (Is_Equivalent (Expected_2, Result_2), "Unexpected Single " & Result_2'Image); Assert (Is_Equivalent (Expected_3, Result_3), "Unexpected Single " & Result_3'Image); end Test_Norm; procedure Test_Normalize (Object : in out Test) is Elements : constant Quaternion := (1.0, 2.0, 3.0, 4.0); begin Assert (not Normalized (Elements), "Elements is unexpectedly a unit quaternion"); declare Result : constant Quaternion := Normalize (Elements); begin Assert (Normalized (Result), "Result not normalized"); end; end Test_Normalize; procedure Test_Normalized (Object : in out Test) is Elements_1 : constant Quaternion := (0.0, 0.0, 0.0, 1.0); Elements_2 : constant Quaternion := (0.5, 0.5, 0.5, -0.5); Elements_3 : constant Quaternion := (0.0, -1.0, 0.0, 0.0); Elements_4 : constant Quaternion := (1.0, 2.0, 3.0, 4.0); begin Assert (Normalized (Elements_1), "Elements_1 not normalized"); Assert (Normalized (Elements_2), "Elements_2 not normalized"); Assert (Normalized (Elements_3), "Elements_3 not normalized"); Assert (not Normalized (Elements_4), "Elements_4 normalized"); end Test_Normalized; procedure Test_Rotate_Axis_Angle (Object : in out Test) is Axis : constant Vector4 := Vectors.Normalize ((1.0, 2.0, 3.0, 0.0)); Angle : constant Element_Type := 90.0; Sin_Value : constant Element_Type := EF.Sin (45.0, 360.0); Cos_Value : constant Element_Type := EF.Cos (45.0, 360.0); Result : constant Quaternion := R (Axis, To_Radians (Angle)); Expected : constant Quaternion := (Axis (X) * Sin_Value, Axis (Y) * Sin_Value, Axis (Z) * Sin_Value, Cos_Value); begin Assert_Equivalent (Expected, Result); Assert (Normalized (Result), "Result not normalized"); end Test_Rotate_Axis_Angle; procedure Test_Rotate_Vectors (Object : in out Test) is Start_Vector : constant Vector4 := (0.0, 1.0, 0.0, 0.0); End_Vector : constant Vector4 := (0.0, 0.0, 1.0, 0.0); Axis : constant Vector4 := (1.0, 0.0, 0.0, 0.0); Angle : constant Element_Type := 90.0; Expected_1 : constant Quaternion := R (Axis, To_Radians (Angle)); Result_1 : constant Quaternion := R (Start_Vector, End_Vector); Expected_2 : constant Quaternion := R (Axis, To_Radians (-Angle)); Result_2 : constant Quaternion := R (End_Vector, Start_Vector); begin Assert_Equivalent (Expected_1, Result_1); Assert_Equivalent (Expected_2, Result_2); end Test_Rotate_Vectors; procedure Test_Rotate (Object : in out Test) is Axis : constant Vector4 := (1.0, 0.0, 0.0, 0.0); Angle : constant Element_Type := 90.0; Rotation : constant Quaternion := R (Axis, To_Radians (Angle)); Expected : constant Vector4 := (0.0, 0.0, 1.0, 0.0); Result : constant Vector4 := Rotate ((0.0, 1.0, 0.0, 0.0), Rotation); begin Assert_Equivalent (Expected, Result); end Test_Rotate; procedure Test_Slerp (Object : in out Test) is Axis : constant Vector4 := (1.0, 0.0, 0.0, 0.0); Angle : constant Element_Type := 45.0; Start_Quaternion : constant Quaternion := R (Axis, To_Radians (0.0)); End_Quaternion : constant Quaternion := R (Axis, To_Radians (90.0)); Expected : constant Quaternion := R (Axis, To_Radians (Angle)); Result : constant Quaternion := Slerp (Start_Quaternion, End_Quaternion, 0.5); begin Assert_Equivalent (Expected, Result); end Test_Slerp; ---------------------------------------------------------------------------- package Caller is new AUnit.Test_Caller (Test); Test_Suite : aliased AUnit.Test_Suites.Test_Suite; function Suite return AUnit.Test_Suites.Access_Test_Suite is Name : constant String := "(Transforms - " & Suite_Name & " - Quaternions) "; begin Test_Suite.Add_Test (Caller.Create (Name & "Test '*' operator", Test_Multiplication'Access)); Test_Suite.Add_Test (Caller.Create (Name & "Test Conjugate function", Test_Conjugate'Access)); Test_Suite.Add_Test (Caller.Create (Name & "Test Norm function", Test_Norm'Access)); Test_Suite.Add_Test (Caller.Create (Name & "Test Normalize function", Test_Normalize'Access)); Test_Suite.Add_Test (Caller.Create (Name & "Test Normalized function", Test_Normalized'Access)); Test_Suite.Add_Test (Caller.Create (Name & "Test Rotate_Axis_Angle function", Test_Rotate_Axis_Angle'Access)); Test_Suite.Add_Test (Caller.Create (Name & "Test Rotate_Vectors function", Test_Rotate_Vectors'Access)); Test_Suite.Add_Test (Caller.Create (Name & "Test Rotate function", Test_Rotate'Access)); Test_Suite.Add_Test (Caller.Create (Name & "Test Slerp function", Test_Slerp'Access)); return Test_Suite'Access; end Suite; end Generic_Test_Transforms_Quaternions;
-- SPDX-License-Identifier: Apache-2.0 -- -- Copyright (c) 2017 onox <[email protected]> -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. with Ada.Numerics.Generic_Elementary_Functions; with AUnit.Assertions; with AUnit.Test_Caller; with AUnit.Test_Fixtures; package body Generic_Test_Transforms_Quaternions is use Orka; use Quaternions; use AUnit.Assertions; use type Vector4; subtype Element_Type is Vectors.Element_Type; use type Element_Type; package EF is new Ada.Numerics.Generic_Elementary_Functions (Element_Type); function To_Radians (Angle : Element_Type) return Element_Type renames Vectors.To_Radians; function Is_Equivalent (Expected, Result : Element_Type) return Boolean is (abs (Result - Expected) <= Element_Type'Model_Epsilon + 1.0e-05 * abs Expected); procedure Assert_Equivalent (Expected, Result : Vector4) is begin for I in Index_4D loop Assert (Is_Equivalent (Expected (I), Result (I)), "Unexpected element " & Expected (I)'Image & " instead of " & Result (I)'Image & " at " & I'Image); end loop; end Assert_Equivalent; procedure Assert_Equivalent (Expected, Result : Quaternion) is begin for I in Index_4D loop Assert (Is_Equivalent (Expected (I), Result (I)), "Unexpected element " & Expected (I)'Image & " instead of " & Result (I)'Image & " at " & I'Image); end loop; end Assert_Equivalent; type Test is new AUnit.Test_Fixtures.Test_Fixture with null record; procedure Test_Multiplication (Object : in out Test) is Half_Angle : constant Element_Type := 45.0; begin declare Axis : constant Vector4 := Vectors.Normalize ((1.0, 2.0, 3.0, 0.0)); Sin_Value : constant Element_Type := EF.Sin (Half_Angle, 360.0); Cos_Value : constant Element_Type := EF.Cos (Half_Angle, 360.0); Result : constant Quaternion := R (Axis, To_Radians (Half_Angle)) * R (Axis, To_Radians (Half_Angle)); Expected : constant Quaternion := (Axis (X) * Sin_Value, Axis (Y) * Sin_Value, Axis (Z) * Sin_Value, Cos_Value); begin Assert_Equivalent (Expected, Result); Assert (Normalized (Result), "Result not normalized"); end; declare Axis : constant Vector4 := (1.0, 0.0, 0.0, 0.0); Angle_Radians : constant Element_Type := To_Radians (30.0); Rotation : constant Quaternion := R (Axis, Angle_Radians) * R (Axis, Angle_Radians) * R (Axis, Angle_Radians); Expected : constant Vector4 := (0.0, 0.0, 1.0, 0.0); Result : constant Vector4 := Rotate ((0.0, 1.0, 0.0, 0.0), Rotation); begin Assert_Equivalent (Expected, Result); end; end Test_Multiplication; procedure Test_Conjugate (Object : in out Test) is Elements : constant Quaternion := (1.0, 2.0, 3.0, 4.0); Expected : constant Quaternion := (-1.0, -2.0, -3.0, 4.0); Result : constant Quaternion := Conjugate (Elements); begin Assert_Equivalent (Expected, Result); end Test_Conjugate; procedure Test_Norm (Object : in out Test) is Elements_1 : constant Quaternion := (1.0, 2.0, 3.0, 4.0); Elements_2 : constant Quaternion := (-1.0, 2.0, -3.0, 4.0); Elements_3 : constant Quaternion := (0.0, 0.0, 0.0, 0.0); Result_1 : constant Element_Type := Norm (Elements_1); Result_2 : constant Element_Type := Norm (Elements_2); Result_3 : constant Element_Type := Norm (Elements_3); Expected_1 : constant Element_Type := EF.Sqrt (30.0); Expected_2 : constant Element_Type := EF.Sqrt (30.0); Expected_3 : constant Element_Type := 0.0; begin Assert (Is_Equivalent (Expected_1, Result_1), "Unexpected Single " & Result_1'Image); Assert (Is_Equivalent (Expected_2, Result_2), "Unexpected Single " & Result_2'Image); Assert (Is_Equivalent (Expected_3, Result_3), "Unexpected Single " & Result_3'Image); end Test_Norm; procedure Test_Normalize (Object : in out Test) is Elements : constant Quaternion := (1.0, 2.0, 3.0, 4.0); begin Assert (not Normalized (Elements), "Elements is unexpectedly a unit quaternion"); declare Result : constant Quaternion := Normalize (Elements); begin Assert (Normalized (Result), "Result not normalized"); end; end Test_Normalize; procedure Test_Normalized (Object : in out Test) is Elements_1 : constant Quaternion := (0.0, 0.0, 0.0, 1.0); Elements_2 : constant Quaternion := (0.5, 0.5, 0.5, -0.5); Elements_3 : constant Quaternion := (0.0, -1.0, 0.0, 0.0); Elements_4 : constant Quaternion := (1.0, 2.0, 3.0, 4.0); begin Assert (Normalized (Elements_1), "Elements_1 not normalized"); Assert (Normalized (Elements_2), "Elements_2 not normalized"); Assert (Normalized (Elements_3), "Elements_3 not normalized"); Assert (not Normalized (Elements_4), "Elements_4 normalized"); end Test_Normalized; procedure Test_Rotate_Axis_Angle (Object : in out Test) is Axis : constant Vector4 := Vectors.Normalize ((1.0, 2.0, 3.0, 0.0)); Angle : constant Element_Type := 90.0; Sin_Value : constant Element_Type := EF.Sin (45.0, 360.0); Cos_Value : constant Element_Type := EF.Cos (45.0, 360.0); Result : constant Quaternion := R (Axis, To_Radians (Angle)); Expected : constant Quaternion := (Axis (X) * Sin_Value, Axis (Y) * Sin_Value, Axis (Z) * Sin_Value, Cos_Value); begin Assert_Equivalent (Expected, Result); Assert (Normalized (Result), "Result not normalized"); end Test_Rotate_Axis_Angle; procedure Test_Axis_Angle (Object : in out Test) is Axis : constant Vector4 := Vectors.Normalize ((1.0, 2.0, 3.0, 0.0)); Angle : constant Element_Type := 90.0; Expected : constant Axis_Angle := (Axis => Vectors.Direction (Axis), Angle => To_Radians (Angle)); Actual : constant Axis_Angle := To_Axis_Angle (From_Axis_Angle (Expected)); begin Assert_Equivalent (Vector4 (Expected.Axis), Vector4 (Actual.Axis)); Assert (Is_Equivalent (Expected.Angle, Actual.Angle), "Unexpected angle " & Actual.Angle'Image); end Test_Axis_Angle; procedure Test_Axis_Angle_No_Rotation (Object : in out Test) is Actual : constant Element_Type := To_Axis_Angle (Identity).Angle; Expected : constant Element_Type := 0.0; begin Assert (Is_Equivalent (Expected, Actual), "Unexpected angle " & Actual'Image); end Test_Axis_Angle_No_Rotation; procedure Test_Rotate_Vectors (Object : in out Test) is Start_Vector : constant Vector4 := (0.0, 1.0, 0.0, 0.0); End_Vector : constant Vector4 := (0.0, 0.0, 1.0, 0.0); Axis : constant Vector4 := (1.0, 0.0, 0.0, 0.0); Angle : constant Element_Type := 90.0; Expected_1 : constant Quaternion := R (Axis, To_Radians (Angle)); Result_1 : constant Quaternion := R (Start_Vector, End_Vector); Expected_2 : constant Quaternion := R (Axis, To_Radians (-Angle)); Result_2 : constant Quaternion := R (End_Vector, Start_Vector); begin Assert_Equivalent (Expected_1, Result_1); Assert_Equivalent (Expected_2, Result_2); end Test_Rotate_Vectors; procedure Test_Rotate (Object : in out Test) is Axis : constant Vector4 := (1.0, 0.0, 0.0, 0.0); Angle : constant Element_Type := 90.0; Rotation : constant Quaternion := R (Axis, To_Radians (Angle)); Expected : constant Vector4 := (0.0, 0.0, 1.0, 0.0); Result : constant Vector4 := Rotate ((0.0, 1.0, 0.0, 0.0), Rotation); begin Assert_Equivalent (Expected, Result); end Test_Rotate; procedure Test_Difference (Object : in out Test) is Axis : constant Vector4 := (1.0, 0.0, 0.0, 0.0); Angle_A : constant Element_Type := 30.0; Angle_B : constant Element_Type := 90.0; Rotation_A : constant Quaternion := R (Axis, To_Radians (Angle_A)); Rotation_B : constant Quaternion := R (Axis, To_Radians (Angle_B)); Actual : constant Axis_Angle := To_Axis_Angle (Difference (Rotation_A, Rotation_B)); Expected : constant Axis_Angle := (Axis => Vectors.Direction (Axis), Angle => To_Radians (60.0)); begin Assert_Equivalent (Vector4 (Expected.Axis), Vector4 (Actual.Axis)); Assert (Is_Equivalent (Expected.Angle, Actual.Angle), "Unexpected angle " & Actual.Angle'Image); end Test_Difference; procedure Test_Slerp (Object : in out Test) is Axis : constant Vector4 := (1.0, 0.0, 0.0, 0.0); Angle : constant Element_Type := 45.0; Start_Quaternion : constant Quaternion := R (Axis, To_Radians (0.0)); End_Quaternion : constant Quaternion := R (Axis, To_Radians (90.0)); Expected : constant Quaternion := R (Axis, To_Radians (Angle)); Result : constant Quaternion := Slerp (Start_Quaternion, End_Quaternion, 0.5); begin Assert_Equivalent (Expected, Result); end Test_Slerp; ---------------------------------------------------------------------------- package Caller is new AUnit.Test_Caller (Test); Test_Suite : aliased AUnit.Test_Suites.Test_Suite; function Suite return AUnit.Test_Suites.Access_Test_Suite is Name : constant String := "(Transforms - " & Suite_Name & " - Quaternions) "; begin Test_Suite.Add_Test (Caller.Create (Name & "Test '*' operator", Test_Multiplication'Access)); Test_Suite.Add_Test (Caller.Create (Name & "Test Conjugate function", Test_Conjugate'Access)); Test_Suite.Add_Test (Caller.Create (Name & "Test Norm function", Test_Norm'Access)); Test_Suite.Add_Test (Caller.Create (Name & "Test Normalize function", Test_Normalize'Access)); Test_Suite.Add_Test (Caller.Create (Name & "Test Normalized function", Test_Normalized'Access)); Test_Suite.Add_Test (Caller.Create (Name & "Test to/from Axis_Angle functions", Test_Axis_Angle'Access)); Test_Suite.Add_Test (Caller.Create (Name & "Test To_Axis_Angle function with Identity", Test_Axis_Angle_No_Rotation'Access)); Test_Suite.Add_Test (Caller.Create (Name & "Test Rotate_Axis_Angle function", Test_Rotate_Axis_Angle'Access)); Test_Suite.Add_Test (Caller.Create (Name & "Test Rotate_Vectors function", Test_Rotate_Vectors'Access)); Test_Suite.Add_Test (Caller.Create (Name & "Test Rotate function", Test_Rotate'Access)); Test_Suite.Add_Test (Caller.Create (Name & "Test Difference function", Test_Difference'Access)); Test_Suite.Add_Test (Caller.Create (Name & "Test Slerp function", Test_Slerp'Access)); return Test_Suite'Access; end Suite; end Generic_Test_Transforms_Quaternions;
Increase test coverage of quaternion transforms
tests: Increase test coverage of quaternion transforms Signed-off-by: onox <[email protected]>
Ada
apache-2.0
onox/orka
a639e1ae545be361b3e339629973cf0e0d46ca9f
awa/awaunit/awa-tests.adb
awa/awaunit/awa-tests.adb
----------------------------------------------------------------------- -- AWA tests - AWA Tests Framework -- Copyright (C) 2011, 2012, 2013 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Task_Termination; with Ada.Task_Identification; with Ada.Exceptions; with Ada.Unchecked_Deallocation; with ASF.Server.Tests; with Util.Log.Loggers; with ASF.Tests; with AWA.Applications.Factory; package body AWA.Tests is Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("AWA.Tests"); protected Shutdown is procedure Termination (Cause : in Ada.Task_Termination.Cause_Of_Termination; Id : in Ada.Task_Identification.Task_Id; Ex : in Ada.Exceptions.Exception_Occurrence); end Shutdown; Application_Created : Boolean := False; Application : AWA.Applications.Application_Access := null; Factory : AWA.Applications.Factory.Application_Factory; Service_Filter : aliased AWA.Services.Filters.Service_Filter; protected body Shutdown is procedure Termination (Cause : in Ada.Task_Termination.Cause_Of_Termination; Id : in Ada.Task_Identification.Task_Id; Ex : in Ada.Exceptions.Exception_Occurrence) is pragma Unreferenced (Cause, Id, Ex); procedure Free is new Ada.Unchecked_Deallocation (Object => AWA.Applications.Application'Class, Name => AWA.Applications.Application_Access); begin Free (Application); end Termination; end Shutdown; -- ------------------------------ -- Setup the service context before executing the test. -- ------------------------------ overriding procedure Set_Up (T : in out Test) is pragma Unreferenced (T); begin ASF.Server.Tests.Set_Context (Application.all'Access); end Set_Up; procedure Initialize (Props : in Util.Properties.Manager) is begin Initialize (null, Props, True); end Initialize; -- ------------------------------ -- Called when the testsuite execution has finished. -- ------------------------------ procedure Finish (Status : in Util.XUnit.Status) is pragma Unreferenced (Status); procedure Free is new Ada.Unchecked_Deallocation (Object => AWA.Applications.Application'Class, Name => AWA.Applications.Application_Access); begin if Application_Created then Free (Application); end if; end Finish; -- ------------------------------ -- Initialize the AWA test framework mockup. -- ------------------------------ procedure Initialize (App : in AWA.Applications.Application_Access; Props : in Util.Properties.Manager; Add_Modules : in Boolean) is pragma Unreferenced (Add_Modules); use AWA.Applications; begin -- Create the application unless it is specified as argument. -- Install a shutdown hook to delete the application when the primary task exits. -- This allows to stop the event threads if any. if App = null then Application_Created := True; Application := new Test_Application; Ada.Task_Termination.Set_Specific_Handler (Ada.Task_Identification.Current_Task, Shutdown.Termination'Access); else Application := App; end if; ASF.Tests.Initialize (Props, Application.all'Access, Factory); Application.Add_Filter ("service", Service_Filter'Access); Application.Add_Filter_Mapping (Name => "service", Pattern => "*.html"); end Initialize; -- ------------------------------ -- Get the test application. -- ------------------------------ function Get_Application return AWA.Applications.Application_Access is begin return Application; end Get_Application; -- ------------------------------ -- Set the application context to simulate a web request context. -- ------------------------------ procedure Set_Application_Context is begin ASF.Server.Tests.Set_Context (Application.all'Access); end Set_Application_Context; -- ------------------------------ -- Initialize the servlets provided by the application. -- This procedure is called by <b>Initialize</b>. -- It should register the application servlets. -- ------------------------------ overriding procedure Initialize_Servlets (App : in out Test_Application) is begin Log.Info ("Initializing application servlets..."); AWA.Applications.Application (App).Initialize_Servlets; App.Add_Servlet (Name => "faces", Server => App.Faces'Unchecked_Access); App.Add_Servlet (Name => "files", Server => App.Files'Unchecked_Access); App.Add_Servlet (Name => "ajax", Server => App.Ajax'Unchecked_Access); App.Add_Servlet (Name => "measures", Server => App.Measures'Unchecked_Access); -- App.Add_Servlet (Name => "auth", Server => App.Auth'Unchecked_Access); -- App.Add_Servlet (Name => "verify-auth", Server => App.Self.Verify_Auth'Access); end Initialize_Servlets; -- ------------------------------ -- Initialize the filters provided by the application. -- This procedure is called by <b>Initialize</b>. -- It should register the application filters. -- ------------------------------ overriding procedure Initialize_Filters (App : in out Test_Application) is begin Log.Info ("Initializing application filters..."); AWA.Applications.Application (App).Initialize_Filters; App.Add_Filter (Name => "dump", Filter => App.Dump'Access); App.Add_Filter (Name => "measures", Filter => App.Measures'Access); App.Add_Filter (Name => "service", Filter => App.Service_Filter'Access); end Initialize_Filters; end AWA.Tests;
----------------------------------------------------------------------- -- AWA tests - AWA Tests Framework -- Copyright (C) 2011, 2012, 2013, 2014 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Task_Termination; with Ada.Task_Identification; with Ada.Exceptions; with Ada.Unchecked_Deallocation; with ASF.Server.Tests; with Util.Log.Loggers; with ASF.Tests; with AWA.Applications.Factory; with AWA.Tests.Helpers.Users; package body AWA.Tests is Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("AWA.Tests"); protected Shutdown is procedure Termination (Cause : in Ada.Task_Termination.Cause_Of_Termination; Id : in Ada.Task_Identification.Task_Id; Ex : in Ada.Exceptions.Exception_Occurrence); end Shutdown; Application_Created : Boolean := False; Application : AWA.Applications.Application_Access := null; Factory : AWA.Applications.Factory.Application_Factory; Service_Filter : aliased AWA.Services.Filters.Service_Filter; protected body Shutdown is procedure Termination (Cause : in Ada.Task_Termination.Cause_Of_Termination; Id : in Ada.Task_Identification.Task_Id; Ex : in Ada.Exceptions.Exception_Occurrence) is pragma Unreferenced (Cause, Id, Ex); procedure Free is new Ada.Unchecked_Deallocation (Object => AWA.Applications.Application'Class, Name => AWA.Applications.Application_Access); begin Free (Application); end Termination; end Shutdown; -- ------------------------------ -- Setup the service context before executing the test. -- ------------------------------ overriding procedure Set_Up (T : in out Test) is pragma Unreferenced (T); begin ASF.Server.Tests.Set_Context (Application.all'Access); end Set_Up; -- ------------------------------ -- Cleanup after the test execution. -- ------------------------------ overriding procedure Tear_Down (T : in out Test) is begin AWA.Tests.Helpers.Users.Tear_Down; end Tear_Down; procedure Initialize (Props : in Util.Properties.Manager) is begin Initialize (null, Props, True); end Initialize; -- ------------------------------ -- Called when the testsuite execution has finished. -- ------------------------------ procedure Finish (Status : in Util.XUnit.Status) is pragma Unreferenced (Status); procedure Free is new Ada.Unchecked_Deallocation (Object => AWA.Applications.Application'Class, Name => AWA.Applications.Application_Access); begin if Application_Created then Free (Application); end if; end Finish; -- ------------------------------ -- Initialize the AWA test framework mockup. -- ------------------------------ procedure Initialize (App : in AWA.Applications.Application_Access; Props : in Util.Properties.Manager; Add_Modules : in Boolean) is pragma Unreferenced (Add_Modules); use AWA.Applications; begin -- Create the application unless it is specified as argument. -- Install a shutdown hook to delete the application when the primary task exits. -- This allows to stop the event threads if any. if App = null then Application_Created := True; Application := new Test_Application; Ada.Task_Termination.Set_Specific_Handler (Ada.Task_Identification.Current_Task, Shutdown.Termination'Access); else Application := App; end if; ASF.Tests.Initialize (Props, Application.all'Access, Factory); Application.Add_Filter ("service", Service_Filter'Access); Application.Add_Filter_Mapping (Name => "service", Pattern => "*.html"); end Initialize; -- ------------------------------ -- Get the test application. -- ------------------------------ function Get_Application return AWA.Applications.Application_Access is begin return Application; end Get_Application; -- ------------------------------ -- Set the application context to simulate a web request context. -- ------------------------------ procedure Set_Application_Context is begin ASF.Server.Tests.Set_Context (Application.all'Access); end Set_Application_Context; -- ------------------------------ -- Initialize the servlets provided by the application. -- This procedure is called by <b>Initialize</b>. -- It should register the application servlets. -- ------------------------------ overriding procedure Initialize_Servlets (App : in out Test_Application) is begin Log.Info ("Initializing application servlets..."); AWA.Applications.Application (App).Initialize_Servlets; App.Add_Servlet (Name => "faces", Server => App.Faces'Unchecked_Access); App.Add_Servlet (Name => "files", Server => App.Files'Unchecked_Access); App.Add_Servlet (Name => "ajax", Server => App.Ajax'Unchecked_Access); App.Add_Servlet (Name => "measures", Server => App.Measures'Unchecked_Access); -- App.Add_Servlet (Name => "auth", Server => App.Auth'Unchecked_Access); -- App.Add_Servlet (Name => "verify-auth", Server => App.Self.Verify_Auth'Access); end Initialize_Servlets; -- ------------------------------ -- Initialize the filters provided by the application. -- This procedure is called by <b>Initialize</b>. -- It should register the application filters. -- ------------------------------ overriding procedure Initialize_Filters (App : in out Test_Application) is begin Log.Info ("Initializing application filters..."); AWA.Applications.Application (App).Initialize_Filters; App.Add_Filter (Name => "dump", Filter => App.Dump'Access); App.Add_Filter (Name => "measures", Filter => App.Measures'Access); App.Add_Filter (Name => "service", Filter => App.Service_Filter'Access); end Initialize_Filters; end AWA.Tests;
Implement Tear_Down to cleanup the users after the test execution
Implement Tear_Down to cleanup the users after the test execution
Ada
apache-2.0
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
d2185fc9f11a151bb469650ab32fb3a72b3d1c5f
src/definitions.ads
src/definitions.ads
-- This file is covered by the Internet Software Consortium (ISC) License -- Reference: ../License.txt package Definitions is pragma Pure; raven_version_major : constant String := "1"; raven_version_minor : constant String := "71"; copyright_years : constant String := "2015-2021"; raven_tool : constant String := "ravenadm"; variant_standard : constant String := "standard"; contact_nobody : constant String := "nobody"; contact_automaton : constant String := "automaton"; dlgroup_main : constant String := "main"; dlgroup_none : constant String := "none"; options_none : constant String := "none"; options_all : constant String := "all"; broken_all : constant String := "all"; boolean_yes : constant String := "yes"; homepage_none : constant String := "none"; spkg_complete : constant String := "complete"; spkg_docs : constant String := "docs"; spkg_examples : constant String := "examples"; spkg_nls : constant String := "nls"; ports_default : constant String := "floating"; default_ssl : constant String := "libressl"; default_mysql : constant String := "oracle-8.0"; default_lua : constant String := "5.3"; default_perl : constant String := "5.30"; default_pgsql : constant String := "12"; default_php : constant String := "7.4"; default_python3 : constant String := "3.8"; default_ruby : constant String := "2.7"; default_tcltk : constant String := "8.6"; default_firebird : constant String := "2.5"; default_binutils : constant String := "binutils:ravensys"; default_compiler : constant String := "gcc9"; previous_default : constant String := "gcc9"; compiler_version : constant String := "9.3.0"; previous_compiler : constant String := "9.2.0"; binutils_version : constant String := "2.35.1"; previous_binutils : constant String := "2.34"; arc_ext : constant String := ".tzst"; jobs_per_cpu : constant := 2; task_stack_limit : constant := 10_000_000; type supported_opsys is (dragonfly, freebsd, netbsd, openbsd, sunos, linux, macos); type supported_arch is (x86_64, i386, aarch64); type cpu_range is range 1 .. 64; type scanners is range cpu_range'First .. cpu_range'Last; type builders is range cpu_range'First .. cpu_range'Last * jobs_per_cpu; type count_type is (total, success, failure, ignored, skipped); -- Modify following with post-patch sed accordingly platform_type : constant supported_opsys := dragonfly; host_localbase : constant String := "/raven"; raven_var : constant String := "/var/ravenports"; host_pkg8 : constant String := host_localbase & "/sbin/ravensw"; ravenexec : constant String := host_localbase & "/libexec/ravenexec"; end Definitions;
-- This file is covered by the Internet Software Consortium (ISC) License -- Reference: ../License.txt package Definitions is pragma Pure; raven_version_major : constant String := "1"; raven_version_minor : constant String := "72"; copyright_years : constant String := "2015-2021"; raven_tool : constant String := "ravenadm"; variant_standard : constant String := "standard"; contact_nobody : constant String := "nobody"; contact_automaton : constant String := "automaton"; dlgroup_main : constant String := "main"; dlgroup_none : constant String := "none"; options_none : constant String := "none"; options_all : constant String := "all"; broken_all : constant String := "all"; boolean_yes : constant String := "yes"; homepage_none : constant String := "none"; spkg_complete : constant String := "complete"; spkg_docs : constant String := "docs"; spkg_examples : constant String := "examples"; spkg_nls : constant String := "nls"; ports_default : constant String := "floating"; default_ssl : constant String := "libressl"; default_mysql : constant String := "oracle-8.0"; default_lua : constant String := "5.3"; default_perl : constant String := "5.30"; default_pgsql : constant String := "12"; default_php : constant String := "7.4"; default_python3 : constant String := "3.8"; default_ruby : constant String := "2.7"; default_tcltk : constant String := "8.6"; default_firebird : constant String := "2.5"; default_binutils : constant String := "binutils:ravensys"; default_compiler : constant String := "gcc9"; previous_default : constant String := "gcc9"; compiler_version : constant String := "9.3.0"; previous_compiler : constant String := "9.2.0"; binutils_version : constant String := "2.35.1"; previous_binutils : constant String := "2.34"; arc_ext : constant String := ".tzst"; jobs_per_cpu : constant := 2; task_stack_limit : constant := 10_000_000; type supported_opsys is (dragonfly, freebsd, netbsd, openbsd, sunos, linux, macos); type supported_arch is (x86_64, i386, aarch64); type cpu_range is range 1 .. 64; type scanners is range cpu_range'First .. cpu_range'Last; type builders is range cpu_range'First .. cpu_range'Last * jobs_per_cpu; type count_type is (total, success, failure, ignored, skipped); -- Modify following with post-patch sed accordingly platform_type : constant supported_opsys := dragonfly; host_localbase : constant String := "/raven"; raven_var : constant String := "/var/ravenports"; host_pkg8 : constant String := host_localbase & "/sbin/ravensw"; ravenexec : constant String := host_localbase & "/libexec/ravenexec"; end Definitions;
bump version for release
bump version for release
Ada
isc
jrmarino/ravenadm,jrmarino/ravenadm,jrmarino/ravenadm
a7aad96528f01aeecd6456e4b8914f521dd6f8fb
src/gen-artifacts-docs-googlecode.adb
src/gen-artifacts-docs-googlecode.adb
----------------------------------------------------------------------- -- gen-artifacts-docs-googlecode -- Artifact for Googlecode documentation format -- Copyright (C) 2015 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- package body Gen.Artifacts.Docs.Googlecode is -- ------------------------------ -- Get the document name from the file document (ex: <name>.wiki or <name>.md). -- ------------------------------ overriding function Get_Document_Name (Formatter : in Document_Formatter; Document : in File_Document) return String is begin return Ada.Strings.Unbounded.To_String (Document.Name) & ".wiki"; end Get_Document_Name; -- ------------------------------ -- Write a line in the target document formatting the line if necessary. -- ------------------------------ overriding procedure Write_Line (Formatter : in out Document_Formatter; File : in Ada.Text_IO.File_Type; Line : in Line_Type) is begin if Line.Kind = L_LIST then Ada.Text_IO.New_Line (File); Ada.Text_IO.Put (File, Line.Content); Formatter.Need_Newline := True; elsif Line.Kind = L_LIST_ITEM then Ada.Text_IO.Put (File, Line.Content); Formatter.Need_Newline := True; else if Formatter.Need_Newline then Ada.Text_IO.New_Line (File); Formatter.Need_Newline := False; end if; Ada.Text_IO.Put_Line (File, Line.Content); end if; end Write_Line; end Gen.Artifacts.Docs.Googlecode;
----------------------------------------------------------------------- -- gen-artifacts-docs-googlecode -- Artifact for Googlecode documentation format -- Copyright (C) 2015 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- package body Gen.Artifacts.Docs.Googlecode is -- ------------------------------ -- Get the document name from the file document (ex: <name>.wiki or <name>.md). -- ------------------------------ overriding function Get_Document_Name (Formatter : in Document_Formatter; Document : in File_Document) return String is begin return Ada.Strings.Unbounded.To_String (Document.Name) & ".wiki"; end Get_Document_Name; -- ------------------------------ -- Start a new document. -- ------------------------------ overriding procedure Start_Document (Formatter : in out Document_Formatter; Document : in File_Document; File : in Ada.Text_IO.File_Type) is begin Ada.Text_IO.Put_Line (File, "#summary " & Ada.Strings.Unbounded.To_String (Document.Title)); Ada.Text_IO.New_Line (File); end Start_Document; -- ------------------------------ -- Write a line in the target document formatting the line if necessary. -- ------------------------------ overriding procedure Write_Line (Formatter : in out Document_Formatter; File : in Ada.Text_IO.File_Type; Line : in Line_Type) is begin if Line.Kind = L_LIST then Ada.Text_IO.New_Line (File); Ada.Text_IO.Put (File, Line.Content); Formatter.Need_Newline := True; elsif Line.Kind = L_LIST_ITEM then Ada.Text_IO.Put (File, Line.Content); Formatter.Need_Newline := True; else if Formatter.Need_Newline then Ada.Text_IO.New_Line (File); Formatter.Need_Newline := False; end if; Ada.Text_IO.Put_Line (File, Line.Content); end if; end Write_Line; end Gen.Artifacts.Docs.Googlecode;
Implement the Start_Document procedure
Implement the Start_Document procedure
Ada
apache-2.0
stcarrez/dynamo,stcarrez/dynamo,stcarrez/dynamo
58a6dfa4570514dda05ba8e799ff22ee28807fb3
samples/openid.adb
samples/openid.adb
----------------------------------------------------------------------- -- openid -- Example of OpenID 2.0 Authentication -- Copyright (C) 2011, 2012 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Text_IO; with Ada.Exceptions; with Ada.IO_Exceptions; with ASF.Server.Web; with ASF.Applications; with ASF.Applications.Main; with ASF.Servlets.Faces; with ASF.Servlets.Files; with ASF.Servlets.Measures; with ASF.Filters.Dump; with Util.Beans.Objects; with Util.Log.Loggers; with Users; with AWS.Net.SSL; with Security.Openid; with Security.Openid.Servlets; procedure Openid is use ASF.Applications; Log : Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("Openid"); CONTEXT_PATH : constant String := "/openid"; CONFIG_PATH : constant String := "samples.properties"; User : aliased Users.User_Info; App : aliased ASF.Applications.Main.Application; Factory : ASF.Applications.Main.Application_Factory; C : ASF.Applications.Config; -- Application servlets. Faces : aliased ASF.Servlets.Faces.Faces_Servlet; Files : aliased ASF.Servlets.Files.File_Servlet; Perf : aliased ASF.Servlets.Measures.Measure_Servlet; Auth : aliased Security.Openid.Servlets.Request_Auth_Servlet; Verify_Auth : aliased Security.Openid.Servlets.Verify_Auth_Servlet; -- Debug filters. Dump : aliased ASF.Filters.Dump.Dump_Filter; -- Web application server WS : ASF.Server.Web.AWS_Container; begin if not AWS.Net.SSL.Is_Supported then Log.Error ("SSL is not supported by AWS."); Log.Error ("SSL is required for the OpenID connector to connect to OpenID providers."); Log.Error ("Please, rebuild AWS with SSL support."); return; end if; begin C.Load_Properties (CONFIG_PATH); exception when Ada.IO_Exceptions.Name_Error => Log.Error ("Cannot read application configuration file {0}", CONFIG_PATH); end; App.Initialize (C, Factory); App.Register ("samplesMsg", "samples"); App.Set_Global ("contextPath", "/openid"); -- Declare a global bean to identify this sample from within the XHTML files. App.Set_Global ("sampleName", "openid"); App.Set_Global ("version", "0.1"); App.Set_Global ("user", Util.Beans.Objects.To_Object (User'Unchecked_Access, Util.Beans.Objects.STATIC)); -- Register the servlets and filters App.Add_Servlet (Name => "faces", Server => Faces'Unchecked_Access); App.Add_Servlet (Name => "files", Server => Files'Unchecked_Access); App.Add_Servlet (Name => "auth", Server => Auth'Unchecked_Access); App.Add_Servlet (Name => "verify-auth", Server => Verify_Auth'Unchecked_Access); App.Add_Servlet (Name => "perf", Server => Perf'Unchecked_Access); -- Register the filters App.Add_Filter (Name => "perf", Filter => Perf'Unchecked_Access); App.Add_Filter (Name => "dump", Filter => Dump'Unchecked_Access); -- Define servlet mappings App.Add_Mapping (Name => "faces", Pattern => "*.html"); App.Add_Mapping (Name => "files", Pattern => "*.css"); App.Add_Mapping (Name => "files", Pattern => "*.js"); App.Add_Mapping (Name => "files", Pattern => "*.png"); App.Add_Mapping (Name => "files", Pattern => "*.jpg"); App.Add_Mapping (Name => "verify-auth", Pattern => "/auth/verify"); App.Add_Mapping (Name => "auth", Pattern => "/auth/auth/*"); App.Add_Mapping (Name => "perf", Pattern => "/statistics.xml"); -- Install the debug filter. App.Add_Filter_Mapping (Name => "perf", Pattern => "*.html"); App.Add_Filter_Mapping (Name => "dump", Pattern => "*.html"); App.Add_Filter_Mapping (Name => "perf", Pattern => "*.css"); App.Add_Filter_Mapping (Name => "dump", Pattern => "*.css"); App.Add_Filter_Mapping (Name => "perf", Pattern => "*.png"); App.Add_Filter_Mapping (Name => "dump", Pattern => "*.png"); App.Add_Filter_Mapping (Name => "perf", Pattern => "*.jpg"); App.Add_Filter_Mapping (Name => "dump", Pattern => "*.jpg"); App.Add_Filter_Mapping (Name => "perf", Pattern => "/auth/verify"); App.Add_Filter_Mapping (Name => "dump", Pattern => "/auth/verify"); App.Add_Filter_Mapping (Name => "perf", Pattern => "/auth/auth/*"); App.Add_Filter_Mapping (Name => "dump", Pattern => "/auth/auth/*"); WS.Register_Application (CONTEXT_PATH, App'Unchecked_Access); Log.Info ("Connect you browser to: http://localhost:8080/openid/auth/login.html"); WS.Start; delay 600.0; App.Close; exception when E : others => Ada.Text_IO.Put_Line ("Exception in server: " & Ada.Exceptions.Exception_Name (E) & ": " & Ada.Exceptions.Exception_Message (E)); end Openid;
----------------------------------------------------------------------- -- openid -- Example of OpenID 2.0 Authentication -- Copyright (C) 2011, 2012 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Text_IO; with Ada.Exceptions; with Ada.IO_Exceptions; with ASF.Server.Web; with ASF.Applications; with ASF.Applications.Main; with ASF.Servlets.Faces; with ASF.Servlets.Files; with ASF.Servlets.Measures; with ASF.Filters.Dump; with Util.Beans.Objects; with Util.Log.Loggers; with Users; with AWS.Net.SSL; with Security.Openid; with Security.Openid.Servlets; procedure Openid is use ASF.Applications; Log : Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("Openid"); CONTEXT_PATH : constant String := "/openid"; CONFIG_PATH : constant String := "samples.properties"; App : aliased ASF.Applications.Main.Application; Factory : ASF.Applications.Main.Application_Factory; C : ASF.Applications.Config; -- Application servlets. Faces : aliased ASF.Servlets.Faces.Faces_Servlet; Files : aliased ASF.Servlets.Files.File_Servlet; Perf : aliased ASF.Servlets.Measures.Measure_Servlet; Auth : aliased Security.Openid.Servlets.Request_Auth_Servlet; Verify_Auth : aliased Security.Openid.Servlets.Verify_Auth_Servlet; -- Debug filters. Dump : aliased ASF.Filters.Dump.Dump_Filter; -- Web application server WS : ASF.Server.Web.AWS_Container; begin if not AWS.Net.SSL.Is_Supported then Log.Error ("SSL is not supported by AWS."); Log.Error ("SSL is required for the OpenID connector to connect to OpenID providers."); Log.Error ("Please, rebuild AWS with SSL support."); return; end if; begin C.Load_Properties (CONFIG_PATH); exception when Ada.IO_Exceptions.Name_Error => Log.Error ("Cannot read application configuration file {0}", CONFIG_PATH); end; App.Initialize (C, Factory); App.Register ("samplesMsg", "samples"); App.Set_Global ("contextPath", "/openid"); -- Declare a global bean to identify this sample from within the XHTML files. App.Set_Global ("sampleName", "openid"); App.Set_Global ("version", "0.1"); App.Set_Global ("user", Util.Beans.Objects.To_Object (Users.User'Access, Util.Beans.Objects.STATIC)); -- Register the servlets and filters App.Add_Servlet (Name => "faces", Server => Faces'Unchecked_Access); App.Add_Servlet (Name => "files", Server => Files'Unchecked_Access); App.Add_Servlet (Name => "auth", Server => Auth'Unchecked_Access); App.Add_Servlet (Name => "verify-auth", Server => Verify_Auth'Unchecked_Access); App.Add_Servlet (Name => "perf", Server => Perf'Unchecked_Access); -- Register the filters App.Add_Filter (Name => "perf", Filter => Perf'Unchecked_Access); App.Add_Filter (Name => "dump", Filter => Dump'Unchecked_Access); -- Define servlet mappings App.Add_Mapping (Name => "faces", Pattern => "*.html"); App.Add_Mapping (Name => "files", Pattern => "*.css"); App.Add_Mapping (Name => "files", Pattern => "*.js"); App.Add_Mapping (Name => "files", Pattern => "*.png"); App.Add_Mapping (Name => "files", Pattern => "*.jpg"); App.Add_Mapping (Name => "verify-auth", Pattern => "/auth/verify"); App.Add_Mapping (Name => "auth", Pattern => "/auth/auth/*"); App.Add_Mapping (Name => "perf", Pattern => "/statistics.xml"); -- Install the debug filter. App.Add_Filter_Mapping (Name => "perf", Pattern => "*.html"); App.Add_Filter_Mapping (Name => "dump", Pattern => "*.html"); App.Add_Filter_Mapping (Name => "perf", Pattern => "*.css"); App.Add_Filter_Mapping (Name => "dump", Pattern => "*.css"); App.Add_Filter_Mapping (Name => "perf", Pattern => "*.png"); App.Add_Filter_Mapping (Name => "dump", Pattern => "*.png"); App.Add_Filter_Mapping (Name => "perf", Pattern => "*.jpg"); App.Add_Filter_Mapping (Name => "dump", Pattern => "*.jpg"); App.Add_Filter_Mapping (Name => "perf", Pattern => "/auth/verify"); App.Add_Filter_Mapping (Name => "dump", Pattern => "/auth/verify"); App.Add_Filter_Mapping (Name => "perf", Pattern => "/auth/auth/*"); App.Add_Filter_Mapping (Name => "dump", Pattern => "/auth/auth/*"); WS.Register_Application (CONTEXT_PATH, App'Unchecked_Access); Log.Info ("Connect you browser to: http://localhost:8080/openid/auth/login.html"); WS.Start; delay 600.0; App.Close; exception when E : others => Ada.Text_IO.Put_Line ("Exception in server: " & Ada.Exceptions.Exception_Name (E) & ": " & Ada.Exceptions.Exception_Message (E)); end Openid;
Use the user bean defined in the Users package
Use the user bean defined in the Users package
Ada
apache-2.0
Letractively/ada-asf,Letractively/ada-asf,Letractively/ada-asf