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
1fd1675f13adfdd1fdfd853bf55aedc37e10fe8d
src/gen-model-packages.ads
src/gen-model-packages.ads
----------------------------------------------------------------------- -- gen-model-packages -- Packages holding model, query representation -- Copyright (C) 2009, 2010, 2011, 2012, 2013, 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.Containers.Hashed_Maps; with Ada.Strings.Unbounded; with Ada.Strings.Unbounded.Hash; with Util.Beans.Objects; with Util.Beans.Objects.Vectors; with Util.Strings.Sets; with Gen.Model.List; with Gen.Model.Mappings; limited with Gen.Model.Enums; limited with Gen.Model.Tables; limited with Gen.Model.Queries; limited with Gen.Model.Beans; package Gen.Model.Packages is use Ada.Strings.Unbounded; -- ------------------------------ -- Model Definition -- ------------------------------ -- The <b>Model_Definition</b> contains the complete model from one or -- several files. It maintains a list of Ada packages that must be generated. type Model_Definition is new Definition with private; type Model_Definition_Access is access all Model_Definition'Class; -- Validate the definition by checking and reporting problems to the logger interface. overriding procedure Validate (Def : in out Model_Definition; Log : in out Util.Log.Logging'Class); -- ------------------------------ -- Package Definition -- ------------------------------ -- The <b>Package_Definition</b> holds the tables, queries and other information -- that must be generated for a given Ada package. type Package_Definition is new Definition with private; type Package_Definition_Access is access all Package_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 : in Package_Definition; Name : in String) return Util.Beans.Objects.Object; -- Prepare the generation of the package: -- o identify the column types which are used -- o build a list of package for the with clauses. overriding procedure Prepare (O : in out Package_Definition); -- Validate the definition by checking and reporting problems to the logger interface. overriding procedure Validate (Def : in out Package_Definition; Log : in out Util.Log.Logging'Class); -- Initialize the package instance overriding procedure Initialize (O : in out Package_Definition); -- Find the type identified by the name. function Find_Type (From : in Package_Definition; Name : in Unbounded_String) return Gen.Model.Mappings.Mapping_Definition_Access; -- Get the model which contains all the package definitions. function Get_Model (From : in Package_Definition) return Model_Definition_Access; -- Returns True if the package is a pre-defined package and must not be generated. function Is_Predefined (From : in Package_Definition) return Boolean; -- Set the package as a pre-defined package. procedure Set_Predefined (From : in out Package_Definition); -- 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 : Model_Definition; Name : String) return Util.Beans.Objects.Object; -- Initialize the model definition instance. overriding procedure Initialize (O : in out Model_Definition); -- Returns True if the model contains at least one package. function Has_Packages (O : in Model_Definition) return Boolean; -- Register or find the package knowing its name procedure Register_Package (O : in out Model_Definition; Name : in Unbounded_String; Result : out Package_Definition_Access); -- Register the declaration of the given enum in the model. procedure Register_Enum (O : in out Model_Definition; Enum : access Gen.Model.Enums.Enum_Definition'Class); -- Register the declaration of the given table in the model. procedure Register_Table (O : in out Model_Definition; Table : access Gen.Model.Tables.Table_Definition'Class); -- Register the declaration of the given query in the model. procedure Register_Query (O : in out Model_Definition; Table : access Gen.Model.Queries.Query_File_Definition'Class); -- Register the declaration of the given bean in the model. procedure Register_Bean (O : in out Model_Definition; Bean : access Gen.Model.Beans.Bean_Definition'Class); -- Register a type mapping. The <b>From</b> type describes a type in the XML -- configuration files (hibernate, query, ...) and the <b>To</b> represents the -- corresponding Ada type. procedure Register_Type (O : in out Model_Definition; From : in String; To : in String); -- Find the type identified by the name. function Find_Type (From : in Model_Definition; Name : in Unbounded_String) return Gen.Model.Mappings.Mapping_Definition_Access; -- Set the directory name associated with the model. This directory name allows to -- save and build a model in separate directories for the application, the unit tests -- and others. procedure Set_Dirname (O : in out Model_Definition; Target_Dir : in String; Model_Dir : in String); -- Get the directory name associated with the model. function Get_Dirname (O : in Model_Definition) return String; -- Get the directory name which contains the model. function Get_Model_Directory (O : in Model_Definition) return String; -- Enable the generation of the Ada package given by the name. By default all the Ada -- packages found in the model are generated. When called, this enables the generation -- only for the Ada packages registered here. procedure Enable_Package_Generation (Model : in out Model_Definition; Name : in String); -- Returns True if the generation is enabled for the given package name. function Is_Generation_Enabled (Model : in Model_Definition; Name : in String) return Boolean; -- Iterate over the model tables. procedure Iterate_Tables (Model : in Model_Definition; Process : not null access procedure (Item : in out Tables.Table_Definition)); -- Prepare the generation of the package: -- o identify the column types which are used -- o build a list of package for the with clauses. overriding procedure Prepare (O : in out Model_Definition); package Package_Map is new Ada.Containers.Hashed_Maps (Key_Type => Unbounded_String, Element_Type => Package_Definition_Access, Hash => Ada.Strings.Unbounded.Hash, Equivalent_Keys => "="); subtype Package_Cursor is Package_Map.Cursor; -- Get the first package of the model definition. function First (From : Model_Definition) return Package_Cursor; -- Returns true if the package cursor contains a valid package function Has_Element (Position : Package_Cursor) return Boolean renames Package_Map.Has_Element; -- Returns the package definition. function Element (Position : Package_Cursor) return Package_Definition_Access renames Package_Map.Element; -- Move the iterator to the next package definition. procedure Next (Position : in out Package_Cursor) renames Package_Map.Next; private package Table_List is new Gen.Model.List (T => Definition, T_Access => Definition_Access); -- Returns False if the <tt>Left</tt> table does not depend on <tt>Right</tt>. -- Returns True if the <tt>Left</tt> table depends on the <tt>Right</tt> table. function Dependency_Compare (Left, Right : in Definition_Access) return Boolean; -- Sort the tables on their dependency. procedure Dependency_Sort is new Table_List.Sort_On ("<" => Dependency_Compare); subtype Table_List_Definition is Table_List.List_Definition; subtype Enum_List_Definition is Table_List.List_Definition; type List_Object is new Util.Beans.Basic.List_Bean with record Values : Util.Beans.Objects.Vectors.Vector; Row : Natural; Value_Bean : Util.Beans.Objects.Object; end record; -- Get the number of elements in the list. overriding function Get_Count (From : in List_Object) return Natural; -- Set the current row index. Valid row indexes start at 1. overriding procedure Set_Row_Index (From : in out List_Object; Index : in Natural); -- Get the element at the current row index. overriding function Get_Row (From : in List_Object) return Util.Beans.Objects.Object; -- 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 List_Object; Name : in String) return Util.Beans.Objects.Object; type Package_Definition is new Definition with record -- Enums defined in the package. Enums : aliased Enum_List_Definition; Enums_Bean : Util.Beans.Objects.Object; -- Hibernate tables Tables : aliased Table_List_Definition; Tables_Bean : Util.Beans.Objects.Object; -- Custom queries Queries : aliased Table_List_Definition; Queries_Bean : Util.Beans.Objects.Object; -- Ada Beans Beans : aliased Table_List_Definition; Beans_Bean : Util.Beans.Objects.Object; -- A list of external packages which are used (used for with clause generation). Used_Spec_Types : aliased List_Object; Used_Spec : Util.Beans.Objects.Object; -- A list of external packages which are used (used for with clause generation). Used_Body_Types : aliased List_Object; Used_Body : Util.Beans.Objects.Object; -- A map of all types defined in this package. Types : Gen.Model.Mappings.Mapping_Maps.Map; -- The base name for the package (ex: gen-model-users) Base_Name : Unbounded_String; -- The global model (used to resolve types from other packages). Model : Model_Definition_Access; -- True if the package uses Ada.Calendar.Time Uses_Calendar_Time : Boolean := False; -- True if the package is a pre-defined package (ie, defined by a UML profile). Is_Predefined : Boolean := False; end record; type Model_Definition is new Definition with record -- List of all enums. Enums : aliased Enum_List_Definition; Enums_Bean : Util.Beans.Objects.Object; -- List of all tables. Tables : aliased Table_List_Definition; Tables_Bean : Util.Beans.Objects.Object; -- List of all queries. Queries : aliased Table_List_Definition; Queries_Bean : Util.Beans.Objects.Object; -- Ada Beans Beans : aliased Table_List_Definition; Beans_Bean : Util.Beans.Objects.Object; -- Map of all packages. Packages : Package_Map.Map; -- Directory associated with the model ('src', 'samples', 'regtests', ...). Dir_Name : Unbounded_String; -- Directory that contains the SQL and model files. DB_Name : Unbounded_String; -- When not empty, a list of packages that must be taken into account for the generation. -- By default all packages and tables defined in the model are generated. Gen_Packages : Util.Strings.Sets.Set; end record; end Gen.Model.Packages;
----------------------------------------------------------------------- -- gen-model-packages -- Packages holding model, query representation -- Copyright (C) 2009, 2010, 2011, 2012, 2013, 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.Containers.Hashed_Maps; with Ada.Strings.Unbounded; with Ada.Strings.Unbounded.Hash; with Util.Beans.Objects; with Util.Beans.Objects.Vectors; with Util.Strings.Sets; with Gen.Model.List; with Gen.Model.Mappings; limited with Gen.Model.Enums; limited with Gen.Model.Tables; limited with Gen.Model.Queries; limited with Gen.Model.Beans; package Gen.Model.Packages is use Ada.Strings.Unbounded; -- ------------------------------ -- Model Definition -- ------------------------------ -- The <b>Model_Definition</b> contains the complete model from one or -- several files. It maintains a list of Ada packages that must be generated. type Model_Definition is new Definition with private; type Model_Definition_Access is access all Model_Definition'Class; -- Validate the definition by checking and reporting problems to the logger interface. overriding procedure Validate (Def : in out Model_Definition; Log : in out Util.Log.Logging'Class); -- ------------------------------ -- Package Definition -- ------------------------------ -- The <b>Package_Definition</b> holds the tables, queries and other information -- that must be generated for a given Ada package. type Package_Definition is new Definition with private; type Package_Definition_Access is access all Package_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 : in Package_Definition; Name : in String) return Util.Beans.Objects.Object; -- Prepare the generation of the package: -- o identify the column types which are used -- o build a list of package for the with clauses. overriding procedure Prepare (O : in out Package_Definition); -- Validate the definition by checking and reporting problems to the logger interface. overriding procedure Validate (Def : in out Package_Definition; Log : in out Util.Log.Logging'Class); -- Initialize the package instance overriding procedure Initialize (O : in out Package_Definition); -- Find the type identified by the name. function Find_Type (From : in Package_Definition; Name : in Unbounded_String) return Gen.Model.Mappings.Mapping_Definition_Access; -- Get the model which contains all the package definitions. function Get_Model (From : in Package_Definition) return Model_Definition_Access; -- Returns True if the package is a pre-defined package and must not be generated. function Is_Predefined (From : in Package_Definition) return Boolean; -- Set the package as a pre-defined package. procedure Set_Predefined (From : in out Package_Definition); -- 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 : Model_Definition; Name : String) return Util.Beans.Objects.Object; -- Initialize the model definition instance. overriding procedure Initialize (O : in out Model_Definition); -- Returns True if the model contains at least one package. function Has_Packages (O : in Model_Definition) return Boolean; -- Register or find the package knowing its name procedure Register_Package (O : in out Model_Definition; Name : in Unbounded_String; Result : out Package_Definition_Access); -- Register the declaration of the given enum in the model. procedure Register_Enum (O : in out Model_Definition; Enum : access Gen.Model.Enums.Enum_Definition'Class); -- Register the declaration of the given table in the model. procedure Register_Table (O : in out Model_Definition; Table : access Gen.Model.Tables.Table_Definition'Class); -- Register the declaration of the given query in the model. procedure Register_Query (O : in out Model_Definition; Table : access Gen.Model.Queries.Query_File_Definition'Class); -- Register the declaration of the given bean in the model. procedure Register_Bean (O : in out Model_Definition; Bean : access Gen.Model.Beans.Bean_Definition'Class); -- Register a type mapping. The <b>From</b> type describes a type in the XML -- configuration files (hibernate, query, ...) and the <b>To</b> represents the -- corresponding Ada type. procedure Register_Type (O : in out Model_Definition; From : in String; To : in String); -- Find the type identified by the name. function Find_Type (From : in Model_Definition; Name : in Unbounded_String) return Gen.Model.Mappings.Mapping_Definition_Access; -- Set the directory name associated with the model. This directory name allows to -- save and build a model in separate directories for the application, the unit tests -- and others. procedure Set_Dirname (O : in out Model_Definition; Target_Dir : in String; Model_Dir : in String); -- Get the directory name associated with the model. function Get_Dirname (O : in Model_Definition) return String; -- Get the directory name which contains the model. function Get_Model_Directory (O : in Model_Definition) return String; -- Enable the generation of the Ada package given by the name. By default all the Ada -- packages found in the model are generated. When called, this enables the generation -- only for the Ada packages registered here. procedure Enable_Package_Generation (Model : in out Model_Definition; Name : in String); -- Returns True if the generation is enabled for the given package name. function Is_Generation_Enabled (Model : in Model_Definition; Name : in String) return Boolean; -- Iterate over the model tables. procedure Iterate_Tables (Model : in Model_Definition; Process : not null access procedure (Item : in out Tables.Table_Definition)); -- Iterate over the model enums. procedure Iterate_Enums (Model : in Model_Definition; Process : not null access procedure (Item : in out Enums.Enum_Definition)); -- Prepare the generation of the package: -- o identify the column types which are used -- o build a list of package for the with clauses. overriding procedure Prepare (O : in out Model_Definition); package Package_Map is new Ada.Containers.Hashed_Maps (Key_Type => Unbounded_String, Element_Type => Package_Definition_Access, Hash => Ada.Strings.Unbounded.Hash, Equivalent_Keys => "="); subtype Package_Cursor is Package_Map.Cursor; -- Get the first package of the model definition. function First (From : Model_Definition) return Package_Cursor; -- Returns true if the package cursor contains a valid package function Has_Element (Position : Package_Cursor) return Boolean renames Package_Map.Has_Element; -- Returns the package definition. function Element (Position : Package_Cursor) return Package_Definition_Access renames Package_Map.Element; -- Move the iterator to the next package definition. procedure Next (Position : in out Package_Cursor) renames Package_Map.Next; private package Table_List is new Gen.Model.List (T => Definition, T_Access => Definition_Access); -- Returns False if the <tt>Left</tt> table does not depend on <tt>Right</tt>. -- Returns True if the <tt>Left</tt> table depends on the <tt>Right</tt> table. function Dependency_Compare (Left, Right : in Definition_Access) return Boolean; -- Sort the tables on their dependency. procedure Dependency_Sort is new Table_List.Sort_On ("<" => Dependency_Compare); subtype Table_List_Definition is Table_List.List_Definition; subtype Enum_List_Definition is Table_List.List_Definition; type List_Object is new Util.Beans.Basic.List_Bean with record Values : Util.Beans.Objects.Vectors.Vector; Row : Natural; Value_Bean : Util.Beans.Objects.Object; end record; -- Get the number of elements in the list. overriding function Get_Count (From : in List_Object) return Natural; -- Set the current row index. Valid row indexes start at 1. overriding procedure Set_Row_Index (From : in out List_Object; Index : in Natural); -- Get the element at the current row index. overriding function Get_Row (From : in List_Object) return Util.Beans.Objects.Object; -- 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 List_Object; Name : in String) return Util.Beans.Objects.Object; type Package_Definition is new Definition with record -- Enums defined in the package. Enums : aliased Enum_List_Definition; Enums_Bean : Util.Beans.Objects.Object; -- Hibernate tables Tables : aliased Table_List_Definition; Tables_Bean : Util.Beans.Objects.Object; -- Custom queries Queries : aliased Table_List_Definition; Queries_Bean : Util.Beans.Objects.Object; -- Ada Beans Beans : aliased Table_List_Definition; Beans_Bean : Util.Beans.Objects.Object; -- A list of external packages which are used (used for with clause generation). Used_Spec_Types : aliased List_Object; Used_Spec : Util.Beans.Objects.Object; -- A list of external packages which are used (used for with clause generation). Used_Body_Types : aliased List_Object; Used_Body : Util.Beans.Objects.Object; -- A map of all types defined in this package. Types : Gen.Model.Mappings.Mapping_Maps.Map; -- The base name for the package (ex: gen-model-users) Base_Name : Unbounded_String; -- The global model (used to resolve types from other packages). Model : Model_Definition_Access; -- True if the package uses Ada.Calendar.Time Uses_Calendar_Time : Boolean := False; -- True if the package is a pre-defined package (ie, defined by a UML profile). Is_Predefined : Boolean := False; end record; type Model_Definition is new Definition with record -- List of all enums. Enums : aliased Enum_List_Definition; Enums_Bean : Util.Beans.Objects.Object; -- List of all tables. Tables : aliased Table_List_Definition; Tables_Bean : Util.Beans.Objects.Object; -- List of all queries. Queries : aliased Table_List_Definition; Queries_Bean : Util.Beans.Objects.Object; -- Ada Beans Beans : aliased Table_List_Definition; Beans_Bean : Util.Beans.Objects.Object; -- Map of all packages. Packages : Package_Map.Map; -- Directory associated with the model ('src', 'samples', 'regtests', ...). Dir_Name : Unbounded_String; -- Directory that contains the SQL and model files. DB_Name : Unbounded_String; -- When not empty, a list of packages that must be taken into account for the generation. -- By default all packages and tables defined in the model are generated. Gen_Packages : Util.Strings.Sets.Set; end record; end Gen.Model.Packages;
Declare the Iterate_Enums procedure on the model
Declare the Iterate_Enums procedure on the model
Ada
apache-2.0
stcarrez/dynamo,stcarrez/dynamo,stcarrez/dynamo
092665cb30b6715d2aa0a230d13ae23862fe075e
awa/src/awa-services-contexts.adb
awa/src/awa-services-contexts.adb
----------------------------------------------------------------------- -- awa-services -- Services -- 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.Task_Attributes; with ADO.Databases; package body AWA.Services.Contexts is use type ADO.Databases.Connection_Status; use type AWA.Users.Principals.Principal_Access; package Task_Context is new Ada.Task_Attributes (Service_Context_Access, null); -- ------------------------------ -- Get the application associated with the current service operation. -- ------------------------------ function Get_Application (Ctx : in Service_Context) return AWA.Applications.Application_Access is begin return Ctx.Application; end Get_Application; -- ------------------------------ -- Get the current database connection for reading. -- ------------------------------ function Get_Session (Ctx : in Service_Context_Access) return ADO.Sessions.Session is begin if Ctx.Slave.Get_Status /= ADO.Databases.OPEN then Ctx.Slave := Ctx.Application.Get_Session; end if; return Ctx.Slave; end Get_Session; -- ------------------------------ -- Get the current database connection for reading and writing. -- ------------------------------ function Get_Master_Session (Ctx : in Service_Context_Access) return ADO.Sessions.Master_Session is begin if Ctx.Master.Get_Status /= ADO.Databases.OPEN then Ctx.Master := Ctx.Application.Get_Master_Session; -- Ctx.Slave := Ctx.Master; end if; return Ctx.Master; end Get_Master_Session; -- ------------------------------ -- Get the current user invoking the service operation. -- Returns a null user if there is none. -- ------------------------------ function Get_User (Ctx : in Service_Context) return AWA.Users.Models.User_Ref is begin if Ctx.Principal = null then return AWA.Users.Models.Null_User; else return Ctx.Principal.Get_User; end if; end Get_User; -- ------------------------------ -- Get the current user identifier invoking the service operation. -- Returns NO_IDENTIFIER if there is none. -- ------------------------------ function Get_User_Identifier (Ctx : in Service_Context) return ADO.Identifier is begin if Ctx.Principal = null then return ADO.NO_IDENTIFIER; else return Ctx.Principal.Get_User_Identifier; end if; end Get_User_Identifier; -- ------------------------------ -- Get the current user session from the user invoking the service operation. -- Returns a null session if there is none. -- ------------------------------ function Get_User_Session (Ctx : in Service_Context) return AWA.Users.Models.Session_Ref is begin if Ctx.Principal = null then return AWA.Users.Models.Null_Session; else return Ctx.Principal.Get_Session; end if; end Get_User_Session; -- ------------------------------ -- Starts a transaction. -- ------------------------------ procedure Start (Ctx : in out Service_Context) is begin if Ctx.Transaction = 0 and then not Ctx.Active_Transaction then Ctx.Master.Begin_Transaction; Ctx.Active_Transaction := True; end if; Ctx.Transaction := Ctx.Transaction + 1; end Start; -- ------------------------------ -- Commits the current transaction. The database transaction is really committed by the -- last <b>Commit</b> called. -- ------------------------------ procedure Commit (Ctx : in out Service_Context) is begin Ctx.Transaction := Ctx.Transaction - 1; if Ctx.Transaction = 0 and then Ctx.Active_Transaction then Ctx.Master.Commit; Ctx.Active_Transaction := False; end if; end Commit; -- ------------------------------ -- Rollback the current transaction. The database transaction is rollback at the first -- call to <b>Rollback</b>. -- ------------------------------ procedure Rollback (Ctx : in out Service_Context) is begin null; end Rollback; -- ------------------------------ -- Set the current application and user context. -- ------------------------------ procedure Set_Context (Ctx : in out Service_Context; Application : in AWA.Applications.Application_Access; Principal : in AWA.Users.Principals.Principal_Access) is begin Ctx.Application := Application; Ctx.Principal := Principal; end Set_Context; -- ------------------------------ -- Initializes the service context. -- ------------------------------ overriding procedure Initialize (Ctx : in out Service_Context) is use type AWA.Applications.Application_Access; begin Ctx.Previous := Task_Context.Value; Task_Context.Set_Value (Ctx'Unchecked_Access); if Ctx.Previous /= null and then Ctx.Application = null then Ctx.Application := Ctx.Previous.Application; end if; end Initialize; -- ------------------------------ -- Finalize the service context, rollback non-committed transaction, releases any object. -- ------------------------------ overriding procedure Finalize (Ctx : in out Service_Context) is begin -- When the service context is released, we must not have any active transaction. -- This means we are leaving the service in an abnormal way such as when an -- exception is raised. If this is the case, rollback the transaction. if Ctx.Active_Transaction then Ctx.Master.Rollback; end if; Task_Context.Set_Value (Ctx.Previous); end Finalize; -- ------------------------------ -- Get the current service context. -- Returns null if the current thread is not associated with any service context. -- ------------------------------ function Current return Service_Context_Access is begin return Task_Context.Value; end Current; end AWA.Services.Contexts;
----------------------------------------------------------------------- -- awa-services -- Services -- 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_Attributes; with ADO.Databases; package body AWA.Services.Contexts is use type ADO.Databases.Connection_Status; use type AWA.Users.Principals.Principal_Access; package Task_Context is new Ada.Task_Attributes (Service_Context_Access, null); -- ------------------------------ -- Get the application associated with the current service operation. -- ------------------------------ function Get_Application (Ctx : in Service_Context) return AWA.Applications.Application_Access is begin return Ctx.Application; end Get_Application; -- ------------------------------ -- Get the current database connection for reading. -- ------------------------------ function Get_Session (Ctx : in Service_Context_Access) return ADO.Sessions.Session is begin -- If a master database session was created, use it. if Ctx.Master.Get_Status = ADO.Databases.OPEN then return ADO.Sessions.Session (Ctx.Master); elsif Ctx.Slave.Get_Status /= ADO.Databases.OPEN then Ctx.Slave := Ctx.Application.Get_Session; end if; return Ctx.Slave; end Get_Session; -- ------------------------------ -- Get the current database connection for reading and writing. -- ------------------------------ function Get_Master_Session (Ctx : in Service_Context_Access) return ADO.Sessions.Master_Session is begin if Ctx.Master.Get_Status /= ADO.Databases.OPEN then Ctx.Master := Ctx.Application.Get_Master_Session; end if; return Ctx.Master; end Get_Master_Session; -- ------------------------------ -- Get the current user invoking the service operation. -- Returns a null user if there is none. -- ------------------------------ function Get_User (Ctx : in Service_Context) return AWA.Users.Models.User_Ref is begin if Ctx.Principal = null then return AWA.Users.Models.Null_User; else return Ctx.Principal.Get_User; end if; end Get_User; -- ------------------------------ -- Get the current user identifier invoking the service operation. -- Returns NO_IDENTIFIER if there is none. -- ------------------------------ function Get_User_Identifier (Ctx : in Service_Context) return ADO.Identifier is begin if Ctx.Principal = null then return ADO.NO_IDENTIFIER; else return Ctx.Principal.Get_User_Identifier; end if; end Get_User_Identifier; -- ------------------------------ -- Get the current user session from the user invoking the service operation. -- Returns a null session if there is none. -- ------------------------------ function Get_User_Session (Ctx : in Service_Context) return AWA.Users.Models.Session_Ref is begin if Ctx.Principal = null then return AWA.Users.Models.Null_Session; else return Ctx.Principal.Get_Session; end if; end Get_User_Session; -- ------------------------------ -- Starts a transaction. -- ------------------------------ procedure Start (Ctx : in out Service_Context) is begin if Ctx.Transaction = 0 and then not Ctx.Active_Transaction then Ctx.Master.Begin_Transaction; Ctx.Active_Transaction := True; end if; Ctx.Transaction := Ctx.Transaction + 1; end Start; -- ------------------------------ -- Commits the current transaction. The database transaction is really committed by the -- last <b>Commit</b> called. -- ------------------------------ procedure Commit (Ctx : in out Service_Context) is begin Ctx.Transaction := Ctx.Transaction - 1; if Ctx.Transaction = 0 and then Ctx.Active_Transaction then Ctx.Master.Commit; Ctx.Active_Transaction := False; end if; end Commit; -- ------------------------------ -- Rollback the current transaction. The database transaction is rollback at the first -- call to <b>Rollback</b>. -- ------------------------------ procedure Rollback (Ctx : in out Service_Context) is begin null; end Rollback; -- ------------------------------ -- Set the current application and user context. -- ------------------------------ procedure Set_Context (Ctx : in out Service_Context; Application : in AWA.Applications.Application_Access; Principal : in AWA.Users.Principals.Principal_Access) is begin Ctx.Application := Application; Ctx.Principal := Principal; end Set_Context; -- ------------------------------ -- Initializes the service context. -- ------------------------------ overriding procedure Initialize (Ctx : in out Service_Context) is use type AWA.Applications.Application_Access; begin Ctx.Previous := Task_Context.Value; Task_Context.Set_Value (Ctx'Unchecked_Access); if Ctx.Previous /= null and then Ctx.Application = null then Ctx.Application := Ctx.Previous.Application; end if; end Initialize; -- ------------------------------ -- Finalize the service context, rollback non-committed transaction, releases any object. -- ------------------------------ overriding procedure Finalize (Ctx : in out Service_Context) is begin -- When the service context is released, we must not have any active transaction. -- This means we are leaving the service in an abnormal way such as when an -- exception is raised. If this is the case, rollback the transaction. if Ctx.Active_Transaction then Ctx.Master.Rollback; end if; Task_Context.Set_Value (Ctx.Previous); end Finalize; -- ------------------------------ -- Get the current service context. -- Returns null if the current thread is not associated with any service context. -- ------------------------------ function Current return Service_Context_Access is begin return Task_Context.Value; end Current; end AWA.Services.Contexts;
Fix Get_Session to return the master session if such session was created.
Fix Get_Session to return the master session if such session was created.
Ada
apache-2.0
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
2a384bdcf60cedbbc56b8b3027e75f94d0591bf6
src/sys/encoders/util-encoders.ads
src/sys/encoders/util-encoders.ads
----------------------------------------------------------------------- -- util-encoders -- Encode/Decode streams and strings from one format to another -- 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 Ada.Streams; with Ada.Finalization; with Interfaces; -- === Encoder and Decoders === -- The <b>Util.Encoders</b> package defines the <b>Encoder</b> and <b>Decode</b> objects -- which provide a mechanism to transform a stream from one format into -- another format. -- -- ==== Simple encoding and decoding ==== -- package Util.Encoders is pragma Preelaborate; Not_Supported : exception; Encoding_Error : exception; -- Encoder/decoder for Base64 (RFC 4648) BASE_64 : constant String := "base64"; -- Encoder/decoder for Base64 (RFC 4648) using the URL alphabet -- (+ and / are replaced by - and _) BASE_64_URL : constant String := "base64url"; -- Encoder/decoder for Base16 (RFC 4648) BASE_16 : constant String := "base16"; HEX : constant String := "hex"; -- Encoder for SHA1 (RFC 3174) HASH_SHA1 : constant String := "sha1"; -- ------------------------------ -- Encoder context object -- ------------------------------ -- The <b>Encoder</b> provides operations to encode and decode -- strings or stream of data from one format to another. -- The <b>Encoded</b> contains two <b>Transformer</b> -- which either <i>encodes</i> or <i>decodes</i> the stream. type Encoder is tagged limited private; -- Encodes the input string <b>Data</b> using the transformation -- rules provided by the <b>E</b> encoder. -- -- Returns the encoded string. -- -- Raises the <b>Encoding_Error</b> exception if the source string -- cannot be encoded. -- Raises the <b>Not_Supported</b> exception if the encoding is not -- supported. function Encode (E : in Encoder; Data : in String) return String; function Encode_Binary (E : in Encoder; Data : in Ada.Streams.Stream_Element_Array) return String; -- Create the encoder object for the specified encoding format. function Create (Name : in String) return Encoder; type Decoder is tagged limited private; -- Decodes the input string <b>Data</b> using the transformation -- rules provided by the <b>E</b> encoder. -- -- Returns the encoded string. -- -- Raises the <b>Encoding_Error</b> exception if the source string -- cannot be decoded. -- Raises the <b>Not_Supported</b> exception if the decoding is not -- supported. function Decode (E : in Decoder; Data : in String) return String; function Decode_Binary (E : in Decoder; Data : in String) return Ada.Streams.Stream_Element_Array; -- Create the decoder object for the specified encoding format. function Create (Name : in String) return Decoder; -- ------------------------------ -- Stream Transformation interface -- ------------------------------ -- The <b>Transformer</b> interface defines the operation to transform -- a stream from one data format to another. type Transformer is limited interface; type Transformer_Access is access all Transformer'Class; -- Transform the input array represented by <b>Data</b> into -- the output array <b>Into</b>. The transformation made by -- the object can be of any nature (Hex encoding, Base64 encoding, -- Hex decoding, Base64 decoding, encryption, compression, ...). -- -- If the transformer does not have enough room to write the result, -- it must return in <b>Encoded</b> the index of the last encoded -- position in the <b>Data</b> array. -- -- The transformer returns in <b>Last</b> the last valid position -- in the output array <b>Into</b>. -- -- The <b>Encoding_Error</b> exception is raised if the input -- array cannot be transformed. procedure Transform (E : in out Transformer; Data : in Ada.Streams.Stream_Element_Array; Into : out Ada.Streams.Stream_Element_Array; Last : out Ada.Streams.Stream_Element_Offset; Encoded : out Ada.Streams.Stream_Element_Offset) is abstract; -- Finish encoding the input array. procedure Finish (E : in out Transformer; Into : in out Ada.Streams.Stream_Element_Array; Last : in out Ada.Streams.Stream_Element_Offset) is null; -- Transform the input string <b>Data</b> using the transformation -- rules provided by the <b>E</b> transformer. -- -- Returns the transformed string. -- -- Raises the <b>Encoding_Error</b> exception if the source string -- cannot be transformed function Transform (E : in out Transformer'Class; Data : in String) return String; -- Transform the input string <b>Data</b> using the transformation -- rules provided by the <b>E</b> transformer. -- -- Returns the transformed string. -- -- Raises the <b>Encoding_Error</b> exception if the source string -- cannot be transformed function Transform (E : in out Transformer'Class; Data : in Ada.Streams.Stream_Element_Array) return String; function Transform (E : in out Transformer'Class; Data : in Ada.Streams.Stream_Element_Array) return Ada.Streams.Stream_Element_Array; -- Transform the input string <b>Data</b> using the transformation -- rules provided by the <b>E</b> transformer and return the data in -- the <b>Into</b> array, setting <b>Last</b> to the last index. -- -- Raises the <b>Encoding_Error</b> exception if the source string -- cannot be transformed procedure Transform (E : in out Transformer'Class; Data : in String; Into : out Ada.Streams.Stream_Element_Array; Last : out Ada.Streams.Stream_Element_Offset); -- Encode the value represented by <tt>Val</tt> in the stream array <tt>Into</tt> starting -- at position <tt>Pos</tt> in that array. The value is encoded using LEB128 format, 7-bits -- at a time until all non zero bits are written. The <tt>Last</tt> parameter is updated -- to indicate the position of the last valid byte written in <tt>Into</tt>. procedure Encode_LEB128 (Into : in out Ada.Streams.Stream_Element_Array; Pos : in Ada.Streams.Stream_Element_Offset; Val : in Interfaces.Unsigned_64; Last : out Ada.Streams.Stream_Element_Offset); -- Decode from the byte array <tt>From</tt> the value represented as LEB128 format starting -- at position <tt>Pos</tt> in that array. After decoding, the <tt>Last</tt> index is updated -- to indicate the last position in the byte array. procedure Decode_LEB128 (From : in Ada.Streams.Stream_Element_Array; Pos : in Ada.Streams.Stream_Element_Offset; Val : out Interfaces.Unsigned_64; Last : out Ada.Streams.Stream_Element_Offset); private -- Transform the input data into the target string. procedure Convert (E : in out Transformer'Class; Data : in Ada.Streams.Stream_Element_Array; Into : out String); type Encoder is new Ada.Finalization.Limited_Controlled with record Encode : Transformer_Access := null; end record; -- Delete the transformers overriding procedure Finalize (E : in out Encoder); type Decoder is new Ada.Finalization.Limited_Controlled with record Decode : Transformer_Access := null; end record; -- Delete the transformers overriding procedure Finalize (E : in out Decoder); end Util.Encoders;
----------------------------------------------------------------------- -- util-encoders -- Encode/Decode streams and strings from one format to another -- Copyright (C) 2009, 2010, 2011, 2012, 2016, 2017, 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.Streams; with Ada.Finalization; with Interfaces; -- === Encoder and Decoders === -- The <b>Util.Encoders</b> package defines the <b>Encoder</b> and <b>Decode</b> objects -- which provide a mechanism to transform a stream from one format into -- another format. -- -- ==== Simple encoding and decoding ==== -- package Util.Encoders is pragma Preelaborate; use Ada.Streams; Not_Supported : exception; Encoding_Error : exception; -- Encoder/decoder for Base64 (RFC 4648) BASE_64 : constant String := "base64"; -- Encoder/decoder for Base64 (RFC 4648) using the URL alphabet -- (+ and / are replaced by - and _) BASE_64_URL : constant String := "base64url"; -- Encoder/decoder for Base16 (RFC 4648) BASE_16 : constant String := "base16"; HEX : constant String := "hex"; -- Encoder for SHA1 (RFC 3174) HASH_SHA1 : constant String := "sha1"; -- ------------------------------ -- Secret key -- ------------------------------ -- A secret key of the given length, it cannot be copied and is safely erased. subtype Key_Length is Stream_Element_Offset range 1 .. Stream_Element_Offset'Last; type Secret_Key (Length : Key_Length) is limited private; -- Create the secret key from the password string. function Create (Password : in String) return Secret_Key with Pre => Password'Length > 0, Post => Create'Result.Length = Password'Length; procedure Create (Password : in String; Key : out Secret_Key) with Pre => Password'Length > 0, Post => Key.Length = Password'Length; -- ------------------------------ -- Encoder context object -- ------------------------------ -- The <b>Encoder</b> provides operations to encode and decode -- strings or stream of data from one format to another. -- The <b>Encoded</b> contains two <b>Transformer</b> -- which either <i>encodes</i> or <i>decodes</i> the stream. type Encoder is tagged limited private; -- Encodes the input string <b>Data</b> using the transformation -- rules provided by the <b>E</b> encoder. -- -- Returns the encoded string. -- -- Raises the <b>Encoding_Error</b> exception if the source string -- cannot be encoded. -- Raises the <b>Not_Supported</b> exception if the encoding is not -- supported. function Encode (E : in Encoder; Data : in String) return String; function Encode_Binary (E : in Encoder; Data : in Ada.Streams.Stream_Element_Array) return String; -- Create the encoder object for the specified encoding format. function Create (Name : in String) return Encoder; type Decoder is tagged limited private; -- Decodes the input string <b>Data</b> using the transformation -- rules provided by the <b>E</b> encoder. -- -- Returns the encoded string. -- -- Raises the <b>Encoding_Error</b> exception if the source string -- cannot be decoded. -- Raises the <b>Not_Supported</b> exception if the decoding is not -- supported. function Decode (E : in Decoder; Data : in String) return String; function Decode_Binary (E : in Decoder; Data : in String) return Ada.Streams.Stream_Element_Array; -- Create the decoder object for the specified encoding format. function Create (Name : in String) return Decoder; -- ------------------------------ -- Stream Transformation interface -- ------------------------------ -- The <b>Transformer</b> interface defines the operation to transform -- a stream from one data format to another. type Transformer is limited interface; type Transformer_Access is access all Transformer'Class; -- Transform the input array represented by <b>Data</b> into -- the output array <b>Into</b>. The transformation made by -- the object can be of any nature (Hex encoding, Base64 encoding, -- Hex decoding, Base64 decoding, encryption, compression, ...). -- -- If the transformer does not have enough room to write the result, -- it must return in <b>Encoded</b> the index of the last encoded -- position in the <b>Data</b> array. -- -- The transformer returns in <b>Last</b> the last valid position -- in the output array <b>Into</b>. -- -- The <b>Encoding_Error</b> exception is raised if the input -- array cannot be transformed. procedure Transform (E : in out Transformer; Data : in Ada.Streams.Stream_Element_Array; Into : out Ada.Streams.Stream_Element_Array; Last : out Ada.Streams.Stream_Element_Offset; Encoded : out Ada.Streams.Stream_Element_Offset) is abstract; -- Finish encoding the input array. procedure Finish (E : in out Transformer; Into : in out Ada.Streams.Stream_Element_Array; Last : in out Ada.Streams.Stream_Element_Offset) is null; -- Transform the input string <b>Data</b> using the transformation -- rules provided by the <b>E</b> transformer. -- -- Returns the transformed string. -- -- Raises the <b>Encoding_Error</b> exception if the source string -- cannot be transformed function Transform (E : in out Transformer'Class; Data : in String) return String; -- Transform the input string <b>Data</b> using the transformation -- rules provided by the <b>E</b> transformer. -- -- Returns the transformed string. -- -- Raises the <b>Encoding_Error</b> exception if the source string -- cannot be transformed function Transform (E : in out Transformer'Class; Data : in Ada.Streams.Stream_Element_Array) return String; function Transform (E : in out Transformer'Class; Data : in Ada.Streams.Stream_Element_Array) return Ada.Streams.Stream_Element_Array; -- Transform the input string <b>Data</b> using the transformation -- rules provided by the <b>E</b> transformer and return the data in -- the <b>Into</b> array, setting <b>Last</b> to the last index. -- -- Raises the <b>Encoding_Error</b> exception if the source string -- cannot be transformed procedure Transform (E : in out Transformer'Class; Data : in String; Into : out Ada.Streams.Stream_Element_Array; Last : out Ada.Streams.Stream_Element_Offset); -- Encode the value represented by <tt>Val</tt> in the stream array <tt>Into</tt> starting -- at position <tt>Pos</tt> in that array. The value is encoded using LEB128 format, 7-bits -- at a time until all non zero bits are written. The <tt>Last</tt> parameter is updated -- to indicate the position of the last valid byte written in <tt>Into</tt>. procedure Encode_LEB128 (Into : in out Ada.Streams.Stream_Element_Array; Pos : in Ada.Streams.Stream_Element_Offset; Val : in Interfaces.Unsigned_64; Last : out Ada.Streams.Stream_Element_Offset); -- Decode from the byte array <tt>From</tt> the value represented as LEB128 format starting -- at position <tt>Pos</tt> in that array. After decoding, the <tt>Last</tt> index is updated -- to indicate the last position in the byte array. procedure Decode_LEB128 (From : in Ada.Streams.Stream_Element_Array; Pos : in Ada.Streams.Stream_Element_Offset; Val : out Interfaces.Unsigned_64; Last : out Ada.Streams.Stream_Element_Offset); private use Ada.Finalization; type Secret_Key (Length : Key_Length) is limited new Limited_Controlled with record Secret : Ada.Streams.Stream_Element_Array (1 .. Length) := (others => 0); end record; overriding procedure Finalize (Object : in out Secret_Key); -- Transform the input data into the target string. procedure Convert (E : in out Transformer'Class; Data : in Ada.Streams.Stream_Element_Array; Into : out String); type Encoder is limited new Limited_Controlled with record Encode : Transformer_Access := null; end record; -- Delete the transformers overriding procedure Finalize (E : in out Encoder); type Decoder is limited new Limited_Controlled with record Decode : Transformer_Access := null; end record; -- Delete the transformers overriding procedure Finalize (E : in out Decoder); end Util.Encoders;
Declare Secret_Key type to hold a secret key and erase memory when it is removed
Declare Secret_Key type to hold a secret key and erase memory when it is removed
Ada
apache-2.0
stcarrez/ada-util,stcarrez/ada-util
63a3dd450125f3d09c8ed406b900b33c4de6d30e
src/sys/http/util-http-clients.adb
src/sys/http/util-http-clients.adb
----------------------------------------------------------------------- -- util-http-clients -- HTTP Clients -- 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 Ada.Unchecked_Deallocation; with Util.Log.Loggers; package body Util.Http.Clients is Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("Util.Http.Clients"); procedure Initialize (Form : in out Form_Data; Size : in Positive) is begin Form.Buffer.Initialize (Output => null, Size => Size); Form.Initialize (Form.Buffer'Unchecked_Access); end Initialize; -- ------------------------------ -- Returns a boolean indicating whether the named response header has already -- been set. -- ------------------------------ overriding function Contains_Header (Reply : in Response; Name : in String) return Boolean is begin if Reply.Delegate = null then return False; else return Reply.Delegate.Contains_Header (Name); end if; end Contains_Header; -- ------------------------------ -- Returns the value of the specified response header as a String. If the response -- did not include a header of the specified name, this method returns null. -- If there are multiple headers with the same name, this method returns the -- first head in the request. The header name is case insensitive. You can use -- this method with any response header. -- ------------------------------ overriding function Get_Header (Reply : in Response; Name : in String) return String is begin if Reply.Delegate = null then return ""; else return Reply.Delegate.Get_Header (Name); end if; end Get_Header; -- ------------------------------ -- Sets a message header with the given name and value. If the header had already -- been set, the new value overwrites the previous one. The containsHeader -- method can be used to test for the presence of a header before setting its value. -- ------------------------------ overriding procedure Set_Header (Reply : in out Response; Name : in String; Value : in String) is begin Reply.Delegate.Set_Header (Name, Value); end Set_Header; -- ------------------------------ -- Adds a request header with the given name and value. -- This method allows request headers to have multiple values. -- ------------------------------ overriding procedure Add_Header (Reply : in out Response; Name : in String; Value : in String) is begin Reply.Delegate.Add_Header (Name, Value); end Add_Header; -- ------------------------------ -- Iterate over the response headers and executes the <b>Process</b> procedure. -- ------------------------------ overriding procedure Iterate_Headers (Reply : in Response; Process : not null access procedure (Name : in String; Value : in String)) is begin if Reply.Delegate /= null then Reply.Delegate.Iterate_Headers (Process); end if; end Iterate_Headers; -- ------------------------------ -- Get the response body as a string. -- ------------------------------ overriding function Get_Body (Reply : in Response) return String is begin if Reply.Delegate = null then return ""; else return Reply.Delegate.Get_Body; end if; end Get_Body; -- ------------------------------ -- Get the response status code. -- ------------------------------ function Get_Status (Reply : in Response) return Natural is begin return Reply.Delegate.Get_Status; end Get_Status; -- ------------------------------ -- Returns a boolean indicating whether the named response header has already -- been set. -- ------------------------------ overriding function Contains_Header (Request : in Client; Name : in String) return Boolean is begin if Request.Delegate = null then return False; else return Request.Delegate.Contains_Header (Name); end if; end Contains_Header; -- ------------------------------ -- Returns the value of the specified request header as a String. If the request -- did not include a header of the specified name, this method returns null. -- If there are multiple headers with the same name, this method returns the -- first head in the request. The header name is case insensitive. You can use -- this method with any response header. -- ------------------------------ overriding function Get_Header (Request : in Client; Name : in String) return String is begin if Request.Delegate = null then return ""; else return Request.Delegate.Get_Header (Name); end if; end Get_Header; -- ------------------------------ -- Sets a header with the given name and value. If the header had already -- been set, the new value overwrites the previous one. The containsHeader -- method can be used to test for the presence of a header before setting its value. -- ------------------------------ overriding procedure Set_Header (Request : in out Client; Name : in String; Value : in String) is begin Request.Delegate.Set_Header (Name, Value); end Set_Header; -- ------------------------------ -- Adds a header with the given name and value. -- This method allows headers to have multiple values. -- ------------------------------ overriding procedure Add_Header (Request : in out Client; Name : in String; Value : in String) is begin Request.Delegate.Add_Header (Name, Value); end Add_Header; -- ------------------------------ -- Iterate over the request headers and executes the <b>Process</b> procedure. -- ------------------------------ overriding procedure Iterate_Headers (Request : in Client; Process : not null access procedure (Name : in String; Value : in String)) is begin Request.Delegate.Iterate_Headers (Process); end Iterate_Headers; -- ------------------------------ -- Removes all headers with the given name. -- ------------------------------ procedure Remove_Header (Request : in out Client; Name : in String) is begin null; end Remove_Header; -- ------------------------------ -- Initialize the client -- ------------------------------ overriding procedure Initialize (Http : in out Client) is begin Http.Delegate := null; Http.Manager := Default_Http_Manager; if Http.Manager = null then Log.Error ("No HTTP manager was defined"); raise Program_Error with "No HTTP manager was defined."; end if; Http.Manager.Create (Http); end Initialize; overriding procedure Finalize (Http : in out Client) is procedure Free is new Ada.Unchecked_Deallocation (Http_Request'Class, Http_Request_Access); begin Free (Http.Delegate); end Finalize; -- ------------------------------ -- Execute an http GET request on the given URL. Additional request parameters, -- cookies and headers should have been set on the client object. -- ------------------------------ procedure Get (Request : in out Client; URL : in String; Reply : out Response'Class) is begin Request.Manager.Do_Get (Request, URL, Reply); end Get; -- ------------------------------ -- Execute an http POST request on the given URL. The post data is passed in <b>Data</b>. -- Additional request cookies and headers should have been set on the client object. -- ------------------------------ procedure Post (Request : in out Client; URL : in String; Data : in String; Reply : out Response'Class) is begin Request.Manager.Do_Post (Request, URL, Data, Reply); end Post; procedure Post (Request : in out Client; URL : in String; Data : in Form_Data'Class; Reply : out Response'Class) is begin Request.Manager.Do_Post (Request, URL, Util.Streams.Texts.To_String (Data.Buffer), Reply); end Post; -- ------------------------------ -- Execute an http PUT request on the given URL. The post data is passed in <b>Data</b>. -- Additional request cookies and headers should have been set on the client object. -- ------------------------------ procedure Put (Request : in out Client; URL : in String; Data : in String; Reply : out Response'Class) is begin Request.Manager.Do_Put (Request, URL, Data, Reply); end Put; -- ------------------------------ -- Execute a http DELETE request on the given URL. -- ------------------------------ procedure Delete (Request : in out Client; URL : in String; Reply : out Response'Class) is begin Request.Manager.Do_Delete (Request, URL, Reply); end Delete; -- ------------------------------ -- Set the timeout for the connection. -- ------------------------------ procedure Set_Timeout (Request : in out Client; Timeout : in Duration) is begin Request.Manager.Set_Timeout (Request, Timeout); end Set_Timeout; -- ------------------------------ -- Adds the specified cookie to the request. This method can be called multiple -- times to set more than one cookie. -- ------------------------------ procedure Add_Cookie (Http : in out Client; Cookie : in Util.Http.Cookies.Cookie) is begin null; end Add_Cookie; -- ------------------------------ -- Free the resource used by the response. -- ------------------------------ overriding procedure Finalize (Reply : in out Response) is procedure Free is new Ada.Unchecked_Deallocation (Http_Response'Class, Http_Response_Access); begin Free (Reply.Delegate); end Finalize; end Util.Http.Clients;
----------------------------------------------------------------------- -- util-http-clients -- HTTP Clients -- Copyright (C) 2011, 2012, 2013, 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 Ada.Unchecked_Deallocation; with Util.Log.Loggers; package body Util.Http.Clients is Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("Util.Http.Clients"); procedure Initialize (Form : in out Form_Data; Size : in Positive) is begin Form.Buffer.Initialize (Output => null, Size => Size); Form.Initialize (Form.Buffer'Unchecked_Access); end Initialize; -- ------------------------------ -- Returns a boolean indicating whether the named response header has already -- been set. -- ------------------------------ overriding function Contains_Header (Reply : in Response; Name : in String) return Boolean is begin if Reply.Delegate = null then return False; else return Reply.Delegate.Contains_Header (Name); end if; end Contains_Header; -- ------------------------------ -- Returns the value of the specified response header as a String. If the response -- did not include a header of the specified name, this method returns null. -- If there are multiple headers with the same name, this method returns the -- first head in the request. The header name is case insensitive. You can use -- this method with any response header. -- ------------------------------ overriding function Get_Header (Reply : in Response; Name : in String) return String is begin if Reply.Delegate = null then return ""; else return Reply.Delegate.Get_Header (Name); end if; end Get_Header; -- ------------------------------ -- Sets a message header with the given name and value. If the header had already -- been set, the new value overwrites the previous one. The containsHeader -- method can be used to test for the presence of a header before setting its value. -- ------------------------------ overriding procedure Set_Header (Reply : in out Response; Name : in String; Value : in String) is begin Reply.Delegate.Set_Header (Name, Value); end Set_Header; -- ------------------------------ -- Adds a request header with the given name and value. -- This method allows request headers to have multiple values. -- ------------------------------ overriding procedure Add_Header (Reply : in out Response; Name : in String; Value : in String) is begin Reply.Delegate.Add_Header (Name, Value); end Add_Header; -- ------------------------------ -- Iterate over the response headers and executes the <b>Process</b> procedure. -- ------------------------------ overriding procedure Iterate_Headers (Reply : in Response; Process : not null access procedure (Name : in String; Value : in String)) is begin if Reply.Delegate /= null then Reply.Delegate.Iterate_Headers (Process); end if; end Iterate_Headers; -- ------------------------------ -- Get the response body as a string. -- ------------------------------ overriding function Get_Body (Reply : in Response) return String is begin if Reply.Delegate = null then return ""; else return Reply.Delegate.Get_Body; end if; end Get_Body; -- ------------------------------ -- Get the response status code. -- ------------------------------ function Get_Status (Reply : in Response) return Natural is begin return Reply.Delegate.Get_Status; end Get_Status; -- ------------------------------ -- Returns a boolean indicating whether the named response header has already -- been set. -- ------------------------------ overriding function Contains_Header (Request : in Client; Name : in String) return Boolean is begin if Request.Delegate = null then return False; else return Request.Delegate.Contains_Header (Name); end if; end Contains_Header; -- ------------------------------ -- Returns the value of the specified request header as a String. If the request -- did not include a header of the specified name, this method returns null. -- If there are multiple headers with the same name, this method returns the -- first head in the request. The header name is case insensitive. You can use -- this method with any response header. -- ------------------------------ overriding function Get_Header (Request : in Client; Name : in String) return String is begin if Request.Delegate = null then return ""; else return Request.Delegate.Get_Header (Name); end if; end Get_Header; -- ------------------------------ -- Sets a header with the given name and value. If the header had already -- been set, the new value overwrites the previous one. The containsHeader -- method can be used to test for the presence of a header before setting its value. -- ------------------------------ overriding procedure Set_Header (Request : in out Client; Name : in String; Value : in String) is begin Request.Delegate.Set_Header (Name, Value); end Set_Header; -- ------------------------------ -- Adds a header with the given name and value. -- This method allows headers to have multiple values. -- ------------------------------ overriding procedure Add_Header (Request : in out Client; Name : in String; Value : in String) is begin Request.Delegate.Add_Header (Name, Value); end Add_Header; -- ------------------------------ -- Iterate over the request headers and executes the <b>Process</b> procedure. -- ------------------------------ overriding procedure Iterate_Headers (Request : in Client; Process : not null access procedure (Name : in String; Value : in String)) is begin Request.Delegate.Iterate_Headers (Process); end Iterate_Headers; -- ------------------------------ -- Removes all headers with the given name. -- ------------------------------ procedure Remove_Header (Request : in out Client; Name : in String) is begin null; end Remove_Header; -- ------------------------------ -- Initialize the client -- ------------------------------ overriding procedure Initialize (Http : in out Client) is begin Http.Delegate := null; Http.Manager := Default_Http_Manager; if Http.Manager = null then Log.Error ("No HTTP manager was defined"); raise Program_Error with "No HTTP manager was defined."; end if; Http.Manager.Create (Http); end Initialize; overriding procedure Finalize (Http : in out Client) is procedure Free is new Ada.Unchecked_Deallocation (Http_Request'Class, Http_Request_Access); begin Free (Http.Delegate); end Finalize; -- ------------------------------ -- Execute an http GET request on the given URL. Additional request parameters, -- cookies and headers should have been set on the client object. -- ------------------------------ procedure Get (Request : in out Client; URL : in String; Reply : out Response'Class) is begin Request.Manager.Do_Get (Request, URL, Reply); end Get; -- ------------------------------ -- Execute an http POST request on the given URL. The post data is passed in <b>Data</b>. -- Additional request cookies and headers should have been set on the client object. -- ------------------------------ procedure Post (Request : in out Client; URL : in String; Data : in String; Reply : out Response'Class) is begin Request.Manager.Do_Post (Request, URL, Data, Reply); end Post; procedure Post (Request : in out Client; URL : in String; Data : in Form_Data'Class; Reply : out Response'Class) is begin Request.Manager.Do_Post (Request, URL, Util.Streams.Texts.To_String (Data.Buffer), Reply); end Post; -- ------------------------------ -- Execute an http PUT request on the given URL. The post data is passed in <b>Data</b>. -- Additional request cookies and headers should have been set on the client object. -- ------------------------------ procedure Put (Request : in out Client; URL : in String; Data : in String; Reply : out Response'Class) is begin Request.Manager.Do_Put (Request, URL, Data, Reply); end Put; -- ------------------------------ -- Execute an http PATCH request on the given URL. The post data is passed in <b>Data</b>. -- Additional request cookies and headers should have been set on the client object. -- ------------------------------ procedure Patch (Request : in out Client; URL : in String; Data : in String; Reply : out Response'Class) is begin Request.Manager.Do_Patch (Request, URL, Data, Reply); end Patch; -- ------------------------------ -- Execute a http DELETE request on the given URL. -- ------------------------------ procedure Delete (Request : in out Client; URL : in String; Reply : out Response'Class) is begin Request.Manager.Do_Delete (Request, URL, Reply); end Delete; -- ------------------------------ -- Execute an http HEAD request on the given URL. Additional request parameters, -- cookies and headers should have been set on the client object. -- ------------------------------ procedure Head (Request : in out Client; URL : in String; Reply : out Response'Class) is begin Request.Manager.Do_Head (Request, URL, Reply); end Head; -- ------------------------------ -- Execute an http OPTIONS request on the given URL. Additional request parameters, -- cookies and headers should have been set on the client object. -- ------------------------------ procedure Options (Request : in out Client; URL : in String; Reply : out Response'Class) is begin Request.Manager.Do_Options (Request, URL, Reply); end Options; -- ------------------------------ -- Set the timeout for the connection. -- ------------------------------ procedure Set_Timeout (Request : in out Client; Timeout : in Duration) is begin Request.Manager.Set_Timeout (Request, Timeout); end Set_Timeout; -- ------------------------------ -- Adds the specified cookie to the request. This method can be called multiple -- times to set more than one cookie. -- ------------------------------ procedure Add_Cookie (Http : in out Client; Cookie : in Util.Http.Cookies.Cookie) is begin null; end Add_Cookie; -- ------------------------------ -- Free the resource used by the response. -- ------------------------------ overriding procedure Finalize (Reply : in out Response) is procedure Free is new Ada.Unchecked_Deallocation (Http_Response'Class, Http_Response_Access); begin Free (Reply.Delegate); end Finalize; end Util.Http.Clients;
Implement operations to support HTTP Head, Patch, Options
Implement operations to support HTTP Head, Patch, Options
Ada
apache-2.0
stcarrez/ada-util,stcarrez/ada-util
25ce4654bff0c6ebba5b266040942769eee98b2a
awa/src/awa-modules-reader.adb
awa/src/awa-modules-reader.adb
----------------------------------------------------------------------- -- awa-modules-reader -- Read module configuration files -- 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.Serialize.IO.XML; with AWA.Applications.Configs; -- The <b>AWA.Modules.Reader</b> package reads the module configuration files -- and initializes the module. package body AWA.Modules.Reader is -- ------------------------------ -- Read the module configuration file and configure the components -- ------------------------------ procedure Read_Configuration (Plugin : in out Module'Class; File : in String; Context : in EL.Contexts.Default.Default_Context_Access) is Reader : Util.Serialize.IO.XML.Parser; package Config is new AWA.Applications.Configs.Reader_Config (Reader, Plugin.App.all'Unchecked_Access, Context); pragma Warnings (Off, Config); begin Log.Info ("Reading module configuration file {0}", File); if AWA.Modules.Log.Get_Level >= Util.Log.DEBUG_LEVEL then Util.Serialize.IO.Dump (Reader, AWA.Modules.Log); end if; -- Read the configuration file and record managed beans, navigation rules. Reader.Parse (File); exception when others => Log.Error ("Error while reading {0}", File); raise; end Read_Configuration; end AWA.Modules.Reader;
----------------------------------------------------------------------- -- awa-modules-reader -- Read module configuration files -- 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.Serialize.IO.XML; with AWA.Applications.Configs; with Security.Policies; -- The <b>AWA.Modules.Reader</b> package reads the module configuration files -- and initializes the module. package body AWA.Modules.Reader is -- ------------------------------ -- Read the module configuration file and configure the components -- ------------------------------ procedure Read_Configuration (Plugin : in out Module'Class; File : in String; Context : in EL.Contexts.Default.Default_Context_Access) is Reader : Util.Serialize.IO.XML.Parser; package Config is new AWA.Applications.Configs.Reader_Config (Reader, Plugin.App.all'Unchecked_Access, Context); pragma Warnings (Off, Config); Sec : constant Security.Policies.Policy_Manager_Access := Plugin.App.Get_Security_Manager; begin Log.Info ("Reading module configuration file {0}", File); Sec.Prepare_Config (Reader); if AWA.Modules.Log.Get_Level >= Util.Log.DEBUG_LEVEL then Util.Serialize.IO.Dump (Reader, AWA.Modules.Log); end if; -- Read the configuration file and record managed beans, navigation rules. Reader.Parse (File); Sec.Finish_Config (Reader); exception when others => Log.Error ("Error while reading {0}", File); raise; end Read_Configuration; end AWA.Modules.Reader;
Call Prepare_Config on the security manager before reading the module XML configuration
Call Prepare_Config on the security manager before reading the module XML configuration
Ada
apache-2.0
tectronics/ada-awa,Letractively/ada-awa,tectronics/ada-awa,tectronics/ada-awa,Letractively/ada-awa,Letractively/ada-awa
865851a744798e7b9f60b1b2fe3a94ba9a56e4c6
src/natools-web-sites.adb
src/natools-web-sites.adb
------------------------------------------------------------------------------ -- Copyright (c) 2014, 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. -- ------------------------------------------------------------------------------ with Natools.S_Expressions.Atom_Ref_Constructors; with Natools.S_Expressions.File_Readers; with Natools.S_Expressions.Interpreter_Loop; with Natools.Static_Maps.Web.Sites; with Natools.Web.Pages; package body Natools.Web.Sites is procedure Add_Page (Builder : in out Site_Builder; File_Root : in S_Expressions.Atom; Path_Root : in S_Expressions.Atom); procedure Add_Page (Builder : in out Site_Builder; Context : in Meaningless_Type; File_Name : in S_Expressions.Atom; Arguments : in out S_Expressions.Lockable.Descriptor'Class); procedure Add_Page_Simple (Builder : in out Site_Builder; Context : in Meaningless_Type; Common_Name : in S_Expressions.Atom); procedure Get_Page (Container : in Page_Maps.Updatable_Map; Path : in S_Expressions.Atom; Result : out Page_Maps.Cursor; Extra_Path_First : out S_Expressions.Offset); procedure Execute (Builder : in out Site_Builder; Context : in Meaningless_Type; Name : in S_Expressions.Atom; Arguments : in out S_Expressions.Lockable.Descriptor'Class); procedure Set_If_Possible (Reference : in out S_Expressions.Atom_Refs.Immutable_Reference; Expression : in S_Expressions.Lockable.Descriptor'Class); ------------------------------ -- Local Helper Subprograms -- ------------------------------ procedure Get_Page (Container : in Page_Maps.Updatable_Map; Path : in S_Expressions.Atom; Result : out Page_Maps.Cursor; Extra_Path_First : out S_Expressions.Offset) is use type S_Expressions.Atom; use type S_Expressions.Octet; use type S_Expressions.Offset; begin Result := Container.Floor (Path); if not Page_Maps.Has_Element (Result) then Extra_Path_First := 0; return; end if; declare Found_Path : constant S_Expressions.Atom := Page_Maps.Key (Result); begin if Found_Path'Length > Path'Length or else Path (Path'First .. Path'First + Found_Path'Length - 1) /= Found_Path then Page_Maps.Clear (Result); return; end if; Extra_Path_First := Path'First + Found_Path'Length; end; if Extra_Path_First in Path'Range and then Path (Extra_Path_First) /= Character'Pos ('/') then Page_Maps.Clear (Result); return; end if; end Get_Page; procedure Set_If_Possible (Reference : in out S_Expressions.Atom_Refs.Immutable_Reference; Expression : in S_Expressions.Lockable.Descriptor'Class) is use type S_Expressions.Events.Event; begin if Expression.Current_Event = S_Expressions.Events.Add_Atom then Reference := S_Expressions.Atom_Ref_Constructors.Create (Expression.Current_Atom); end if; end Set_If_Possible; ---------------------- -- Site Interpreter -- ---------------------- procedure Add_Page (Builder : in out Site_Builder; File_Root : in S_Expressions.Atom; Path_Root : in S_Expressions.Atom) is use type S_Expressions.Atom; File : constant S_Expressions.Atom := Builder.File_Prefix.Query.Data.all & File_Root & Builder.File_Suffix.Query.Data.all; Path : constant S_Expressions.Atom := Builder.Path_Prefix.Query.Data.all & Path_Root & Builder.Path_Suffix.Query.Data.all; Page : constant Pages.Page_Ref := Pages.Create (File, Path); begin Builder.Pages.Insert (Path, Page); end Add_Page; procedure Add_Page (Builder : in out Site_Builder; Context : in Meaningless_Type; File_Name : in S_Expressions.Atom; Arguments : in out S_Expressions.Lockable.Descriptor'Class) is pragma Unreferenced (Context); use type S_Expressions.Events.Event; begin if Arguments.Current_Event = S_Expressions.Events.Add_Atom then Add_Page (Builder, File_Name, Arguments.Current_Atom); end if; end Add_Page; procedure Add_Page_Simple (Builder : in out Site_Builder; Context : in Meaningless_Type; Common_Name : in S_Expressions.Atom) is pragma Unreferenced (Context); begin Add_Page (Builder, Common_Name, Common_Name); end Add_Page_Simple; procedure Add_Pages is new S_Expressions.Interpreter_Loop (Site_Builder, Meaningless_Type, Add_Page, Add_Page_Simple); procedure Execute (Builder : in out Site_Builder; Context : in Meaningless_Type; Name : in S_Expressions.Atom; Arguments : in out S_Expressions.Lockable.Descriptor'Class) is pragma Unreferenced (Context); package Commands renames Natools.Static_Maps.Web.Sites; use type S_Expressions.Events.Event; begin case Commands.To_Command (S_Expressions.To_String (Name)) is when Commands.Error => Log (Severities.Error, "Unknown site command """ & S_Expressions.To_String (Name) & '"'); when Commands.Set_Default_Template => Set_If_Possible (Builder.Default_Template, Arguments); when Commands.Set_File_Prefix => Set_If_Possible (Builder.File_Prefix, Arguments); when Commands.Set_File_Suffix => Set_If_Possible (Builder.File_Suffix, Arguments); when Commands.Set_Path_Prefix => Set_If_Possible (Builder.Path_Prefix, Arguments); when Commands.Set_Path_Suffix => Set_If_Possible (Builder.Path_Suffix, Arguments); when Commands.Set_Template_File => if Arguments.Current_Event = S_Expressions.Events.Add_Atom then declare Reader : S_Expressions.File_Readers.S_Reader := S_Expressions.File_Readers.Reader (S_Expressions.To_String (Arguments.Current_Atom)); begin Containers.Set_Expressions (Builder.Templates, Reader); end; end if; when Commands.Set_Templates => Containers.Set_Expressions (Builder.Templates, Arguments); when Commands.Site_Map => Add_Pages (Arguments, Builder, Meaningless_Value); end case; end Execute; procedure Interpreter is new S_Expressions.Interpreter_Loop (Site_Builder, Meaningless_Type, Execute); procedure Update (Builder : in out Site_Builder; Expression : in out S_Expressions.Lockable.Descriptor'Class) is begin Interpreter (Expression, Builder, Meaningless_Value); end Update; --------------------------- -- Site Public Interface -- --------------------------- function Create (File_Name : String) return Site is Result : Site := (File_Name => S_Expressions.Atom_Ref_Constructors.Create (S_Expressions.To_Atom (File_Name)), others => <>); begin Reload (Result); return Result; end Create; procedure Reload (Object : in out Site) is Reader : S_Expressions.File_Readers.S_Reader := S_Expressions.File_Readers.Reader (S_Expressions.To_String (Object.File_Name.Query.Data.all)); Builder : Site_Builder; begin Update (Builder, Reader); Object := (Default_Template => Builder.Default_Template, File_Name => Object.File_Name, Pages => Page_Maps.Create (Builder.Pages), Templates => Builder.Templates); if Object.Default_Template.Is_Empty then Object.Default_Template := S_Expressions.Atom_Ref_Constructors.Create (S_Expressions.To_Atom ("html")); end if; end Reload; procedure Respond (Object : aliased in out Site; Exchange : in out Exchanges.Exchange) is use type S_Expressions.Octet; use type S_Expressions.Offset; procedure Call_Page (Key : in S_Expressions.Atom; Page_Object : in out Page'Class); Path : constant S_Expressions.Atom := S_Expressions.To_Atom (Exchanges.Path (Exchange)); procedure Call_Page (Key : in S_Expressions.Atom; Page_Object : in out Page'Class) is use type S_Expressions.Atom; begin pragma Assert (Key'Length <= Path'Length and then Key = Path (Path'First .. Path'First + Key'Length - 1)); Respond (Page_Object, Exchange, Object, Path (Path'First + Key'Length .. Path'Last)); end Call_Page; Cursor : Page_Maps.Cursor; Extra_Path_First : S_Expressions.Offset; begin Get_Page (Object.Pages, Path, Cursor, Extra_Path_First); if not Page_Maps.Has_Element (Cursor) then return; end if; Response_Loop : loop Object.Pages.Update_Element (Cursor, Call_Page'Access); exit Response_Loop when Exchanges.Has_Response (Exchange); Find_Parent : loop Remove_Path_Component : loop Extra_Path_First := Extra_Path_First - 1; exit Response_Loop when Extra_Path_First not in Path'Range; exit Remove_Path_Component when Path (Extra_Path_First) = Character'Pos ('/'); end loop Remove_Path_Component; Cursor := Object.Pages.Find (Path (Path'First .. Extra_Path_First - 1)); exit Find_Parent when Page_Maps.Has_Element (Cursor); end loop Find_Parent; end loop Response_Loop; end Respond; ------------------------- -- Site Data Accessors -- ------------------------- function Default_Template (Object : Site) return S_Expressions.Atom is begin return Object.Default_Template.Query.Data.all; end Default_Template; function Template (Object : Site; Name : S_Expressions.Atom) return S_Expressions.Caches.Cursor is begin return Containers.Get_Expression (Object.Templates, Name); end Template; end Natools.Web.Sites;
------------------------------------------------------------------------------ -- Copyright (c) 2014, 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. -- ------------------------------------------------------------------------------ with Natools.S_Expressions.Atom_Ref_Constructors; with Natools.S_Expressions.File_Readers; with Natools.S_Expressions.Interpreter_Loop; with Natools.Static_Maps.Web.Sites; with Natools.Web.Pages; package body Natools.Web.Sites is procedure Add_Page (Builder : in out Site_Builder; File_Root : in S_Expressions.Atom; Path_Root : in S_Expressions.Atom); procedure Add_Page (Builder : in out Site_Builder; Context : in Meaningless_Type; File_Name : in S_Expressions.Atom; Arguments : in out S_Expressions.Lockable.Descriptor'Class); procedure Add_Page_Simple (Builder : in out Site_Builder; Context : in Meaningless_Type; Common_Name : in S_Expressions.Atom); procedure Get_Page (Container : in Page_Maps.Updatable_Map; Path : in S_Expressions.Atom; Result : out Page_Maps.Cursor; Extra_Path_First : out S_Expressions.Offset); procedure Execute (Builder : in out Site_Builder; Context : in Meaningless_Type; Name : in S_Expressions.Atom; Arguments : in out S_Expressions.Lockable.Descriptor'Class); procedure Set_If_Possible (Reference : in out S_Expressions.Atom_Refs.Immutable_Reference; Expression : in S_Expressions.Lockable.Descriptor'Class); ------------------------------ -- Local Helper Subprograms -- ------------------------------ procedure Get_Page (Container : in Page_Maps.Updatable_Map; Path : in S_Expressions.Atom; Result : out Page_Maps.Cursor; Extra_Path_First : out S_Expressions.Offset) is use type S_Expressions.Atom; use type S_Expressions.Octet; use type S_Expressions.Offset; begin Result := Container.Floor (Path); if not Page_Maps.Has_Element (Result) then Extra_Path_First := 0; return; end if; declare Found_Path : constant S_Expressions.Atom := Page_Maps.Key (Result); begin if Found_Path'Length > Path'Length or else Path (Path'First .. Path'First + Found_Path'Length - 1) /= Found_Path then Page_Maps.Clear (Result); return; end if; Extra_Path_First := Path'First + Found_Path'Length; end; if Extra_Path_First in Path'Range and then Path (Extra_Path_First) /= Character'Pos ('/') then Page_Maps.Clear (Result); return; end if; end Get_Page; procedure Set_If_Possible (Reference : in out S_Expressions.Atom_Refs.Immutable_Reference; Expression : in S_Expressions.Lockable.Descriptor'Class) is use type S_Expressions.Events.Event; begin if Expression.Current_Event = S_Expressions.Events.Add_Atom then Reference := S_Expressions.Atom_Ref_Constructors.Create (Expression.Current_Atom); end if; end Set_If_Possible; ---------------------- -- Site Interpreter -- ---------------------- procedure Add_Page (Builder : in out Site_Builder; File_Root : in S_Expressions.Atom; Path_Root : in S_Expressions.Atom) is use type S_Expressions.Atom; File : constant S_Expressions.Atom := Builder.File_Prefix.Query.Data.all & File_Root & Builder.File_Suffix.Query.Data.all; Path : constant S_Expressions.Atom := Builder.Path_Prefix.Query.Data.all & Path_Root & Builder.Path_Suffix.Query.Data.all; Page : constant Pages.Page_Ref := Pages.Create (File, Path); begin Builder.Pages.Insert (Path, Page); end Add_Page; procedure Add_Page (Builder : in out Site_Builder; Context : in Meaningless_Type; File_Name : in S_Expressions.Atom; Arguments : in out S_Expressions.Lockable.Descriptor'Class) is pragma Unreferenced (Context); use type S_Expressions.Events.Event; begin if Arguments.Current_Event = S_Expressions.Events.Add_Atom then Add_Page (Builder, File_Name, Arguments.Current_Atom); end if; end Add_Page; procedure Add_Page_Simple (Builder : in out Site_Builder; Context : in Meaningless_Type; Common_Name : in S_Expressions.Atom) is pragma Unreferenced (Context); begin Add_Page (Builder, Common_Name, Common_Name); end Add_Page_Simple; procedure Add_Pages is new S_Expressions.Interpreter_Loop (Site_Builder, Meaningless_Type, Add_Page, Add_Page_Simple); procedure Execute (Builder : in out Site_Builder; Context : in Meaningless_Type; Name : in S_Expressions.Atom; Arguments : in out S_Expressions.Lockable.Descriptor'Class) is pragma Unreferenced (Context); package Commands renames Natools.Static_Maps.Web.Sites; use type S_Expressions.Events.Event; begin case Commands.To_Command (S_Expressions.To_String (Name)) is when Commands.Error => Log (Severities.Error, "Unknown site command """ & S_Expressions.To_String (Name) & '"'); when Commands.Set_Default_Template => Set_If_Possible (Builder.Default_Template, Arguments); when Commands.Set_File_Prefix => Set_If_Possible (Builder.File_Prefix, Arguments); when Commands.Set_File_Suffix => Set_If_Possible (Builder.File_Suffix, Arguments); when Commands.Set_Path_Prefix => Set_If_Possible (Builder.Path_Prefix, Arguments); when Commands.Set_Path_Suffix => Set_If_Possible (Builder.Path_Suffix, Arguments); when Commands.Set_Template_File => if Arguments.Current_Event = S_Expressions.Events.Add_Atom then declare Reader : S_Expressions.File_Readers.S_Reader := S_Expressions.File_Readers.Reader (S_Expressions.To_String (Arguments.Current_Atom)); begin Containers.Set_Expressions (Builder.Templates, Reader); end; end if; when Commands.Set_Templates => Containers.Set_Expressions (Builder.Templates, Arguments); when Commands.Site_Map => Add_Pages (Arguments, Builder, Meaningless_Value); end case; end Execute; procedure Interpreter is new S_Expressions.Interpreter_Loop (Site_Builder, Meaningless_Type, Execute); procedure Update (Builder : in out Site_Builder; Expression : in out S_Expressions.Lockable.Descriptor'Class) is begin Interpreter (Expression, Builder, Meaningless_Value); end Update; --------------------------- -- Site Public Interface -- --------------------------- function Create (File_Name : String) return Site is Result : Site := (File_Name => S_Expressions.Atom_Ref_Constructors.Create (S_Expressions.To_Atom (File_Name)), others => <>); begin Reload (Result); return Result; end Create; procedure Reload (Object : in out Site) is Reader : S_Expressions.File_Readers.S_Reader := S_Expressions.File_Readers.Reader (S_Expressions.To_String (Object.File_Name.Query.Data.all)); Empty_Atom : constant S_Expressions.Atom_Refs.Immutable_Reference := S_Expressions.Atom_Ref_Constructors.Create (S_Expressions.Null_Atom); Builder : Site_Builder := (Default_Template => S_Expressions.Atom_Refs.Null_Immutable_Reference, File_Prefix => Empty_Atom, File_Suffix => Empty_Atom, Path_Prefix => Empty_Atom, Path_Suffix => Empty_Atom, Pages | Templates => <>); begin Update (Builder, Reader); Object := (Default_Template => Builder.Default_Template, File_Name => Object.File_Name, Pages => Page_Maps.Create (Builder.Pages), Templates => Builder.Templates); if Object.Default_Template.Is_Empty then Object.Default_Template := S_Expressions.Atom_Ref_Constructors.Create (S_Expressions.To_Atom ("html")); end if; end Reload; procedure Respond (Object : aliased in out Site; Exchange : in out Exchanges.Exchange) is use type S_Expressions.Octet; use type S_Expressions.Offset; procedure Call_Page (Key : in S_Expressions.Atom; Page_Object : in out Page'Class); Path : constant S_Expressions.Atom := S_Expressions.To_Atom (Exchanges.Path (Exchange)); procedure Call_Page (Key : in S_Expressions.Atom; Page_Object : in out Page'Class) is use type S_Expressions.Atom; begin pragma Assert (Key'Length <= Path'Length and then Key = Path (Path'First .. Path'First + Key'Length - 1)); Respond (Page_Object, Exchange, Object, Path (Path'First + Key'Length .. Path'Last)); end Call_Page; Cursor : Page_Maps.Cursor; Extra_Path_First : S_Expressions.Offset; begin Get_Page (Object.Pages, Path, Cursor, Extra_Path_First); if not Page_Maps.Has_Element (Cursor) then return; end if; Response_Loop : loop Object.Pages.Update_Element (Cursor, Call_Page'Access); exit Response_Loop when Exchanges.Has_Response (Exchange); Find_Parent : loop Remove_Path_Component : loop Extra_Path_First := Extra_Path_First - 1; exit Response_Loop when Extra_Path_First not in Path'Range; exit Remove_Path_Component when Path (Extra_Path_First) = Character'Pos ('/'); end loop Remove_Path_Component; Cursor := Object.Pages.Find (Path (Path'First .. Extra_Path_First - 1)); exit Find_Parent when Page_Maps.Has_Element (Cursor); end loop Find_Parent; end loop Response_Loop; end Respond; ------------------------- -- Site Data Accessors -- ------------------------- function Default_Template (Object : Site) return S_Expressions.Atom is begin return Object.Default_Template.Query.Data.all; end Default_Template; function Template (Object : Site; Name : S_Expressions.Atom) return S_Expressions.Caches.Cursor is begin return Containers.Get_Expression (Object.Templates, Name); end Template; end Natools.Web.Sites;
fix initialization of site builders
sites: fix initialization of site builders
Ada
isc
faelys/natools-web,faelys/natools-web
fbf9dae02abfd6dfef1abed11ce53332fcff301a
src/wiki-parsers-html.adb
src/wiki-parsers-html.adb
----------------------------------------------------------------------- -- wiki-parsers-html -- Wiki HTML parser -- Copyright (C) 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.Characters.Conversions; with Wiki.Helpers; with Wiki.Parsers.Html.Entities; package body Wiki.Parsers.Html is -- Parse an HTML attribute procedure Parse_Attribute_Name (P : in out Parser; Name : in out Unbounded_Wide_Wide_String); -- Parse a HTML/XML comment to strip it. procedure Parse_Comment (P : in out Parser); -- Parse a simple DOCTYPE declaration and ignore it. procedure Parse_Doctype (P : in out Parser); procedure Collect_Attributes (P : in out Parser); function Is_Letter (C : in Wide_Wide_Character) return Boolean; procedure Collect_Attribute_Value (P : in out Parser; Value : in out Unbounded_Wide_Wide_String); function Is_Letter (C : in Wide_Wide_Character) return Boolean is begin return C > ' ' and C /= ':' and C /= '>' and C /= ''' and C /= '"' and C /= '/' and C /= '=' and C /= '<'; end Is_Letter; -- ------------------------------ -- Parse an HTML attribute -- ------------------------------ procedure Parse_Attribute_Name (P : in out Parser; Name : in out Unbounded_Wide_Wide_String) is C : Wide_Wide_Character; begin Name := To_Unbounded_Wide_Wide_String (""); Skip_Spaces (P); while not P.Is_Eof loop Peek (P, C); if not Is_Letter (C) then Put_Back (P, C); return; end if; Ada.Strings.Wide_Wide_Unbounded.Append (Name, C); end loop; end Parse_Attribute_Name; procedure Collect_Attribute_Value (P : in out Parser; Value : in out Unbounded_Wide_Wide_String) is C : Wide_Wide_Character; Token : Wide_Wide_Character; begin Value := To_Unbounded_Wide_Wide_String (""); Peek (P, Token); if Wiki.Helpers.Is_Space (Token) then return; elsif Token = '>' then Put_Back (P, Token); return; elsif Token /= ''' and Token /= '"' then Append (Value, Token); while not P.Is_Eof loop Peek (P, C); if C = ''' or C = '"' or C = ' ' or C = '=' or C = '>' or C = '<' or C = '`' then Put_Back (P, C); return; end if; Append (Value, C); end loop; else while not P.Is_Eof loop Peek (P, C); if C = Token then return; end if; Append (Value, C); end loop; end if; end Collect_Attribute_Value; -- ------------------------------ -- Parse a list of HTML attributes up to the first '>'. -- attr-name -- attr-name= -- attr-name=value -- attr-name='value' -- attr-name="value" -- <name name='value' ...> -- ------------------------------ procedure Collect_Attributes (P : in out Parser) is C : Wide_Wide_Character; Name : Unbounded_Wide_Wide_String; Value : Unbounded_Wide_Wide_String; begin Wiki.Attributes.Clear (P.Attributes); while not P.Is_Eof loop Parse_Attribute_Name (P, Name); Skip_Spaces (P); Peek (P, C); if C = '>' or C = '<' or C = '/' then Put_Back (P, C); exit; end if; if C = '=' then Collect_Attribute_Value (P, Value); Attributes.Append (P.Attributes, Name, Value); elsif Wiki.Helpers.Is_Space (C) and Length (Name) > 0 then Attributes.Append (P.Attributes, Name, Null_Unbounded_Wide_Wide_String); end if; end loop; -- Peek (P, C); -- Add any pending attribute. if Length (Name) > 0 then Attributes.Append (P.Attributes, Name, Null_Unbounded_Wide_Wide_String); end if; end Collect_Attributes; -- ------------------------------ -- Parse a HTML/XML comment to strip it. -- ------------------------------ procedure Parse_Comment (P : in out Parser) is C : Wide_Wide_Character; begin Peek (P, C); while not P.Is_Eof loop Peek (P, C); if C = '-' then declare Count : Natural := 1; begin Peek (P, C); while not P.Is_Eof and C = '-' loop Peek (P, C); Count := Count + 1; end loop; exit when C = '>' and Count >= 2; end; end if; end loop; end Parse_Comment; -- ------------------------------ -- Parse a simple DOCTYPE declaration and ignore it. -- ------------------------------ procedure Parse_Doctype (P : in out Parser) is C : Wide_Wide_Character; begin while not P.Is_Eof loop Peek (P, C); exit when C = '>'; end loop; end Parse_Doctype; -- ------------------------------ -- Parse a HTML element <XXX attributes> -- or parse an end of HTML element </XXX> -- ------------------------------ procedure Parse_Element (P : in out Parser) is Name : Unbounded_Wide_Wide_String; C : Wide_Wide_Character; Tag : Wiki.Nodes.Html_Tag_Type; begin Peek (P, C); if C = '!' then Peek (P, C); if C = '-' then Parse_Comment (P); else Parse_Doctype (P); end if; return; end if; if C /= '/' then Put_Back (P, C); end if; Parse_Attribute_Name (P, Name); Tag := Wiki.Nodes.Find_Tag (To_Wide_Wide_String (Name)); if C = '/' then Skip_Spaces (P); Peek (P, C); if C /= '>' then Put_Back (P, C); end if; Flush_Text (P); End_Element (P, Tag); else Collect_Attributes (P); Peek (P, C); if C = '/' then Peek (P, C); if C = '>' then Start_Element (P, Tag, P.Attributes); End_Element (P, Tag); return; end if; elsif C /= '>' then Put_Back (P, C); end if; Start_Element (P, Tag, P.Attributes); end if; end Parse_Element; -- ------------------------------ -- Parse an HTML entity such as &nbsp; and replace it with the corresponding code. -- ------------------------------ procedure Parse_Entity (P : in out Parser; Token : in Wide_Wide_Character) is pragma Unreferenced (Token); Name : String (1 .. 10); Len : Natural := 0; High : Natural := Wiki.Parsers.Html.Entities.Keywords'Last; Low : Natural := Wiki.Parsers.Html.Entities.Keywords'First; Pos : Natural; C : Wide_Wide_Character; begin while Len < Name'Last loop Peek (P, C); exit when C = ';' or else P.Is_Eof; Len := Len + 1; Name (Len) := Ada.Characters.Conversions.To_Character (C); end loop; while Low <= High loop Pos := (Low + High) / 2; if Wiki.Parsers.Html.Entities.Keywords (Pos).all = Name (1 .. Len) then Parse_Text (P, Entities.Mapping (Pos)); return; elsif Entities.Keywords (Pos).all < Name (1 .. Len) then Low := Pos + 1; else High := Pos - 1; end if; end loop; -- The HTML entity is not recognized: we must treat it as plain wiki text. Parse_Text (P, '&'); for I in 1 .. Len loop Parse_Text (P, Ada.Characters.Conversions.To_Wide_Wide_Character (Name (I))); end loop; end Parse_Entity; end Wiki.Parsers.Html;
----------------------------------------------------------------------- -- wiki-parsers-html -- Wiki HTML parser -- Copyright (C) 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.Characters.Conversions; with Ada.Strings.Wide_Wide_Unbounded; with Wiki.Helpers; with Wiki.Parsers.Html.Entities; package body Wiki.Parsers.Html is use Ada.Strings.Wide_Wide_Unbounded; -- Parse an HTML attribute procedure Parse_Attribute_Name (P : in out Parser; Name : in out Unbounded_Wide_Wide_String); -- Parse a HTML/XML comment to strip it. procedure Parse_Comment (P : in out Parser); -- Parse a simple DOCTYPE declaration and ignore it. procedure Parse_Doctype (P : in out Parser); procedure Collect_Attributes (P : in out Parser); function Is_Letter (C : in Wide_Wide_Character) return Boolean; procedure Collect_Attribute_Value (P : in out Parser; Value : in out Unbounded_Wide_Wide_String); function Is_Letter (C : in Wide_Wide_Character) return Boolean is begin return C > ' ' and C /= ':' and C /= '>' and C /= ''' and C /= '"' and C /= '/' and C /= '=' and C /= '<'; end Is_Letter; -- ------------------------------ -- Parse an HTML attribute -- ------------------------------ procedure Parse_Attribute_Name (P : in out Parser; Name : in out Unbounded_Wide_Wide_String) is C : Wide_Wide_Character; begin Name := To_Unbounded_Wide_Wide_String (""); Skip_Spaces (P); while not P.Is_Eof loop Peek (P, C); if not Is_Letter (C) then Put_Back (P, C); return; end if; Ada.Strings.Wide_Wide_Unbounded.Append (Name, C); end loop; end Parse_Attribute_Name; procedure Collect_Attribute_Value (P : in out Parser; Value : in out Unbounded_Wide_Wide_String) is C : Wide_Wide_Character; Token : Wide_Wide_Character; begin Value := To_Unbounded_Wide_Wide_String (""); Peek (P, Token); if Wiki.Helpers.Is_Space (Token) then return; elsif Token = '>' then Put_Back (P, Token); return; elsif Token /= ''' and Token /= '"' then Append (Value, Token); while not P.Is_Eof loop Peek (P, C); if C = ''' or C = '"' or C = ' ' or C = '=' or C = '>' or C = '<' or C = '`' then Put_Back (P, C); return; end if; Append (Value, C); end loop; else while not P.Is_Eof loop Peek (P, C); if C = Token then return; end if; Append (Value, C); end loop; end if; end Collect_Attribute_Value; -- ------------------------------ -- Parse a list of HTML attributes up to the first '>'. -- attr-name -- attr-name= -- attr-name=value -- attr-name='value' -- attr-name="value" -- <name name='value' ...> -- ------------------------------ procedure Collect_Attributes (P : in out Parser) is C : Wide_Wide_Character; Name : Unbounded_Wide_Wide_String; Value : Unbounded_Wide_Wide_String; begin Wiki.Attributes.Clear (P.Attributes); while not P.Is_Eof loop Parse_Attribute_Name (P, Name); Skip_Spaces (P); Peek (P, C); if C = '>' or C = '<' or C = '/' then Put_Back (P, C); exit; end if; if C = '=' then Collect_Attribute_Value (P, Value); Attributes.Append (P.Attributes, Name, Value); elsif Wiki.Helpers.Is_Space (C) and Length (Name) > 0 then Attributes.Append (P.Attributes, Name, Null_Unbounded_Wide_Wide_String); end if; end loop; -- Peek (P, C); -- Add any pending attribute. if Length (Name) > 0 then Attributes.Append (P.Attributes, Name, Null_Unbounded_Wide_Wide_String); end if; end Collect_Attributes; -- ------------------------------ -- Parse a HTML/XML comment to strip it. -- ------------------------------ procedure Parse_Comment (P : in out Parser) is C : Wide_Wide_Character; begin Peek (P, C); while not P.Is_Eof loop Peek (P, C); if C = '-' then declare Count : Natural := 1; begin Peek (P, C); while not P.Is_Eof and C = '-' loop Peek (P, C); Count := Count + 1; end loop; exit when C = '>' and Count >= 2; end; end if; end loop; end Parse_Comment; -- ------------------------------ -- Parse a simple DOCTYPE declaration and ignore it. -- ------------------------------ procedure Parse_Doctype (P : in out Parser) is C : Wide_Wide_Character; begin while not P.Is_Eof loop Peek (P, C); exit when C = '>'; end loop; end Parse_Doctype; -- ------------------------------ -- Parse a HTML element <XXX attributes> -- or parse an end of HTML element </XXX> -- ------------------------------ procedure Parse_Element (P : in out Parser) is Name : Unbounded_Wide_Wide_String; C : Wide_Wide_Character; Tag : Wiki.Nodes.Html_Tag_Type; begin Peek (P, C); if C = '!' then Peek (P, C); if C = '-' then Parse_Comment (P); else Parse_Doctype (P); end if; return; end if; if C /= '/' then Put_Back (P, C); end if; Parse_Attribute_Name (P, Name); Tag := Wiki.Nodes.Find_Tag (To_Wide_Wide_String (Name)); if C = '/' then Skip_Spaces (P); Peek (P, C); if C /= '>' then Put_Back (P, C); end if; Flush_Text (P); End_Element (P, Tag); else Collect_Attributes (P); Peek (P, C); if C = '/' then Peek (P, C); if C = '>' then Start_Element (P, Tag, P.Attributes); End_Element (P, Tag); return; end if; elsif C /= '>' then Put_Back (P, C); end if; Start_Element (P, Tag, P.Attributes); end if; end Parse_Element; -- ------------------------------ -- Parse an HTML entity such as &nbsp; and replace it with the corresponding code. -- ------------------------------ procedure Parse_Entity (P : in out Parser; Token : in Wide_Wide_Character) is pragma Unreferenced (Token); Name : String (1 .. 10); Len : Natural := 0; High : Natural := Wiki.Parsers.Html.Entities.Keywords'Last; Low : Natural := Wiki.Parsers.Html.Entities.Keywords'First; Pos : Natural; C : Wide_Wide_Character; begin while Len < Name'Last loop Peek (P, C); exit when C = ';' or else P.Is_Eof; Len := Len + 1; Name (Len) := Ada.Characters.Conversions.To_Character (C); end loop; while Low <= High loop Pos := (Low + High) / 2; if Wiki.Parsers.Html.Entities.Keywords (Pos).all = Name (1 .. Len) then Parse_Text (P, Entities.Mapping (Pos)); return; elsif Entities.Keywords (Pos).all < Name (1 .. Len) then Low := Pos + 1; else High := Pos - 1; end if; end loop; -- The HTML entity is not recognized: we must treat it as plain wiki text. Parse_Text (P, '&'); for I in 1 .. Len loop Parse_Text (P, Ada.Characters.Conversions.To_Wide_Wide_Character (Name (I))); end loop; end Parse_Entity; end Wiki.Parsers.Html;
Fix compilation
Fix compilation
Ada
apache-2.0
stcarrez/ada-wiki,stcarrez/ada-wiki
b6215c8859a328066ff696c978aaeae1abd2aba1
regtests/util-streams-buffered-lzma-tests.ads
regtests/util-streams-buffered-lzma-tests.ads
----------------------------------------------------------------------- -- util-streams-buffered-lzma-tests -- Unit tests for LZMA buffered 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.Tests; package Util.Streams.Buffered.Lzma.Tests is procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite); type Test is new Util.Tests.Test with null record; procedure Test_Compress_Stream (T : in out Test); end Util.Streams.Buffered.Lzma.Tests;
----------------------------------------------------------------------- -- util-streams-buffered-lzma-tests -- Unit tests for LZMA buffered 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.Tests; package Util.Streams.Buffered.Lzma.Tests is procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite); type Test is new Util.Tests.Test with null record; procedure Test_Compress_Stream (T : in out Test); procedure Test_Compress_File_Stream (T : in out Test); end Util.Streams.Buffered.Lzma.Tests;
Declare the Test_Compress_File_Stream procedure
Declare the Test_Compress_File_Stream procedure
Ada
apache-2.0
stcarrez/ada-util,stcarrez/ada-util
a28691a85794a41c245a77ffcc81b25925ff58e5
matp/src/mat-readers-streams-files.adb
matp/src/mat-readers-streams-files.adb
----------------------------------------------------------------------- -- mat-readers-files -- Reader for files -- 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.Streams.Stream_IO; with Util.Log.Loggers; package body MAT.Readers.Streams.Files is -- The logger Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("MAT.Readers.Files"); BUFFER_SIZE : constant Natural := 100 * 1024; -- ------------------------------ -- Open the file. -- ------------------------------ procedure Open (Reader : in out File_Reader_Type; Path : in String) is begin Log.Info ("Reading data stream {0}", Path); Reader.Stream.Initialize (Size => BUFFER_SIZE, Input => Reader.File'Unchecked_Access, Output => null); Reader.File.Open (Mode => Ada.Streams.Stream_IO.In_File, Name => Path); end Open; end MAT.Readers.Streams.Files;
----------------------------------------------------------------------- -- mat-readers-files -- Reader for files -- 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 Ada.Streams.Stream_IO; with Util.Log.Loggers; package body MAT.Readers.Streams.Files is -- The logger Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("MAT.Readers.Files"); BUFFER_SIZE : constant Natural := 100 * 1024; -- ------------------------------ -- Open the file. -- ------------------------------ procedure Open (Reader : in out File_Reader_Type; Path : in String) is Stream : constant access Util.Streams.Input_Stream'Class := Reader.File'Access; begin Log.Info ("Reading data stream {0}", Path); Reader.Stream.Initialize (Size => BUFFER_SIZE, Input => Stream); Reader.File.Open (Mode => Ada.Streams.Stream_IO.In_File, Name => Path); end Open; end MAT.Readers.Streams.Files;
Fix initialization of file stream
Fix initialization of file stream
Ada
apache-2.0
stcarrez/mat,stcarrez/mat,stcarrez/mat
9b254412e9307077855a9b438d86a9dda35c5b78
src/util-streams-pipes.adb
src/util-streams-pipes.adb
----------------------------------------------------------------------- -- util-streams-raw -- Raw streams for Unix based systems -- Copyright (C) 2011, 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.IO_Exceptions; package body Util.Streams.Pipes is -- ----------------------- -- Set the shell executable path to use to launch a command. The default on Unix is -- the /bin/sh command. Argument splitting is done by the /bin/sh -c command. -- When setting an empty shell command, the argument splitting is done by the -- <tt>Spawn</tt> procedure. -- ----------------------- procedure Set_Shell (Stream : in out Pipe_Stream; Shell : in String) is begin Util.Processes.Set_Shell (Stream.Proc, Shell); end Set_Shell; -- ----------------------- -- Before launching the process, redirect the input stream of the process -- to the specified file. -- Raises <b>Invalid_State</b> if the process is running. -- ----------------------- procedure Set_Input_Stream (Stream : in out Pipe_Stream; File : in String) is begin Util.Processes.Set_Input_Stream (Stream.Proc, File); end Set_Input_Stream; -- ----------------------- -- Set the output stream of the process. -- Raises <b>Invalid_State</b> if the process is running. -- ----------------------- procedure Set_Output_Stream (Stream : in out Pipe_Stream; File : in String; Append : in Boolean := False) is begin Util.Processes.Set_Output_Stream (Stream.Proc, File, Append); end Set_Output_Stream; -- ----------------------- -- Set the error stream of the process. -- Raises <b>Invalid_State</b> if the process is running. -- ----------------------- procedure Set_Error_Stream (Stream : in out Pipe_Stream; File : in String; Append : in Boolean := False) is begin Util.Processes.Set_Error_Stream (Stream.Proc, File, Append); end Set_Error_Stream; -- ----------------------- -- Set the working directory that the process will use once it is created. -- The directory must exist or the <b>Invalid_Directory</b> exception will be raised. -- ----------------------- procedure Set_Working_Directory (Stream : in out Pipe_Stream; Path : in String) is begin Util.Processes.Set_Working_Directory (Stream.Proc, Path); end Set_Working_Directory; -- ----------------------- -- Open a pipe to read or write to an external process. The pipe is created and the -- command is executed with the input and output streams redirected through the pipe. -- ----------------------- procedure Open (Stream : in out Pipe_Stream; Command : in String; Mode : in Pipe_Mode := READ) is begin Util.Processes.Spawn (Stream.Proc, Command, Mode); end Open; -- ----------------------- -- Close the pipe and wait for the external process to terminate. -- ----------------------- overriding procedure Close (Stream : in out Pipe_Stream) is begin Util.Processes.Wait (Stream.Proc); end Close; -- ----------------------- -- Get the process exit status. -- ----------------------- function Get_Exit_Status (Stream : in Pipe_Stream) return Integer is begin return Util.Processes.Get_Exit_Status (Stream.Proc); end Get_Exit_Status; -- ----------------------- -- Returns True if the process is running. -- ----------------------- function Is_Running (Stream : in Pipe_Stream) return Boolean is begin return Util.Processes.Is_Running (Stream.Proc); end Is_Running; -- ----------------------- -- Write the buffer array to the output stream. -- ----------------------- overriding procedure Write (Stream : in out Pipe_Stream; Buffer : in Ada.Streams.Stream_Element_Array) is Output : constant Streams.Output_Stream_Access := Processes.Get_Input_Stream (Stream.Proc); begin if Output = null then raise Ada.IO_Exceptions.Status_Error with "Process is not launched"; end if; Output.Write (Buffer); end Write; -- ----------------------- -- Read into the buffer as many bytes as possible and return in -- <b>last</b> the position of the last byte read. -- ----------------------- overriding procedure Read (Stream : in out Pipe_Stream; Into : out Ada.Streams.Stream_Element_Array; Last : out Ada.Streams.Stream_Element_Offset) is Input : constant Streams.Input_Stream_Access := Processes.Get_Output_Stream (Stream.Proc); begin if Input = null then raise Ada.IO_Exceptions.Status_Error with "Process is not launched"; end if; Input.Read (Into, Last); end Read; -- ----------------------- -- Flush the stream and release the buffer. -- ----------------------- overriding procedure Finalize (Object : in out Pipe_Stream) is begin null; end Finalize; end Util.Streams.Pipes;
----------------------------------------------------------------------- -- util-streams-raw -- Raw streams for Unix based systems -- Copyright (C) 2011, 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.IO_Exceptions; package body Util.Streams.Pipes is -- ----------------------- -- Set the shell executable path to use to launch a command. The default on Unix is -- the /bin/sh command. Argument splitting is done by the /bin/sh -c command. -- When setting an empty shell command, the argument splitting is done by the -- <tt>Spawn</tt> procedure. -- ----------------------- procedure Set_Shell (Stream : in out Pipe_Stream; Shell : in String) is begin Util.Processes.Set_Shell (Stream.Proc, Shell); end Set_Shell; -- ----------------------- -- Before launching the process, redirect the input stream of the process -- to the specified file. -- Raises <b>Invalid_State</b> if the process is running. -- ----------------------- procedure Set_Input_Stream (Stream : in out Pipe_Stream; File : in String) is begin Util.Processes.Set_Input_Stream (Stream.Proc, File); end Set_Input_Stream; -- ----------------------- -- Set the output stream of the process. -- Raises <b>Invalid_State</b> if the process is running. -- ----------------------- procedure Set_Output_Stream (Stream : in out Pipe_Stream; File : in String; Append : in Boolean := False) is begin Util.Processes.Set_Output_Stream (Stream.Proc, File, Append); end Set_Output_Stream; -- ----------------------- -- Set the error stream of the process. -- Raises <b>Invalid_State</b> if the process is running. -- ----------------------- procedure Set_Error_Stream (Stream : in out Pipe_Stream; File : in String; Append : in Boolean := False) is begin Util.Processes.Set_Error_Stream (Stream.Proc, File, Append); end Set_Error_Stream; -- ----------------------- -- Closes the given file descriptor in the child process before executing the command. -- ----------------------- procedure Add_Close (Stream : in out Pipe_Stream; Fd : in Util.Processes.File_Type) is begin Util.Processes.Add_Close (Stream.Proc, Fd); end Add_Close; -- ----------------------- -- Set the working directory that the process will use once it is created. -- The directory must exist or the <b>Invalid_Directory</b> exception will be raised. -- ----------------------- procedure Set_Working_Directory (Stream : in out Pipe_Stream; Path : in String) is begin Util.Processes.Set_Working_Directory (Stream.Proc, Path); end Set_Working_Directory; -- ----------------------- -- Open a pipe to read or write to an external process. The pipe is created and the -- command is executed with the input and output streams redirected through the pipe. -- ----------------------- procedure Open (Stream : in out Pipe_Stream; Command : in String; Mode : in Pipe_Mode := READ) is begin Util.Processes.Spawn (Stream.Proc, Command, Mode); end Open; -- ----------------------- -- Close the pipe and wait for the external process to terminate. -- ----------------------- overriding procedure Close (Stream : in out Pipe_Stream) is begin Util.Processes.Wait (Stream.Proc); end Close; -- ----------------------- -- Get the process exit status. -- ----------------------- function Get_Exit_Status (Stream : in Pipe_Stream) return Integer is begin return Util.Processes.Get_Exit_Status (Stream.Proc); end Get_Exit_Status; -- ----------------------- -- Returns True if the process is running. -- ----------------------- function Is_Running (Stream : in Pipe_Stream) return Boolean is begin return Util.Processes.Is_Running (Stream.Proc); end Is_Running; -- ----------------------- -- Write the buffer array to the output stream. -- ----------------------- overriding procedure Write (Stream : in out Pipe_Stream; Buffer : in Ada.Streams.Stream_Element_Array) is Output : constant Streams.Output_Stream_Access := Processes.Get_Input_Stream (Stream.Proc); begin if Output = null then raise Ada.IO_Exceptions.Status_Error with "Process is not launched"; end if; Output.Write (Buffer); end Write; -- ----------------------- -- Read into the buffer as many bytes as possible and return in -- <b>last</b> the position of the last byte read. -- ----------------------- overriding procedure Read (Stream : in out Pipe_Stream; Into : out Ada.Streams.Stream_Element_Array; Last : out Ada.Streams.Stream_Element_Offset) is Input : constant Streams.Input_Stream_Access := Processes.Get_Output_Stream (Stream.Proc); begin if Input = null then raise Ada.IO_Exceptions.Status_Error with "Process is not launched"; end if; Input.Read (Into, Last); end Read; -- ----------------------- -- Flush the stream and release the buffer. -- ----------------------- overriding procedure Finalize (Object : in out Pipe_Stream) is begin null; end Finalize; end Util.Streams.Pipes;
Implement the Add_Close procedure
Implement the Add_Close procedure
Ada
apache-2.0
stcarrez/ada-util,stcarrez/ada-util
96c066794db14110590d4d275570535b429ab867
mat/src/mat-readers-marshaller.adb
mat/src/mat-readers-marshaller.adb
----------------------------------------------------------------------- -- Ipc -- Ipc channel between profiler tool and application -- -- 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; use System; with System.Address_To_Access_Conversions; with System.Storage_Elements; with MAT.Types; with Interfaces; use Interfaces; package body MAT.Readers.Marshaller is use System.Storage_Elements; package Uint8_Access is new System.Address_To_Access_Conversions (MAT.Types.Uint8); package Uint32_Access is new System.Address_To_Access_Conversions (MAT.Types.Uint32); function Get_Raw_Uint32 (Buf : System.Address) return MAT.Types.Uint32 is use Uint32_Access; P : Object_Pointer := To_Pointer (Buf); begin return P.all; end Get_Raw_Uint32; function Get_Uint8 (Buffer : in Buffer_Ptr) return MAT.Types.Uint8 is use Uint8_Access; P : Object_Pointer := To_Pointer (Buffer.Current); begin if Buffer.Size = 0 then raise Buffer_Underflow_Error; end if; Buffer.Size := Buffer.Size - 1; Buffer.Current := Buffer.Current + Storage_Offset (1); return P.all; end Get_Uint8; function Get_Uint16 (Buffer : in Buffer_Ptr) return MAT.Types.Uint16 is use Uint8_Access; High : Object_Pointer := To_Pointer (Buffer.Current + Storage_Offset (1)); Low : Object_Pointer := To_Pointer (Buffer.Current); begin if Buffer.Size <= 1 then raise Buffer_Underflow_Error; end if; Buffer.Size := Buffer.Size - 2; Buffer.Current := Buffer.Current + Storage_Offset (2); return MAT.Types.Uint16 (High.all) * 256 + MAT.Types.Uint16 (Low.all); end Get_Uint16; function Get_Uint32 (Buffer : in Buffer_Ptr) return MAT.Types.Uint32 is use Uint32_Access; P : Object_Pointer := To_Pointer (Buffer.Current); begin if Buffer.Size < 4 then raise Buffer_Underflow_Error; end if; Buffer.Size := Buffer.Size - 4; Buffer.Current := Buffer.Current + Storage_Offset (4); if Buffer.Current >= Buffer.Last then Buffer.Current := Buffer.Start; end if; return P.all; end Get_Uint32; function Get_Uint64 (Buffer : in Buffer_Ptr) return MAT.Types.Uint64 is Val : MAT.Types.Uint64 := MAT.Types.Uint64 (Get_Uint32 (Buffer)); begin return Val + MAT.Types.Uint64 (Get_Uint32 (Buffer)) * 2**32; end Get_Uint64; function Get_Target_Value (Msg : in Buffer_Ptr; Kind : in MAT.Events.Attribute_Type) return Target_Type is begin case Kind is when MAT.Events.T_UINT8 => return Target_Type (Get_Uint8 (Msg)); when MAT.Events.T_UINT16 => return Target_Type (Get_Uint16 (Msg)); when MAT.Events.T_UINT32 => return Target_Type (Get_Uint32 (Msg)); when MAT.Events.T_UINT64 => return Target_Type (Get_Uint64 (Msg)); when others => pragma Assert (False, "Invalid attribute type "); return 0; end case; end Get_Target_Value; -- ------------------------------ -- 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 is Len : constant MAT.Types.Uint8 := Get_Uint8 (Buffer); Result : String (1 .. Natural (Len)); begin for I in Result'Range loop Result (I) := Character'Val (Get_Uint8 (Buffer)); end loop; return Result; end Get_String; -- ------------------------------ -- Skip the given number of bytes from the message. -- ------------------------------ procedure Skip (Buffer : in Buffer_Ptr; Size : in Natural) is begin Buffer.Size := Buffer.Size - Size; Buffer.Current := Buffer.Current + Storage_Offset (Size); end Skip; end MAT.Readers.Marshaller;
----------------------------------------------------------------------- -- Ipc -- Ipc channel between profiler tool and application -- -- 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; use System; with System.Address_To_Access_Conversions; with System.Storage_Elements; with MAT.Types; with Util.Log.Loggers; with Interfaces; use Interfaces; package body MAT.Readers.Marshaller is use System.Storage_Elements; -- The logger Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("MAT.Readers.Marshaller"); package Uint8_Access is new System.Address_To_Access_Conversions (MAT.Types.Uint8); package Uint32_Access is new System.Address_To_Access_Conversions (MAT.Types.Uint32); function Get_Raw_Uint32 (Buf : System.Address) return MAT.Types.Uint32 is use Uint32_Access; P : Object_Pointer := To_Pointer (Buf); begin return P.all; end Get_Raw_Uint32; function Get_Uint8 (Buffer : in Buffer_Ptr) return MAT.Types.Uint8 is use Uint8_Access; P : Object_Pointer := To_Pointer (Buffer.Current); begin if Buffer.Size = 0 then Log.Error ("Not enough data to get a uint8"); raise Buffer_Underflow_Error; end if; Buffer.Size := Buffer.Size - 1; Buffer.Current := Buffer.Current + Storage_Offset (1); return P.all; end Get_Uint8; function Get_Uint16 (Buffer : in Buffer_Ptr) return MAT.Types.Uint16 is use Uint8_Access; High : Object_Pointer := To_Pointer (Buffer.Current + Storage_Offset (1)); Low : Object_Pointer := To_Pointer (Buffer.Current); begin if Buffer.Size <= 1 then Log.Error ("Not enough data to get a uint16"); raise Buffer_Underflow_Error; end if; Buffer.Size := Buffer.Size - 2; Buffer.Current := Buffer.Current + Storage_Offset (2); return MAT.Types.Uint16 (High.all) * 256 + MAT.Types.Uint16 (Low.all); end Get_Uint16; function Get_Uint32 (Buffer : in Buffer_Ptr) return MAT.Types.Uint32 is use Uint32_Access; P : Object_Pointer := To_Pointer (Buffer.Current); begin if Buffer.Size < 4 then Log.Error ("Not enough data to get a uint32"); raise Buffer_Underflow_Error; end if; Buffer.Size := Buffer.Size - 4; Buffer.Current := Buffer.Current + Storage_Offset (4); if Buffer.Current >= Buffer.Last then Buffer.Current := Buffer.Start; end if; return P.all; end Get_Uint32; function Get_Uint64 (Buffer : in Buffer_Ptr) return MAT.Types.Uint64 is Val : MAT.Types.Uint64 := MAT.Types.Uint64 (Get_Uint32 (Buffer)); begin return Val + MAT.Types.Uint64 (Get_Uint32 (Buffer)) * 2**32; end Get_Uint64; function Get_Target_Value (Msg : in Buffer_Ptr; Kind : in MAT.Events.Attribute_Type) return Target_Type is begin case Kind is when MAT.Events.T_UINT8 => return Target_Type (Get_Uint8 (Msg)); when MAT.Events.T_UINT16 => return Target_Type (Get_Uint16 (Msg)); when MAT.Events.T_UINT32 => return Target_Type (Get_Uint32 (Msg)); when MAT.Events.T_UINT64 => return Target_Type (Get_Uint64 (Msg)); when others => Log.Error ("Invalid attribute type {0}", MAT.EVents.Attribute_Type'Image (Kind)); return 0; end case; end Get_Target_Value; -- ------------------------------ -- 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 is Len : constant MAT.Types.Uint8 := Get_Uint8 (Buffer); Result : String (1 .. Natural (Len)); begin for I in Result'Range loop Result (I) := Character'Val (Get_Uint8 (Buffer)); end loop; return Result; end Get_String; -- ------------------------------ -- Skip the given number of bytes from the message. -- ------------------------------ procedure Skip (Buffer : in Buffer_Ptr; Size : in Natural) is begin Buffer.Size := Buffer.Size - Size; Buffer.Current := Buffer.Current + Storage_Offset (Size); end Skip; end MAT.Readers.Marshaller;
Add some log error message if there is not enough data in the buffer
Add some log error message if there is not enough data in the buffer
Ada
apache-2.0
stcarrez/mat,stcarrez/mat,stcarrez/mat
bd84b99fad869375b7344d862ec806e246d44a74
regtests/ado-objects-tests.adb
regtests/ado-objects-tests.adb
----------------------------------------------------------------------- -- ADO Objects Tests -- Tests for ADO.Objects -- Copyright (C) 2011, 2012, 2013, 2014, 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 ADO.Sessions; with Regtests.Simple.Model; with Regtests.Comments; with Regtests.Statements.Model; package body ADO.Objects.Tests is use Util.Tests; use type Ada.Containers.Hash_Type; -- Test the Set_xxx and Get_xxx operation on various simple times. generic Name : String; type Element_Type (<>) is private; with function "=" (Left, Right : in Element_Type) return Boolean is <>; with procedure Set_Value (Item : in out Regtests.Statements.Model.Nullable_Table_Ref; Val : in Element_Type); with function Get_Value (Item : in Regtests.Statements.Model.Nullable_Table_Ref) return Element_Type; Val1 : Element_Type; Val2 : Element_Type; procedure Test_Op (T : in out Test); procedure Test_Op (T : in out Test) is Item1 : Regtests.Statements.Model.Nullable_Table_Ref; Item2 : Regtests.Statements.Model.Nullable_Table_Ref; Item3 : Regtests.Statements.Model.Nullable_Table_Ref; DB : ADO.Sessions.Master_Session := Regtests.Get_Master_Database; begin Set_Value (Item1, Val1); Item1.Save (DB); T.Assert (Item1.Is_Inserted, Name & " item is created"); -- Util.Tests.Assert_Equals (T, T'Image (Val), T'Image ( -- Load in a second item and check the value. Item2.Load (DB, Item1.Get_Id); T.Assert (Item2.Get_Id = Item1.Get_Id, Name & " item2 cannot be loaded"); -- T.Assert (Get_Value (Item2) = Val1, Name & " invalid value loaded in item2"); -- Change the item in database. Set_Value (Item2, Val2); Item2.Save (DB); T.Assert (Get_Value (Item2) = Val2, Name & " invalid value loaded in item2"); -- Load again and compare to check the update. Item3.Load (DB, Item2.Get_Id); T.Assert (Get_Value (Item3) = Val2, Name & " invalid value loaded in item3"); end Test_Op; procedure Test_Object_Nullable_Integer is new Test_Op ("Nullable_Integer", Nullable_Integer, "=", Regtests.Statements.Model.Set_Int_Value, Regtests.Statements.Model.Get_Int_Value, Nullable_Integer '(Value => 123, Is_Null => False), Nullable_Integer '(Value => 0, Is_Null => True)); procedure Test_Object_Nullable_Entity_Type is new Test_Op ("Nullable_Entity_Type", Nullable_Entity_Type, "=", Regtests.Statements.Model.Set_Entity_Value, Regtests.Statements.Model.Get_Entity_Value, Nullable_Entity_Type '(Value => 456, Is_Null => False), Nullable_Entity_Type '(Value => 0, Is_Null => True)); procedure Test_Object_Nullable_Time is new Test_Op ("Nullable_Time", Nullable_Time, "=", Regtests.Statements.Model.Set_Time_Value, Regtests.Statements.Model.Get_Time_Value, Nullable_Time '(Value => 456, Is_Null => False), Nullable_Time '(Value => <>, Is_Null => True)); function Get_Allocate_Key (N : Identifier) return Object_Key; function Get_Allocate_Key (N : Identifier) return Object_Key is Result : Object_Key (Of_Type => KEY_INTEGER, Of_Class => Regtests.Simple.Model.ALLOCATE_TABLE); begin Set_Value (Result, N); return Result; end Get_Allocate_Key; -- ------------------------------ -- Various tests on Hash and key comparison -- ------------------------------ procedure Test_Key (T : in out Test) is K1 : constant Object_Key := Get_Allocate_Key (1); K2 : Object_Key (Of_Type => KEY_STRING, Of_Class => Regtests.Simple.Model.USER_TABLE); K3 : Object_Key := K1; K4 : Object_Key (Of_Type => KEY_INTEGER, Of_Class => Regtests.Simple.Model.USER_TABLE); begin T.Assert (not (K1 = K2), "Key on different tables must be different"); T.Assert (not (K2 = K4), "Key with different type must be different"); T.Assert (K1 = K3, "Keys are identical"); T.Assert (Equivalent_Elements (K1, K3), "Keys are identical"); T.Assert (Equivalent_Elements (K3, K1), "Keys are identical"); T.Assert (Hash (K1) = Hash (K3), "Hash of identical keys should be identical"); Set_Value (K3, 2); T.Assert (not (K1 = K3), "Keys should be different"); T.Assert (Hash (K1) /= Hash (K3), "Hash should be different"); T.Assert (Hash (K1) /= Hash (K2), "Hash should be different"); Set_Value (K4, 1); T.Assert (Hash (K1) /= Hash (K4), "Hash on key with same value and different tables should be different"); T.Assert (not (K4 = K1), "Key on different tables should be different"); Set_Value (K2, 1); T.Assert (Hash (K1) /= Hash (K2), "Hash should be different"); end Test_Key; -- ------------------------------ -- Check: -- Object_Ref := (reference counting) -- Object_Ref.Copy -- Object_Ref.Get_xxx generated method -- Object_Ref.Set_xxx generated method -- Object_Ref.= -- ------------------------------ procedure Test_Object_Ref (T : in out Test) is use type Regtests.Simple.Model.User_Ref; Obj1 : Regtests.Simple.Model.User_Ref; Null_Obj : Regtests.Simple.Model.User_Ref; begin T.Assert (Obj1 = Null_Obj, "Two null objects are identical"); for I in 1 .. 10 loop Obj1.Set_Name ("User name"); T.Assert (Obj1.Get_Name = "User name", "User_Ref.Set_Name invalid result"); T.Assert (Obj1 /= Null_Obj, "Object is not identical as the null object"); declare Obj2 : constant Regtests.Simple.Model.User_Ref := Obj1; Obj3 : Regtests.Simple.Model.User_Ref; begin Obj1.Copy (Obj3); Obj3.Set_Id (2); -- Check the copy T.Assert (Obj2.Get_Name = "User name", "Object_Ref.Copy invalid copy"); T.Assert (Obj3.Get_Name = "User name", "Object_Ref.Copy invalid copy"); T.Assert (Obj2 = Obj1, "Object_Ref.'=' invalid comparison after assignment"); T.Assert (Obj3 /= Obj1, "Object_Ref.'=' invalid comparison after copy"); -- Change original, make sure it's the same of Obj2. Obj1.Set_Name ("Second name"); T.Assert (Obj2.Get_Name = "Second name", "Object_Ref.Copy invalid copy"); T.Assert (Obj2 = Obj1, "Object_Ref.'=' invalid comparison after assignment"); -- The copy is not modified T.Assert (Obj3.Get_Name = "User name", "Object_Ref.Copy invalid copy"); end; end loop; end Test_Object_Ref; -- ------------------------------ -- Test creation of an object with lazy loading. -- ------------------------------ procedure Test_Create_Object (T : in out Test) is User : Regtests.Simple.Model.User_Ref; Cmt : Regtests.Comments.Comment_Ref; begin -- Create an object within a transaction. declare S : ADO.Sessions.Master_Session := Regtests.Get_Master_Database; begin S.Begin_Transaction; User.Set_Name ("Joe"); User.Set_Value (0); User.Save (S); S.Commit; end; -- Load it from another session. declare S : ADO.Sessions.Master_Session := Regtests.Get_Master_Database; U2 : Regtests.Simple.Model.User_Ref; begin U2.Load (S, User.Get_Id); Assert_Equals (T, "Joe", Ada.Strings.Unbounded.To_String (U2.Get_Name), "Cannot load created object"); Assert_Equals (T, Integer (0), Integer (U2.Get_Value), "Invalid load"); T.Assert (User.Get_Key = U2.Get_Key, "Invalid key after load"); end; -- Create a comment for the user. declare S : ADO.Sessions.Master_Session := Regtests.Get_Master_Database; begin S.Begin_Transaction; Cmt.Set_Message (Ada.Strings.Unbounded.To_Unbounded_String ("A comment from Joe")); Cmt.Set_User (User); Cmt.Set_Entity_Id (2); Cmt.Set_Entity_Type (1); -- Cmt.Set_Date (ADO.DEFAULT_TIME); Cmt.Set_Date (Ada.Calendar.Clock); Cmt.Save (S); S.Commit; end; -- Load that comment. declare S : ADO.Sessions.Master_Session := Regtests.Get_Master_Database; C2 : Regtests.Comments.Comment_Ref; begin T.Assert (not C2.Is_Loaded, "Object is not loaded"); C2.Load (S, Cmt.Get_Id); T.Assert (not C2.Is_Null, "Loading of object failed"); T.Assert (C2.Is_Loaded, "Object is loaded"); T.Assert (Cmt.Get_Key = C2.Get_Key, "Invalid key after load"); T.Assert_Equals ("A comment from Joe", Ada.Strings.Unbounded.To_String (C2.Get_Message), "Invalid message"); T.Assert (not C2.Get_User.Is_Null, "User associated with the comment should not be null"); -- T.Assert (not C2.Get_Entity_Type.Is_Null, "Entity type was not set"); -- Check that we can access the user name (lazy load) Assert_Equals (T, "Joe", Ada.Strings.Unbounded.To_String (C2.Get_User.Get_Name), "Cannot load created object"); end; end Test_Create_Object; -- ------------------------------ -- Test creation and deletion of an object record -- ------------------------------ procedure Test_Delete_Object (T : in out Test) is User : Regtests.Simple.Model.User_Ref; begin -- Create an object within a transaction. declare S : ADO.Sessions.Master_Session := Regtests.Get_Master_Database; begin S.Begin_Transaction; User.Set_Name ("Joe (delete)"); User.Set_Value (0); User.Save (S); S.Commit; end; -- Load it and delete it from another session. declare S : ADO.Sessions.Master_Session := Regtests.Get_Master_Database; U2 : Regtests.Simple.Model.User_Ref; begin U2.Load (S, User.Get_Id); S.Begin_Transaction; U2.Delete (S); S.Commit; end; -- Try to load the deleted object. declare S : ADO.Sessions.Master_Session := Regtests.Get_Master_Database; U2 : Regtests.Simple.Model.User_Ref; begin U2.Load (S, User.Get_Id); T.Assert (False, "Load of a deleted object should raise NOT_FOUND"); exception when ADO.Objects.NOT_FOUND => null; end; end Test_Delete_Object; -- ------------------------------ -- Test Is_Inserted and Is_Null -- ------------------------------ procedure Test_Is_Inserted (T : in out Test) is User : Regtests.Simple.Model.User_Ref; begin T.Assert (not User.Is_Inserted, "A null object should not be marked as INSERTED"); T.Assert (User.Is_Null, "A null object should be marked as NULL"); -- Create an object within a transaction. declare S : ADO.Sessions.Master_Session := Regtests.Get_Master_Database; begin S.Begin_Transaction; User.Set_Name ("John"); T.Assert (not User.Is_Null, "User should not be NULL"); T.Assert (not User.Is_Inserted, "User was not saved and not yet inserted in database"); User.Set_Value (1); User.Save (S); S.Commit; T.Assert (User.Is_Inserted, "After a save operation, the user should be marked INSERTED"); T.Assert (not User.Is_Null, "User should not be NULL"); end; declare S : ADO.Sessions.Master_Session := Regtests.Get_Master_Database; John : Regtests.Simple.Model.User_Ref; begin John.Load (S, User.Get_Id); T.Assert (John.Is_Inserted, "After a load, the object should be marked INSERTED"); T.Assert (not John.Is_Null, "After a load, the object should not be NULL"); end; end Test_Is_Inserted; package Caller is new Util.Test_Caller (Test, "ADO.Objects"); -- ------------------------------ -- Add the tests in the test suite -- ------------------------------ procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is begin Caller.Add_Test (Suite, "Test ADO.Objects.Hash", Test_Key'Access); Caller.Add_Test (Suite, "Test Object_Ref.Get/Set", Test_Object_Ref'Access); Caller.Add_Test (Suite, "Test ADO.Objects.Create", Test_Create_Object'Access); Caller.Add_Test (Suite, "Test ADO.Objects.Delete", Test_Delete_Object'Access); Caller.Add_Test (Suite, "Test ADO.Objects.Is_Created", Test_Is_Inserted'Access); Caller.Add_Test (Suite, "Test ADO.Objects (Nullable_Integer)", Test_Object_Nullable_Integer'Access); Caller.Add_Test (Suite, "Test ADO.Objects (Nullable_Entity_Type)", Test_Object_Nullable_Entity_Type'Access); Caller.Add_Test (Suite, "Test ADO.Objects (Nullable_Time)", Test_Object_Nullable_Time'Access); end Add_Tests; end ADO.Objects.Tests;
----------------------------------------------------------------------- -- ADO Objects Tests -- Tests for ADO.Objects -- Copyright (C) 2011, 2012, 2013, 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 Util.Test_Caller; with ADO.Sessions; with Regtests.Simple.Model; with Regtests.Comments; with Regtests.Statements.Model; package body ADO.Objects.Tests is use Util.Tests; use type Ada.Containers.Hash_Type; -- Test the Set_xxx and Get_xxx operation on various simple times. generic Name : String; type Element_Type (<>) is private; with function "=" (Left, Right : in Element_Type) return Boolean is <>; with procedure Set_Value (Item : in out Regtests.Statements.Model.Nullable_Table_Ref; Val : in Element_Type); with function Get_Value (Item : in Regtests.Statements.Model.Nullable_Table_Ref) return Element_Type; Val1 : Element_Type; Val2 : Element_Type; procedure Test_Op (T : in out Test); procedure Test_Op (T : in out Test) is Item1 : Regtests.Statements.Model.Nullable_Table_Ref; Item2 : Regtests.Statements.Model.Nullable_Table_Ref; Item3 : Regtests.Statements.Model.Nullable_Table_Ref; DB : ADO.Sessions.Master_Session := Regtests.Get_Master_Database; begin Set_Value (Item1, Val1); Item1.Save (DB); T.Assert (Item1.Is_Inserted, Name & " item is created"); -- Util.Tests.Assert_Equals (T, T'Image (Val), T'Image ( -- Load in a second item and check the value. Item2.Load (DB, Item1.Get_Id); T.Assert (Item2.Get_Id = Item1.Get_Id, Name & " item2 cannot be loaded"); -- T.Assert (Get_Value (Item2) = Val1, Name & " invalid value loaded in item2"); -- Change the item in database. Set_Value (Item2, Val2); Item2.Save (DB); T.Assert (Get_Value (Item2) = Val2, Name & " invalid value loaded in item2"); -- Load again and compare to check the update. Item3.Load (DB, Item2.Get_Id); T.Assert (Get_Value (Item3) = Val2, Name & " invalid value loaded in item3"); end Test_Op; procedure Test_Object_Nullable_Integer is new Test_Op ("Nullable_Integer", Nullable_Integer, "=", Regtests.Statements.Model.Set_Int_Value, Regtests.Statements.Model.Get_Int_Value, Nullable_Integer '(Value => 123, Is_Null => False), Nullable_Integer '(Value => 0, Is_Null => True)); procedure Test_Object_Nullable_Entity_Type is new Test_Op ("Nullable_Entity_Type", Nullable_Entity_Type, "=", Regtests.Statements.Model.Set_Entity_Value, Regtests.Statements.Model.Get_Entity_Value, Nullable_Entity_Type '(Value => 456, Is_Null => False), Nullable_Entity_Type '(Value => 0, Is_Null => True)); procedure Test_Object_Nullable_Time is new Test_Op ("Nullable_Time", Nullable_Time, "=", Regtests.Statements.Model.Set_Time_Value, Regtests.Statements.Model.Get_Time_Value, Nullable_Time '(Value => 456, Is_Null => False), Nullable_Time '(Value => <>, Is_Null => True)); function Get_Allocate_Key (N : Identifier) return Object_Key; function Get_Allocate_Key (N : Identifier) return Object_Key is Result : Object_Key (Of_Type => KEY_INTEGER, Of_Class => Regtests.Simple.Model.ALLOCATE_TABLE); begin Set_Value (Result, N); return Result; end Get_Allocate_Key; -- ------------------------------ -- Various tests on Hash and key comparison -- ------------------------------ procedure Test_Key (T : in out Test) is K1 : constant Object_Key := Get_Allocate_Key (1); K2 : Object_Key (Of_Type => KEY_STRING, Of_Class => Regtests.Simple.Model.USER_TABLE); K3 : Object_Key := K1; K4 : Object_Key (Of_Type => KEY_INTEGER, Of_Class => Regtests.Simple.Model.USER_TABLE); begin T.Assert (not (K1 = K2), "Key on different tables must be different"); T.Assert (not (K2 = K4), "Key with different type must be different"); T.Assert (K1 = K3, "Keys are identical"); T.Assert (Equivalent_Elements (K1, K3), "Keys are identical"); T.Assert (Equivalent_Elements (K3, K1), "Keys are identical"); T.Assert (Hash (K1) = Hash (K3), "Hash of identical keys should be identical"); Set_Value (K3, 2); T.Assert (not (K1 = K3), "Keys should be different"); T.Assert (Hash (K1) /= Hash (K3), "Hash should be different"); T.Assert (Hash (K1) /= Hash (K2), "Hash should be different"); Set_Value (K4, 1); T.Assert (Hash (K1) /= Hash (K4), "Hash on key with same value and different tables should be different"); T.Assert (not (K4 = K1), "Key on different tables should be different"); Set_Value (K2, 1); T.Assert (Hash (K1) /= Hash (K2), "Hash should be different"); end Test_Key; -- ------------------------------ -- Check: -- Object_Ref := (reference counting) -- Object_Ref.Copy -- Object_Ref.Get_xxx generated method -- Object_Ref.Set_xxx generated method -- Object_Ref.= -- ------------------------------ procedure Test_Object_Ref (T : in out Test) is use type Regtests.Simple.Model.User_Ref; Obj1 : Regtests.Simple.Model.User_Ref; Null_Obj : Regtests.Simple.Model.User_Ref; begin T.Assert (Obj1 = Null_Obj, "Two null objects are identical"); for I in 1 .. 10 loop Obj1.Set_Name ("User name"); T.Assert (Obj1.Get_Name = "User name", "User_Ref.Set_Name invalid result"); T.Assert (Obj1 /= Null_Obj, "Object is not identical as the null object"); declare Obj2 : constant Regtests.Simple.Model.User_Ref := Obj1; Obj3 : Regtests.Simple.Model.User_Ref; begin Obj1.Copy (Obj3); Obj3.Set_Id (2); -- Check the copy T.Assert (Obj2.Get_Name = "User name", "Object_Ref.Copy invalid copy"); T.Assert (Obj3.Get_Name = "User name", "Object_Ref.Copy invalid copy"); T.Assert (Obj2 = Obj1, "Object_Ref.'=' invalid comparison after assignment"); T.Assert (Obj3 /= Obj1, "Object_Ref.'=' invalid comparison after copy"); -- Change original, make sure it's the same of Obj2. Obj1.Set_Name ("Second name"); T.Assert (Obj2.Get_Name = "Second name", "Object_Ref.Copy invalid copy"); T.Assert (Obj2 = Obj1, "Object_Ref.'=' invalid comparison after assignment"); -- The copy is not modified T.Assert (Obj3.Get_Name = "User name", "Object_Ref.Copy invalid copy"); end; end loop; end Test_Object_Ref; -- ------------------------------ -- Test creation of an object with lazy loading. -- ------------------------------ procedure Test_Create_Object (T : in out Test) is User : Regtests.Simple.Model.User_Ref; Cmt : Regtests.Comments.Comment_Ref; begin -- Create an object within a transaction. declare S : ADO.Sessions.Master_Session := Regtests.Get_Master_Database; begin S.Begin_Transaction; User.Set_Name ("Joe"); User.Set_Value (0); User.Save (S); S.Commit; end; -- Load it from another session. declare S : ADO.Sessions.Master_Session := Regtests.Get_Master_Database; U2 : Regtests.Simple.Model.User_Ref; begin U2.Load (S, User.Get_Id); T.Assert (not U2.Get_Name.Is_Null, "Cannot load created object"); Assert_Equals (T, "Joe", Ada.Strings.Unbounded.To_String (U2.Get_Name.Value), "Cannot load created object"); Assert_Equals (T, Integer (0), Integer (U2.Get_Value), "Invalid load"); T.Assert (User.Get_Key = U2.Get_Key, "Invalid key after load"); end; -- Create a comment for the user. declare S : ADO.Sessions.Master_Session := Regtests.Get_Master_Database; begin S.Begin_Transaction; Cmt.Set_Message (Ada.Strings.Unbounded.To_Unbounded_String ("A comment from Joe")); Cmt.Set_User (User); Cmt.Set_Entity_Id (2); Cmt.Set_Entity_Type (1); -- Cmt.Set_Date (ADO.DEFAULT_TIME); Cmt.Set_Date (Ada.Calendar.Clock); Cmt.Save (S); S.Commit; end; -- Load that comment. declare S : ADO.Sessions.Master_Session := Regtests.Get_Master_Database; C2 : Regtests.Comments.Comment_Ref; begin T.Assert (not C2.Is_Loaded, "Object is not loaded"); C2.Load (S, Cmt.Get_Id); T.Assert (not C2.Is_Null, "Loading of object failed"); T.Assert (C2.Is_Loaded, "Object is loaded"); T.Assert (Cmt.Get_Key = C2.Get_Key, "Invalid key after load"); T.Assert_Equals ("A comment from Joe", Ada.Strings.Unbounded.To_String (C2.Get_Message), "Invalid message"); T.Assert (not C2.Get_User.Is_Null, "User associated with the comment should not be null"); -- T.Assert (not C2.Get_Entity_Type.Is_Null, "Entity type was not set"); -- Check that we can access the user name (lazy load) Assert_Equals (T, "Joe", Ada.Strings.Unbounded.To_String (C2.Get_User.Get_Name.Value), "Cannot load created object"); end; end Test_Create_Object; -- ------------------------------ -- Test creation and deletion of an object record -- ------------------------------ procedure Test_Delete_Object (T : in out Test) is User : Regtests.Simple.Model.User_Ref; begin -- Create an object within a transaction. declare S : ADO.Sessions.Master_Session := Regtests.Get_Master_Database; begin S.Begin_Transaction; User.Set_Name ("Joe (delete)"); User.Set_Value (0); User.Save (S); S.Commit; end; -- Load it and delete it from another session. declare S : ADO.Sessions.Master_Session := Regtests.Get_Master_Database; U2 : Regtests.Simple.Model.User_Ref; begin U2.Load (S, User.Get_Id); S.Begin_Transaction; U2.Delete (S); S.Commit; end; -- Try to load the deleted object. declare S : ADO.Sessions.Master_Session := Regtests.Get_Master_Database; U2 : Regtests.Simple.Model.User_Ref; begin U2.Load (S, User.Get_Id); T.Assert (False, "Load of a deleted object should raise NOT_FOUND"); exception when ADO.Objects.NOT_FOUND => null; end; end Test_Delete_Object; -- ------------------------------ -- Test Is_Inserted and Is_Null -- ------------------------------ procedure Test_Is_Inserted (T : in out Test) is User : Regtests.Simple.Model.User_Ref; begin T.Assert (not User.Is_Inserted, "A null object should not be marked as INSERTED"); T.Assert (User.Is_Null, "A null object should be marked as NULL"); -- Create an object within a transaction. declare S : ADO.Sessions.Master_Session := Regtests.Get_Master_Database; begin S.Begin_Transaction; User.Set_Name ("John"); T.Assert (not User.Is_Null, "User should not be NULL"); T.Assert (not User.Is_Inserted, "User was not saved and not yet inserted in database"); User.Set_Value (1); User.Save (S); S.Commit; T.Assert (User.Is_Inserted, "After a save operation, the user should be marked INSERTED"); T.Assert (not User.Is_Null, "User should not be NULL"); end; declare S : ADO.Sessions.Master_Session := Regtests.Get_Master_Database; John : Regtests.Simple.Model.User_Ref; begin John.Load (S, User.Get_Id); T.Assert (John.Is_Inserted, "After a load, the object should be marked INSERTED"); T.Assert (not John.Is_Null, "After a load, the object should not be NULL"); end; end Test_Is_Inserted; package Caller is new Util.Test_Caller (Test, "ADO.Objects"); -- ------------------------------ -- Add the tests in the test suite -- ------------------------------ procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is begin Caller.Add_Test (Suite, "Test ADO.Objects.Hash", Test_Key'Access); Caller.Add_Test (Suite, "Test Object_Ref.Get/Set", Test_Object_Ref'Access); Caller.Add_Test (Suite, "Test ADO.Objects.Create", Test_Create_Object'Access); Caller.Add_Test (Suite, "Test ADO.Objects.Delete", Test_Delete_Object'Access); Caller.Add_Test (Suite, "Test ADO.Objects.Is_Created", Test_Is_Inserted'Access); Caller.Add_Test (Suite, "Test ADO.Objects (Nullable_Integer)", Test_Object_Nullable_Integer'Access); Caller.Add_Test (Suite, "Test ADO.Objects (Nullable_Entity_Type)", Test_Object_Nullable_Entity_Type'Access); Caller.Add_Test (Suite, "Test ADO.Objects (Nullable_Time)", Test_Object_Nullable_Time'Access); end Add_Tests; end ADO.Objects.Tests;
Update to use Nullable_String type
Update to use Nullable_String type
Ada
apache-2.0
stcarrez/ada-ado
f3ad2c16ec43957606e9937bc02c40d4560ca08a
src/base/log/util-log-loggers.ads
src/base/log/util-log-loggers.ads
----------------------------------------------------------------------- -- util-log-loggers -- Utility Log Package -- Copyright (C) 2006, 2008, 2009, 2011, 2018 Free Software Foundation, Inc. -- 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 Ada.Strings.Unbounded; with Util.Log.Appenders; with Util.Properties; with Ada.Finalization; package Util.Log.Loggers is use Ada.Exceptions; use Ada.Strings.Unbounded; -- The logger identifies and configures the log produced -- by a component that uses it. The logger has a name -- which can be printed in the log outputs. The logger instance -- contains a log level which can be used to control the level of -- logs. type Logger is tagged limited private; type Logger_Access is access constant Logger; -- Create a logger with the given name. function Create (Name : in String) return Logger; -- Create a logger with the given name and use the specified level. function Create (Name : in String; Level : in Level_Type) return Logger; -- Initialize the logger and create a logger with the given name. function Create (Name : in String; Config : in String) return Logger; -- Change the log level procedure Set_Level (Log : in out Logger; Level : in Level_Type); -- Get the log level. function Get_Level (Log : in Logger) return Level_Type; -- Get the log level name. function Get_Level_Name (Log : in Logger) return String; procedure Print (Log : in Logger; Level : in Level_Type; Message : in String; Arg1 : in String := ""; Arg2 : in String := ""; Arg3 : in String := ""; Arg4 : in String := ""); procedure Debug (Log : in Logger'Class; Message : in String; Arg1 : in String := ""; Arg2 : in String := ""; Arg3 : in String := ""); procedure Debug (Log : in Logger'Class; Message : in String; Arg1 : in Unbounded_String; Arg2 : in String := ""; Arg3 : in String := ""); procedure Debug (Log : in Logger'Class; Message : in String; Arg1 : in Unbounded_String; Arg2 : in Unbounded_String; Arg3 : in String := ""); procedure Info (Log : in Logger'Class; Message : in String; Arg1 : in String := ""; Arg2 : in String := ""; Arg3 : in String := ""); procedure Info (Log : in Logger'Class; Message : in String; Arg1 : in Unbounded_String; Arg2 : in String := ""; Arg3 : in String := ""); procedure Warn (Log : in Logger'Class; Message : in String; Arg1 : in String := ""; Arg2 : in String := ""; Arg3 : in String := ""); procedure Error (Log : in Logger'Class; Message : in String; Arg1 : in String := ""; Arg2 : in String := ""; Arg3 : in String := ""); procedure Error (Log : in Logger'Class; Message : in String; E : in Exception_Occurrence; Trace : in Boolean := False); -- Set the appender that will handle the log events procedure Set_Appender (Log : in out Logger'Class; Appender : in Util.Log.Appenders.Appender_Access); -- Initialize the log environment with the property file. procedure Initialize (Name : in String); -- Initialize the log environment with the properties. procedure Initialize (Properties : in Util.Properties.Manager); type Logger_Info (<>) is limited private; -- Get the logger name. function Get_Logger_Name (Log : in Logger_Info) return String; -- Return a printable traceback that correspond to the exception. function Traceback (E : in Exception_Occurrence) return String; private type Logger_Info_Access is access all Logger_Info; type Logger_Info (Len : Positive) is record Next_Logger : Logger_Info_Access; Prev_Logger : Logger_Info_Access; Level : Level_Type := INFO_LEVEL; Appender : Util.Log.Appenders.Appender_Access; Name : String (1 .. Len); end record; type Logger is new Ada.Finalization.Limited_Controlled with record Instance : Logger_Info_Access; end record; -- Finalize the logger and flush the associated appender overriding procedure Finalize (Log : in out Logger); end Util.Log.Loggers;
----------------------------------------------------------------------- -- util-log-loggers -- Utility Log Package -- Copyright (C) 2006, 2008, 2009, 2011, 2018, 2019 Free Software Foundation, Inc. -- 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 Ada.Strings.Unbounded; with Util.Log.Appenders; with Util.Properties; with Ada.Finalization; package Util.Log.Loggers is use Ada.Exceptions; use Ada.Strings.Unbounded; -- The logger identifies and configures the log produced -- by a component that uses it. The logger has a name -- which can be printed in the log outputs. The logger instance -- contains a log level which can be used to control the level of -- logs. type Logger is tagged limited private; type Logger_Access is access constant Logger; -- Create a logger with the given name. function Create (Name : in String) return Logger; -- Create a logger with the given name and use the specified level. function Create (Name : in String; Level : in Level_Type) return Logger; -- Initialize the logger and create a logger with the given name. function Create (Name : in String; Config : in String) return Logger; -- Change the log level procedure Set_Level (Log : in out Logger; Level : in Level_Type); -- Get the log level. function Get_Level (Log : in Logger) return Level_Type; -- Get the log level name. function Get_Level_Name (Log : in Logger) return String; procedure Print (Log : in Logger; Level : in Level_Type; Message : in String; Arg1 : in String := ""; Arg2 : in String := ""; Arg3 : in String := ""; Arg4 : in String := ""); procedure Debug (Log : in Logger'Class; Message : in String; Arg1 : in String := ""; Arg2 : in String := ""; Arg3 : in String := ""); procedure Debug (Log : in Logger'Class; Message : in String; Arg1 : in String; Arg2 : in String; Arg3 : in String; Arg4 : in String); procedure Debug (Log : in Logger'Class; Message : in String; Arg1 : in Unbounded_String; Arg2 : in String := ""; Arg3 : in String := ""); procedure Debug (Log : in Logger'Class; Message : in String; Arg1 : in Unbounded_String; Arg2 : in Unbounded_String; Arg3 : in String := ""); procedure Info (Log : in Logger'Class; Message : in String; Arg1 : in String := ""; Arg2 : in String := ""; Arg3 : in String := ""); procedure Info (Log : in Logger'Class; Message : in String; Arg1 : in String; Arg2 : in String; Arg3 : in String; Arg4 : in String); procedure Info (Log : in Logger'Class; Message : in String; Arg1 : in Unbounded_String; Arg2 : in String := ""; Arg3 : in String := ""); procedure Warn (Log : in Logger'Class; Message : in String; Arg1 : in String := ""; Arg2 : in String := ""; Arg3 : in String := ""); procedure Error (Log : in Logger'Class; Message : in String; Arg1 : in String := ""; Arg2 : in String := ""; Arg3 : in String := ""); procedure Error (Log : in Logger'Class; Message : in String; E : in Exception_Occurrence; Trace : in Boolean := False); -- Set the appender that will handle the log events procedure Set_Appender (Log : in out Logger'Class; Appender : in Util.Log.Appenders.Appender_Access); -- Initialize the log environment with the property file. procedure Initialize (Name : in String); -- Initialize the log environment with the properties. procedure Initialize (Properties : in Util.Properties.Manager); type Logger_Info (<>) is limited private; -- Get the logger name. function Get_Logger_Name (Log : in Logger_Info) return String; -- Return a printable traceback that correspond to the exception. function Traceback (E : in Exception_Occurrence) return String; private type Logger_Info_Access is access all Logger_Info; type Logger_Info (Len : Positive) is record Next_Logger : Logger_Info_Access; Prev_Logger : Logger_Info_Access; Level : Level_Type := INFO_LEVEL; Appender : Util.Log.Appenders.Appender_Access; Name : String (1 .. Len); end record; type Logger is new Ada.Finalization.Limited_Controlled with record Instance : Logger_Info_Access; end record; -- Finalize the logger and flush the associated appender overriding procedure Finalize (Log : in out Logger); end Util.Log.Loggers;
Add Info and Debug operations with 4 parameters
Add Info and Debug operations with 4 parameters
Ada
apache-2.0
stcarrez/ada-util,stcarrez/ada-util
03ca4c01323fd9327688453382cd6f02571ec2db
matp/regtests/mat-memory-tests.adb
matp/regtests/mat-memory-tests.adb
----------------------------------------------------------------------- -- mat-memory-tests -- Unit tests for MAT memory -- 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 MAT.Expressions; with MAT.Memory.Targets; package body MAT.Memory.Tests is use Util.Tests; package Caller is new Util.Test_Caller (Test, "Memory"); -- Builtin and well known definition of test frames. Frame_1_0 : constant MAT.Frames.Frame_Table (1 .. 10) := (1_0, 1_2, 1_3, 1_4, 1_5, 1_6, 1_7, 1_8, 1_9, 1_10); procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is begin Caller.Add_Test (Suite, "Test MAT.Memory.Probe_Malloc", Test_Probe_Malloc'Access); Caller.Add_Test (Suite, "Test MAT.Memory.Probe_Free", Test_Probe_Free'Access); end Add_Tests; -- ------------------------------ -- Basic consistency checks when creating the test tree -- ------------------------------ procedure Test_Probe_Malloc (T : in out Test) is M : MAT.Memory.Targets.Target_Memory; S : Allocation; R : Allocation_Map; begin S.Size := 4; M.Create_Frame (Frame_1_0, S.Frame); -- Create memory slots: -- [10 .. 14] [20 .. 24] [30 ..34] .. [100 .. 104] for I in 1 .. 10 loop M.Probe_Malloc (MAT.Types.Target_Addr (10 * I), S); end loop; -- Search for a memory region that does not overlap a memory slot. M.Find (15, 19, MAT.Expressions.EMPTY, R); Util.Tests.Assert_Equals (T, 0, Integer (R.Length), "Find must return 0 slots in range [15 .. 19]"); M.Find (1, 9, MAT.Expressions.EMPTY, R); Util.Tests.Assert_Equals (T, 0, Integer (R.Length), "Find must return 0 slots in range [1 .. 9]"); M.Find (105, 1000, MAT.Expressions.EMPTY, R); Util.Tests.Assert_Equals (T, 0, Integer (R.Length), "Find must return 0 slots in range [105 .. 1000]"); -- Search with an overlap. M.Find (1, 1000, MAT.Expressions.EMPTY, R); Util.Tests.Assert_Equals (T, 10, Integer (R.Length), "Find must return 10 slots in range [1 .. 1000]"); R.Clear; M.Find (1, 19, MAT.Expressions.EMPTY, R); Util.Tests.Assert_Equals (T, 1, Integer (R.Length), "Find must return 1 slot in range [1 .. 19]"); R.Clear; M.Find (13, 19, MAT.Expressions.EMPTY, R); Util.Tests.Assert_Equals (T, 1, Integer (R.Length), "Find must return 1 slot in range [13 .. 19]"); R.Clear; M.Find (100, 1000, MAT.Expressions.EMPTY, R); Util.Tests.Assert_Equals (T, 1, Integer (R.Length), "Find must return 1 slot in range [100 .. 1000]"); R.Clear; M.Find (101, 1000, MAT.Expressions.EMPTY, R); Util.Tests.Assert_Equals (T, 1, Integer (R.Length), "Find must return 1 slot in range [101 .. 1000]"); end Test_Probe_Malloc; -- ------------------------------ -- Test Probe_Free with update of memory slots. -- ------------------------------ procedure Test_Probe_Free (T : in out Test) is M : MAT.Memory.Targets.Target_Memory; S : Allocation; R : Allocation_Map; Size : MAT.Types.Target_Size; Id : MAT.Events.Targets.Event_Id_Type; begin S.Size := 4; M.Create_Frame (Frame_1_0, S.Frame); -- Malloc followed by a free. M.Probe_Malloc (10, S); M.Probe_Free (10, S, Size, Id); M.Find (1, 1000, MAT.Expressions.EMPTY, R); Util.Tests.Assert_Equals (T, 0, Integer (R.Length), "Find must return 0 slot after a free"); -- Free the same slot a second time (free error). M.Probe_Free (10, S, Size, Id); -- Malloc followed by a free. M.Probe_Malloc (10, S); M.Probe_Malloc (20, S); M.Probe_Malloc (30, S); M.Probe_Free (20, S, Size, Id); M.Find (1, 1000, MAT.Expressions.EMPTY, R); Util.Tests.Assert_Equals (T, 2, Integer (R.Length), "Find must return 2 slots after a malloc/free sequence"); end Test_Probe_Free; end MAT.Memory.Tests;
----------------------------------------------------------------------- -- mat-memory-tests -- Unit tests for MAT memory -- 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 MAT.Expressions; with MAT.Memory.Targets; package body MAT.Memory.Tests is use Util.Tests; package Caller is new Util.Test_Caller (Test, "Memory"); -- Builtin and well known definition of test frames. Frame_1_0 : constant MAT.Frames.Frame_Table (1 .. 10) := (1_0, 1_2, 1_3, 1_4, 1_5, 1_6, 1_7, 1_8, 1_9, 1_10); procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is begin Caller.Add_Test (Suite, "Test MAT.Memory.Probe_Malloc", Test_Probe_Malloc'Access); Caller.Add_Test (Suite, "Test MAT.Memory.Probe_Free", Test_Probe_Free'Access); end Add_Tests; -- ------------------------------ -- Basic consistency checks when creating the test tree -- ------------------------------ procedure Test_Probe_Malloc (T : in out Test) is M : MAT.Memory.Targets.Target_Memory; S : Allocation; R : Allocation_Map; begin S.Size := 4; M.Create_Frame (Frame_1_0, S.Frame); -- Create memory slots: -- [10 .. 14] [20 .. 24] [30 ..34] .. [100 .. 104] for I in 1 .. 10 loop M.Probe_Malloc (MAT.Types.Target_Addr (10 * I), S); end loop; -- Search for a memory region that does not overlap a memory slot. M.Find (15, 19, MAT.Expressions.EMPTY, R); Util.Tests.Assert_Equals (T, 0, Integer (R.Length), "Find must return 0 slots in range [15 .. 19]"); M.Find (1, 9, MAT.Expressions.EMPTY, R); Util.Tests.Assert_Equals (T, 0, Integer (R.Length), "Find must return 0 slots in range [1 .. 9]"); M.Find (105, 1000, MAT.Expressions.EMPTY, R); Util.Tests.Assert_Equals (T, 0, Integer (R.Length), "Find must return 0 slots in range [105 .. 1000]"); -- Search with an overlap. M.Find (1, 1000, MAT.Expressions.EMPTY, R); Util.Tests.Assert_Equals (T, 10, Integer (R.Length), "Find must return 10 slots in range [1 .. 1000]"); R.Clear; M.Find (1, 19, MAT.Expressions.EMPTY, R); Util.Tests.Assert_Equals (T, 1, Integer (R.Length), "Find must return 1 slot in range [1 .. 19]"); R.Clear; M.Find (13, 19, MAT.Expressions.EMPTY, R); Util.Tests.Assert_Equals (T, 1, Integer (R.Length), "Find must return 1 slot in range [13 .. 19]"); R.Clear; M.Find (100, 1000, MAT.Expressions.EMPTY, R); Util.Tests.Assert_Equals (T, 1, Integer (R.Length), "Find must return 1 slot in range [100 .. 1000]"); R.Clear; M.Find (101, 1000, MAT.Expressions.EMPTY, R); Util.Tests.Assert_Equals (T, 1, Integer (R.Length), "Find must return 1 slot in range [101 .. 1000]"); end Test_Probe_Malloc; -- ------------------------------ -- Test Probe_Free with update of memory slots. -- ------------------------------ procedure Test_Probe_Free (T : in out Test) is M : MAT.Memory.Targets.Target_Memory; S : Allocation; R : Allocation_Map; Size : MAT.Types.Target_Size; Id : MAT.Events.Event_Id_Type; begin S.Size := 4; M.Create_Frame (Frame_1_0, S.Frame); -- Malloc followed by a free. M.Probe_Malloc (10, S); M.Probe_Free (10, S, Size, Id); M.Find (1, 1000, MAT.Expressions.EMPTY, R); Util.Tests.Assert_Equals (T, 0, Integer (R.Length), "Find must return 0 slot after a free"); -- Free the same slot a second time (free error). M.Probe_Free (10, S, Size, Id); -- Malloc followed by a free. M.Probe_Malloc (10, S); M.Probe_Malloc (20, S); M.Probe_Malloc (30, S); M.Probe_Free (20, S, Size, Id); M.Find (1, 1000, MAT.Expressions.EMPTY, R); Util.Tests.Assert_Equals (T, 2, Integer (R.Length), "Find must return 2 slots after a malloc/free sequence"); end Test_Probe_Free; end MAT.Memory.Tests;
Move the Event_Id_Type to the MAT.Events package
Move the Event_Id_Type to the MAT.Events package
Ada
apache-2.0
stcarrez/mat,stcarrez/mat,stcarrez/mat
34c88d1875c7ee48563de0abfe9c241a767a074a
src/security-oauth-file_registry.adb
src/security-oauth-file_registry.adb
----------------------------------------------------------------------- -- security-oauth-file_registry -- File Based Application and Realm -- 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 Util.Encoders.HMAC.SHA1; with Util.Log.Loggers; package body Security.OAuth.File_Registry is Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("Security.OAuth.File_Registry"); -- ------------------------------ -- Get the principal name. -- ------------------------------ overriding function Get_Name (From : in File_Principal) return String is begin return To_String (From.Name); end Get_Name; -- ------------------------------ -- Find the application that correspond to the given client id. -- The <tt>Invalid_Application</tt> exception should be raised if there is no such application. -- ------------------------------ overriding function Find_Application (Realm : in File_Application_Manager; Client_Id : in String) return Servers.Application'Class is Pos : constant Application_Maps.Cursor := Realm.Applications.Find (Client_Id); begin if not Application_Maps.Has_Element (Pos) then raise Servers.Invalid_Application; end if; return Application_Maps.Element (Pos); end Find_Application; -- ------------------------------ -- Add the application to the application repository. -- ------------------------------ procedure Add_Application (Realm : in out File_Application_Manager; App : in Servers.Application) is begin Realm.Applications.Include (App.Get_Application_Identifier, App); end Add_Application; -- ------------------------------ -- Load from the properties the definition of applications. The list of applications -- is controled by the property <prefix>.list which contains a comma separated list of -- application names or ids. The application definition are represented by properties -- of the form: -- <prefix>.<app>.client_id -- <prefix>.<app>.client_secret -- <prefix>.<app>.callback_url -- ------------------------------ procedure Load (Realm : in out File_Application_Manager; Props : in Util.Properties.Manager'Class; Prefix : in String) is procedure Configure (Basename : in String); procedure Configure (Basename : in String) is App : Servers.Application; begin App.Set_Application_Identifier (Props.Get (Basename & ".client_id")); App.Set_Application_Secret (Props.Get (Basename & ".client_secret")); App.Set_Application_Callback (Props.Get (Basename & ".callback_url", "")); Realm.Add_Application (App); end Configure; List : constant String := Props.Get (Prefix & ".list"); First : Natural := List'First; Last : Natural; Count : Natural := 0; begin Log.Info ("Loading application with prefix {0}", Prefix); while First <= List'Last loop Last := Util.Strings.Index (Source => List, Char => ',', From => First); if Last = 0 then Last := List'Last; else Last := Last - 1; end if; begin Configure (Prefix & "." & List (First .. Last)); Count := Count + 1; exception when others => Log.Error ("Invalid application definition {0}", Prefix & "." & List (First .. Last)); end; First := Last + 2; end loop; Log.Info ("Loaded {0} applications", Util.Strings.Image (Count)); end Load; procedure Load (Realm : in out File_Application_Manager; Path : in String; Prefix : in String) is Props : Util.Properties.Manager; begin Log.Info ("Loading application with prefix {0} from {1}", Prefix, Path); Props.Load_Properties (Path); Realm.Load (Props, Prefix); end Load; -- ------------------------------ -- Load from the properties the definition of users. The list of users -- is controled by the property <prefix>.list which contains a comma separated list of -- users names or ids. The user definition are represented by properties -- of the form: -- <prefix>.<user>.username -- <prefix>.<user>.password -- <prefix>.<user>.salt -- When a 'salt' property is defined, it is assumed that the password is encrypted using -- the salt and SHA1 and base64url. Otherwise, the password is in clear text. -- ------------------------------ procedure Load (Realm : in out File_Realm_Manager; Props : in Util.Properties.Manager'Class; Prefix : in String) is procedure Configure (Basename : in String); procedure Configure (Basename : in String) is Username : constant String := Props.Get (Basename & ".username"); Password : constant String := Props.Get (Basename & ".password"); Salt : constant String := Props.Get (Basename & ".salt", ""); begin if Salt'Length = 0 then Realm.Add_User (Username, Password); else Realm.Users.Include (Username, Salt & " " & Password); end if; end Configure; List : constant String := Props.Get (Prefix & ".list"); First : Natural := List'First; Last : Natural; Count : Natural := 0; begin Log.Info ("Loading users with prefix {0}", Prefix); while First <= List'Last loop Last := Util.Strings.Index (Source => List, Char => ',', From => First); if Last = 0 then Last := List'Last; else Last := Last - 1; end if; begin Configure (Prefix & "." & List (First .. Last)); Count := Count + 1; exception when others => Log.Error ("Invalid user definition {0}", Prefix & "." & List (First .. Last)); end; First := Last + 2; end loop; Log.Info ("Loaded {0} users", Util.Strings.Image (Count)); end Load; procedure Load (Realm : in out File_Realm_Manager; Path : in String; Prefix : in String) is Props : Util.Properties.Manager; begin Log.Info ("Loading users with prefix {0} from {1}", Prefix, Path); Props.Load_Properties (Path); Realm.Load (Props, Prefix); end Load; -- ------------------------------ -- Authenticate the token and find the associated authentication principal. -- The access token has been verified and the token represents the identifier -- of the Tuple (client_id, user, session) that describes the authentication. -- The <tt>Authenticate</tt> procedure should look in its database (internal -- or external) to find the authentication principal that was granted for -- the token Tuple. When the token was not found (because it was revoked), -- the procedure should return a null principal. If the authentication -- principal can be cached, the <tt>Cacheable</tt> value should be set. -- In that case, the access token and authentication principal are inserted -- in a cache. -- ------------------------------ overriding procedure Authenticate (Realm : in out File_Realm_Manager; Token : in String; Auth : out Principal_Access; Cacheable : out Boolean) is Pos : constant Token_Maps.Cursor := Realm.Tokens.Find (Token); begin if Token_Maps.Has_Element (Pos) then Auth := Token_Maps.Element (Pos).all'Access; else Auth := null; end if; Cacheable := True; end Authenticate; -- ------------------------------ -- Create an auth token string that identifies the given principal. The returned -- token will be used by <tt>Authenticate</tt> to retrieve back the principal. The -- returned token does not need to be signed. It will be inserted in the public part -- of the returned access token. -- ------------------------------ overriding function Authorize (Realm : in File_Realm_Manager; App : in Servers.Application'Class; Scope : in String; Auth : in Principal_Access) return String is begin return To_String (File_Principal (Auth.all).Token); end Authorize; overriding procedure Verify (Realm : in out File_Realm_Manager; Username : in String; Password : in String; Auth : out Principal_Access) is Result : File_Principal_Access; Pos : constant User_Maps.Cursor := Realm.Users.Find (Username); begin if not User_Maps.Has_Element (Pos) then Log.Info ("Verify user {0} - unkown user", Username); Auth := null; return; end if; -- Verify that the crypt password with the recorded salt are the same. declare Expect : constant String := User_Maps.Element (Pos); Hash : constant String := Realm.Crypt_Password (Expect, Password); begin if Hash /= Expect then Log.Info ("Verify user {0} - invalid password", Username); Auth := null; return; end if; end; -- Generate a random token and make the principal to record it. declare Token : constant String := Realm.Random.Generate (Realm.Token_Bits); begin Result := new File_Principal; Ada.Strings.Unbounded.Append (Result.Token, Token); Ada.Strings.Unbounded.Append (Result.Name, Username); Realm.Tokens.Insert (Token, Result); end; Log.Info ("Verify user {0} - grant access", Username); Auth := Result.all'Access; end Verify; overriding procedure Verify (Realm : in out File_Realm_Manager; Token : in String; Auth : out Principal_Access) is begin Log.Info ("Verify token {0}", Token); Auth := null; end Verify; overriding procedure Revoke (Realm : in out File_Realm_Manager; Auth : in Principal_Access) is begin if Auth /= null and then Auth.all in File_Principal'Class then Realm.Tokens.Delete (To_String (File_Principal (Auth.all).Token)); end if; end Revoke; -- ------------------------------ -- Crypt the password using the given salt and return the string composed with -- the salt in clear text and the crypted password. -- ------------------------------ function Crypt_Password (Realm : in File_Realm_Manager; Salt : in String; Password : in String) return String is pragma Unreferenced (Realm); Pos : Natural := Util.Strings.Index (Salt, ' '); begin if Pos = 0 then Pos := Salt'Last; else Pos := Pos - 1; end if; return Salt (Salt'First .. Pos) & " " & Util.Encoders.HMAC.SHA1.Sign_Base64 (Key => Salt (Salt'First .. Pos), Data => Password, URL => True); end Crypt_Password; -- ------------------------------ -- Add a username with the associated password. -- ------------------------------ procedure Add_User (Realm : in out File_Realm_Manager; Username : in String; Password : in String) is Salt : constant String := Realm.Random.Generate (Realm.Token_Bits); begin Realm.Users.Include (Username, Realm.Crypt_Password (Salt, Password)); end Add_User; end Security.OAuth.File_Registry;
----------------------------------------------------------------------- -- security-oauth-file_registry -- File Based Application and Realm -- 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 Util.Encoders.HMAC.SHA1; with Util.Log.Loggers; package body Security.OAuth.File_Registry is Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("Security.OAuth.File_Registry"); -- ------------------------------ -- Get the principal name. -- ------------------------------ overriding function Get_Name (From : in File_Principal) return String is begin return To_String (From.Name); end Get_Name; -- ------------------------------ -- Check if the permission was granted. -- ------------------------------ overriding function Has_Permission (Auth : in File_Principal; Permission : in Security.Permissions.Permission_Index) return Boolean is begin return Security.Permissions.Has_Permission (Auth.Perms, Permission); end Has_Permission; -- ------------------------------ -- Find the application that correspond to the given client id. -- The <tt>Invalid_Application</tt> exception should be raised if there is no such application. -- ------------------------------ overriding function Find_Application (Realm : in File_Application_Manager; Client_Id : in String) return Servers.Application'Class is Pos : constant Application_Maps.Cursor := Realm.Applications.Find (Client_Id); begin if not Application_Maps.Has_Element (Pos) then raise Servers.Invalid_Application; end if; return Application_Maps.Element (Pos); end Find_Application; -- ------------------------------ -- Add the application to the application repository. -- ------------------------------ procedure Add_Application (Realm : in out File_Application_Manager; App : in Servers.Application) is begin Realm.Applications.Include (App.Get_Application_Identifier, App); end Add_Application; -- ------------------------------ -- Load from the properties the definition of applications. The list of applications -- is controled by the property <prefix>.list which contains a comma separated list of -- application names or ids. The application definition are represented by properties -- of the form: -- <prefix>.<app>.client_id -- <prefix>.<app>.client_secret -- <prefix>.<app>.callback_url -- ------------------------------ procedure Load (Realm : in out File_Application_Manager; Props : in Util.Properties.Manager'Class; Prefix : in String) is procedure Configure (Basename : in String); procedure Configure (Basename : in String) is App : Servers.Application; begin App.Set_Application_Identifier (Props.Get (Basename & ".client_id")); App.Set_Application_Secret (Props.Get (Basename & ".client_secret")); App.Set_Application_Callback (Props.Get (Basename & ".callback_url", "")); Realm.Add_Application (App); end Configure; List : constant String := Props.Get (Prefix & ".list"); First : Natural := List'First; Last : Natural; Count : Natural := 0; begin Log.Info ("Loading application with prefix {0}", Prefix); while First <= List'Last loop Last := Util.Strings.Index (Source => List, Char => ',', From => First); if Last = 0 then Last := List'Last; else Last := Last - 1; end if; begin Configure (Prefix & "." & List (First .. Last)); Count := Count + 1; exception when others => Log.Error ("Invalid application definition {0}", Prefix & "." & List (First .. Last)); end; First := Last + 2; end loop; Log.Info ("Loaded {0} applications", Util.Strings.Image (Count)); end Load; procedure Load (Realm : in out File_Application_Manager; Path : in String; Prefix : in String) is Props : Util.Properties.Manager; begin Log.Info ("Loading application with prefix {0} from {1}", Prefix, Path); Props.Load_Properties (Path); Realm.Load (Props, Prefix); end Load; -- ------------------------------ -- Load from the properties the definition of users. The list of users -- is controled by the property <prefix>.list which contains a comma separated list of -- users names or ids. The user definition are represented by properties -- of the form: -- <prefix>.<user>.username -- <prefix>.<user>.password -- <prefix>.<user>.salt -- When a 'salt' property is defined, it is assumed that the password is encrypted using -- the salt and SHA1 and base64url. Otherwise, the password is in clear text. -- ------------------------------ procedure Load (Realm : in out File_Realm_Manager; Props : in Util.Properties.Manager'Class; Prefix : in String) is procedure Configure (Basename : in String); procedure Configure (Basename : in String) is Username : constant String := Props.Get (Basename & ".username"); Password : constant String := Props.Get (Basename & ".password"); Salt : constant String := Props.Get (Basename & ".salt", ""); begin if Salt'Length = 0 then Realm.Add_User (Username, Password); else Realm.Users.Include (Username, Salt & " " & Password); end if; end Configure; List : constant String := Props.Get (Prefix & ".list"); First : Natural := List'First; Last : Natural; Count : Natural := 0; begin Log.Info ("Loading users with prefix {0}", Prefix); while First <= List'Last loop Last := Util.Strings.Index (Source => List, Char => ',', From => First); if Last = 0 then Last := List'Last; else Last := Last - 1; end if; begin Configure (Prefix & "." & List (First .. Last)); Count := Count + 1; exception when others => Log.Error ("Invalid user definition {0}", Prefix & "." & List (First .. Last)); end; First := Last + 2; end loop; Log.Info ("Loaded {0} users", Util.Strings.Image (Count)); end Load; procedure Load (Realm : in out File_Realm_Manager; Path : in String; Prefix : in String) is Props : Util.Properties.Manager; begin Log.Info ("Loading users with prefix {0} from {1}", Prefix, Path); Props.Load_Properties (Path); Realm.Load (Props, Prefix); end Load; -- ------------------------------ -- Authenticate the token and find the associated authentication principal. -- The access token has been verified and the token represents the identifier -- of the Tuple (client_id, user, session) that describes the authentication. -- The <tt>Authenticate</tt> procedure should look in its database (internal -- or external) to find the authentication principal that was granted for -- the token Tuple. When the token was not found (because it was revoked), -- the procedure should return a null principal. If the authentication -- principal can be cached, the <tt>Cacheable</tt> value should be set. -- In that case, the access token and authentication principal are inserted -- in a cache. -- ------------------------------ overriding procedure Authenticate (Realm : in out File_Realm_Manager; Token : in String; Auth : out Servers.Principal_Access; Cacheable : out Boolean) is Pos : constant Token_Maps.Cursor := Realm.Tokens.Find (Token); begin if Token_Maps.Has_Element (Pos) then Auth := Token_Maps.Element (Pos).all'Access; else Auth := null; end if; Cacheable := True; end Authenticate; -- ------------------------------ -- Create an auth token string that identifies the given principal. The returned -- token will be used by <tt>Authenticate</tt> to retrieve back the principal. The -- returned token does not need to be signed. It will be inserted in the public part -- of the returned access token. -- ------------------------------ overriding function Authorize (Realm : in File_Realm_Manager; App : in Servers.Application'Class; Scope : in String; Auth : in Servers.Principal_Access) return String is File_Auth : constant File_Principal_Access := File_Principal (Auth.all)'Access; begin for P of Security.Permissions.Get_Permission_Array (Scope) loop Security.Permissions.Add_Permission (File_Auth.Perms, P); end loop; return To_String (File_Principal (Auth.all).Token); end Authorize; overriding procedure Verify (Realm : in out File_Realm_Manager; Username : in String; Password : in String; Auth : out Servers.Principal_Access) is Result : File_Principal_Access; Pos : constant User_Maps.Cursor := Realm.Users.Find (Username); begin if not User_Maps.Has_Element (Pos) then Log.Info ("Verify user {0} - unkown user", Username); Auth := null; return; end if; -- Verify that the crypt password with the recorded salt are the same. declare Expect : constant String := User_Maps.Element (Pos); Hash : constant String := Realm.Crypt_Password (Expect, Password); begin if Hash /= Expect then Log.Info ("Verify user {0} - invalid password", Username); Auth := null; return; end if; end; -- Generate a random token and make the principal to record it. declare Token : constant String := Realm.Random.Generate (Realm.Token_Bits); begin Result := new File_Principal; Ada.Strings.Unbounded.Append (Result.Token, Token); Ada.Strings.Unbounded.Append (Result.Name, Username); Realm.Tokens.Insert (Token, Result); end; Log.Info ("Verify user {0} - grant access", Username); Auth := Result.all'Access; end Verify; overriding procedure Verify (Realm : in out File_Realm_Manager; Token : in String; Auth : out Servers.Principal_Access) is begin Log.Info ("Verify token {0}", Token); Auth := null; end Verify; overriding procedure Revoke (Realm : in out File_Realm_Manager; Auth : in Servers.Principal_Access) is use type Servers.Principal_Access; begin if Auth /= null and then Auth.all in File_Principal'Class then Realm.Tokens.Delete (To_String (File_Principal (Auth.all).Token)); end if; end Revoke; -- ------------------------------ -- Crypt the password using the given salt and return the string composed with -- the salt in clear text and the crypted password. -- ------------------------------ function Crypt_Password (Realm : in File_Realm_Manager; Salt : in String; Password : in String) return String is pragma Unreferenced (Realm); Pos : Natural := Util.Strings.Index (Salt, ' '); begin if Pos = 0 then Pos := Salt'Last; else Pos := Pos - 1; end if; return Salt (Salt'First .. Pos) & " " & Util.Encoders.HMAC.SHA1.Sign_Base64 (Key => Salt (Salt'First .. Pos), Data => Password, URL => True); end Crypt_Password; -- ------------------------------ -- Add a username with the associated password. -- ------------------------------ procedure Add_User (Realm : in out File_Realm_Manager; Username : in String; Password : in String) is Salt : constant String := Realm.Random.Generate (Realm.Token_Bits); begin Realm.Users.Include (Username, Realm.Crypt_Password (Salt, Password)); end Add_User; end Security.OAuth.File_Registry;
Implement the Has_Permission function Populate the File_Principal with the permissions defined in the scope
Implement the Has_Permission function Populate the File_Principal with the permissions defined in the scope
Ada
apache-2.0
stcarrez/ada-security
292182c64e82aa0cce4754231b8fa7bf9bdcd27a
tools/druss-commands-bboxes.adb
tools/druss-commands-bboxes.adb
----------------------------------------------------------------------- -- druss-commands-bboxes -- Commands to manage the bboxes -- 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.Text_IO; with Ada.Streams; with Util.Log.Loggers; with Util.Properties; with Util.Strings; with Util.Strings.Sets; with Bbox.API; with Druss.Gateways; with UPnP.SSDP; package body Druss.Commands.Bboxes is use Ada.Strings.Unbounded; use Ada.Text_IO; use type Ada.Streams.Stream_Element_Offset; use type Ada.Streams.Stream_Element; -- The logger Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("Druss.Commands.Bboxes"); procedure Discover (IP : in String) is Box : Bbox.API.Client_Type; Info : Util.Properties.Manager; begin Box.Set_Server (IP); Box.Get ("device", Info); if Info.Get ("device.modelname", "") /= "" then Log.Info ("Found a bbox at {0}", IP); end if; exception when E : others => null; end Discover; procedure Discover (Command : in Command_Type) is IPs : Util.Strings.Sets.Set; Retry : Natural := 0; Scanner : UPnP.SSDP.Scanner_Type; Itf_IPs : Util.Strings.Sets.Set; procedure Process (URI : in String) is Pos2 : Natural; begin -- http:// Pos2 := Util.Strings.Index (URI, ':', 7); if Pos2 > 0 and then not IPs.Contains (URI (URI'First + 7 .. Pos2 - 1)) then Log.Info ("Detected an IGD device at {0}", URI (URI'First + 7 .. Pos2 - 1)); IPs.Include (URI (URI'First + 7 .. Pos2 - 1)); end if; Log.Warn ("Found: {0}", URI); end Process; begin Log.Info ("Discovering gateways on the network"); Scanner.Initialize; Scanner.Find_IPv4_Addresses (Itf_IPs); while Retry < 5 loop Scanner.Send_Discovery ("urn:schemas-upnp-org:device:InternetGatewayDevice:1", Itf_IPs); Scanner.Discover ("urn:schemas-upnp-org:device:InternetGatewayDevice:1", Process'Access, 1.0); Retry := Retry + 1; end loop; for IP of IPs loop Discover (IP); end loop; end Discover; -- Execute the command with the arguments. The command name is passed with the command -- arguments. overriding procedure Execute (Command : in Command_Type; Name : in String; Args : in Util.Commands.Argument_List'Class; Context : in out Context_Type) is begin if Args.Get_Count = 0 then Druss.Commands.Driver.Usage (Args); elsif Args.Get_Argument (1) = "discover" then Command.Discover; end if; end Execute; -- Write the help associated with the command. overriding procedure Help (Command : in Command_Type; Context : in out Context_Type) is begin Put_Line ("bbox: Manage and define the configuration to connect to the Bbox"); Put_Line ("Usage: bbox <operation>..."); New_Line; Put_Line (" The Bbox API operation are called and the raw JSON result is printed."); Put_Line (" When several operations are called, a JSON array is formed to insert"); Put_Line (" their result in the final JSON content so that it is valid."); Put_Line (" Examples:"); Put_Line (" bbox discover Discover the bbox(es) connected to the LAN"); Put_Line (" bbox add IP Add a bbox Get information about the Bbox"); Put_Line (" bbox del IP Get the list of hosts detected by the Bbox"); end Help; end Druss.Commands.Bboxes;
----------------------------------------------------------------------- -- druss-commands-bboxes -- Commands to manage the bboxes -- 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.Text_IO; with Ada.Streams; with Util.Log.Loggers; with Util.Properties; with Util.Strings; with Util.Strings.Sets; with Bbox.API; with Druss.Gateways; with Druss.Config; with UPnP.SSDP; package body Druss.Commands.Bboxes is use Ada.Strings.Unbounded; use Ada.Text_IO; use type Ada.Streams.Stream_Element_Offset; use type Ada.Streams.Stream_Element; -- The logger Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("Druss.Commands.Bboxes"); procedure Discover (IP : in String) is Box : Bbox.API.Client_Type; Info : Util.Properties.Manager; begin Box.Set_Server (IP); Box.Get ("device", Info); if Info.Get ("device.modelname", "") /= "" then Log.Info ("Found a bbox at {0}", IP); end if; exception when E : others => null; end Discover; -- Add the bbox with the given IP address. procedure Add_Bbox (Command : in Command_Type; IP : in String; Context : in out Context_Type) is Box : Bbox.API.Client_Type; Info : Util.Properties.Manager; Gw : Druss.Gateways.Gateway_Ref := Druss.Gateways.Find_IP (Context.Gateways, IP); begin if not Gw.Is_Null then Log.Debug ("Bbox {0} is already registered", IP); return; end if; Box.Set_Server (IP); Box.Get ("device", Info); if Info.Get ("device.modelname", "") /= "" then Log.Info ("Found a new bbox at {0}", IP); Gw := Druss.Gateways.Gateway_Refs.Create; Gw.Value.IP := Ada.Strings.Unbounded.To_Unbounded_String (IP); Context.Gateways.Append (Gw); end if; exception when E : others => null; end Add_Bbox; procedure Discover (Command : in Command_Type; Context : in out Context_Type) is Retry : Natural := 0; Scanner : UPnP.SSDP.Scanner_Type; Itf_IPs : Util.Strings.Sets.Set; procedure Check_Bbox (IP : in String) is Box : Bbox.API.Client_Type; Info : Util.Properties.Manager; begin Box.Set_Server (IP); Box.Get ("device", Info); if Info.Get ("device.modelname", "") /= "" then Log.Info ("Found a bbox at {0}", IP); end if; exception when E : others => null; end Check_Bbox; procedure Process (URI : in String) is Pos : Natural; begin if URI'Length <= 7 or else URI (URI'First .. URI'First + 6) /= "http://" then return; end if; Pos := Util.Strings.Index (URI, ':', 6); if Pos > 0 then Command.Add_Bbox (URI (URI'First + 7 .. Pos - 1), Context); -- Check_Bbox (); end if; end Process; begin Log.Info ("Discovering gateways on the network"); Scanner.Initialize; Scanner.Find_IPv4_Addresses (Itf_IPs); while Retry < 5 loop Scanner.Send_Discovery ("urn:schemas-upnp-org:device:InternetGatewayDevice:1", Itf_IPs); Scanner.Discover ("urn:schemas-upnp-org:device:InternetGatewayDevice:1", Process'Access, 1.0); Retry := Retry + 1; end loop; Druss.Config.Save_Gateways (Context.Gateways); end Discover; -- ------------------------------ -- Set the password to be used by the Bbox API to connect to the box. -- ------------------------------ procedure Password (Command : in Command_Type; Args : in Util.Commands.Argument_List'Class; Context : in out Context_Type) is begin if Args.Get_Count < 2 then Druss.Commands.Driver.Usage (Args); end if; declare Passwd : constant String := Args.Get_Argument (2); Gw : Druss.Gateways.Gateway_Ref; procedure Change_Password (Gateway : in out Druss.Gateways.Gateway_Type) is begin Gateway.Passwd := Ada.Strings.Unbounded.To_Unbounded_String (Passwd); end Change_Password; begin if Args.Get_Count = 2 then Druss.Gateways.Iterate (Context.Gateways, Change_Password'Access); else for I in 3 .. Args.Get_Count loop Gw := Druss.Gateways.Find_IP (Context.Gateways, Args.Get_Argument (I)); if not Gw.Is_Null then Change_Password (Gw.Value.all); end if; end loop; end if; Druss.Config.Save_Gateways (Context.Gateways); end; end Password; -- ------------------------------ -- Execute the command with the arguments. The command name is passed with the command -- arguments. -- ------------------------------ overriding procedure Execute (Command : in Command_Type; Name : in String; Args : in Util.Commands.Argument_List'Class; Context : in out Context_Type) is begin if Args.Get_Count = 0 then Druss.Commands.Driver.Usage (Args); elsif Args.Get_Argument (1) = "discover" then Command.Discover (Context); elsif Args.Get_Argument (1) = "password" then Command.Password (Args, Context); else Put_Line ("Invalid sub-command: " & Args.Get_Argument (1)); Druss.Commands.Driver.Usage (Args); end if; end Execute; -- ------------------------------ -- Write the help associated with the command. -- ------------------------------ overriding procedure Help (Command : in Command_Type; Context : in out Context_Type) is begin Put_Line ("bbox: Manage and define the configuration to connect to the Bbox"); Put_Line ("Usage: bbox <operation>..."); New_Line; Put_Line (" Druss needs to know the list of Bboxes which are available on the network."); Put_Line (" It also need some credentials to connect to the Bbox using the Bbox API."); Put_Line (" The 'bbox' command allows to manage that list and configuration."); Put_Line (" Examples:"); Put_Line (" bbox discover Discover the bbox(es) connected to the LAN"); Put_Line (" bbox add IP Add a bbox knowing its IP address"); Put_Line (" bbox del IP Delete a bbox from the list"); Put_Line (" bbox password <pass> [IP] Set the bbox API connection password"); end Help; end Druss.Commands.Bboxes;
Update the Discover procedure to add the discovered bbox to the configuration and save the configuration Add a password command to setup the password to be used by the bbox API
Update the Discover procedure to add the discovered bbox to the configuration and save the configuration Add a password command to setup the password to be used by the bbox API
Ada
apache-2.0
stcarrez/bbox-ada-api
82caf8b49270364660a9ec7adac6d85da90c3144
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 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). procedure Write_Entity (Stream : in out Output_Stream; Name : in String; Value : in Util.Beans.Objects.Object); -- Starts a XML array. procedure Start_Array (Stream : in out Output_Stream; Length : in Ada.Containers.Count_Type); -- Terminates a XML array. procedure End_Array (Stream : in out Output_Stream); -- 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); -- 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;
Fix Start_Array and End_Array operation and mark them overriding
Fix Start_Array and End_Array operation and mark them overriding
Ada
apache-2.0
stcarrez/ada-util,stcarrez/ada-util
16fad4ad4b502d79948c7ae0fd5a535797c5d302
src/util-commands-consoles-text.adb
src/util-commands-consoles-text.adb
----------------------------------------------------------------------- -- util-commands-consoles-text - Text console interface -- Copyright (C) 2014, 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. ----------------------------------------------------------------------- package body Util.Commands.Consoles.Text is -- ------------------------------ -- Report an error message. -- ------------------------------ overriding procedure Error (Console : in out Console_Type; Message : in String) is pragma Unreferenced (Console); begin Ada.Text_IO.Put_Line (Message); end Error; -- ------------------------------ -- Report a notice message. -- ------------------------------ overriding procedure Notice (Console : in out Console_Type; Kind : in Notice_Type; Message : in String) is pragma Unreferenced (Console, Kind); begin Ada.Text_IO.Put_Line (Message); end Notice; -- ------------------------------ -- Print the field value for the given field. -- ------------------------------ overriding procedure Print_Field (Console : in out Console_Type; Field : in Field_Type; Value : in String; Justify : in Justify_Type := J_LEFT) is use type Ada.Text_IO.Count; Pos : constant Ada.Text_IO.Count := Ada.Text_IO.Count (Console.Cols (Field)); Size : constant Natural := Console.Sizes (Field); Start : Natural := Value'First; Last : constant Natural := Value'Last; Pad : Natural := 0; begin case Justify is when J_LEFT => if Value'Length > Size then Start := Last - Size + 1; end if; when J_RIGHT => if Value'Length < Size then Pad := Size - Value'Length - 1; else Start := Last - Size + 1; end if; when J_CENTER => if Value'Length < Size then Pad := (Size - Value'Length) / 2; else Start := Last - Size + 1; end if; when J_RIGHT_NO_FILL => if Value'Length >= Size then Start := Last - Size + 1; end if; end case; if Pad > 0 then Ada.Text_IO.Set_Col (Pos + Ada.Text_IO.Count (Pad)); elsif Pos > 1 then Ada.Text_IO.Set_Col (Pos); end if; Ada.Text_IO.Put (Value (Start .. Last)); end Print_Field; -- ------------------------------ -- Print the title for the given field. -- ------------------------------ overriding procedure Print_Title (Console : in out Console_Type; Field : in Field_Type; Title : in String) is use type Ada.Text_IO.Count; Pos : constant Ada.Text_IO.Count := Ada.Text_IO.Count (Console.Cols (Field)); begin if Pos > 1 then Ada.Text_IO.Set_Col (Pos); end if; Ada.Text_IO.Put (Title); end Print_Title; -- ------------------------------ -- Start a new title in a report. -- ------------------------------ overriding procedure Start_Title (Console : in out Console_Type) is begin Console.Field_Count := 0; Console.Sizes := (others => 0); Console.Cols := (others => 1); end Start_Title; -- ------------------------------ -- Finish a new title in a report. -- ------------------------------ procedure End_Title (Console : in out Console_Type) is pragma Unreferenced (Console); begin Ada.Text_IO.New_Line; end End_Title; -- ------------------------------ -- Start a new row in a report. -- ------------------------------ overriding procedure Start_Row (Console : in out Console_Type) is pragma Unreferenced (Console); begin null; end Start_Row; -- ------------------------------ -- Finish a new row in a report. -- ------------------------------ overriding procedure End_Row (Console : in out Console_Type) is pragma Unreferenced (Console); begin Ada.Text_IO.New_Line; end End_Row; end Util.Commands.Consoles.Text;
----------------------------------------------------------------------- -- util-commands-consoles-text -- Text 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. ----------------------------------------------------------------------- package body Util.Commands.Consoles.Text is -- ------------------------------ -- Report an error message. -- ------------------------------ overriding procedure Error (Console : in out Console_Type; Message : in String) is pragma Unreferenced (Console); begin Ada.Text_IO.Put_Line (Message); end Error; -- ------------------------------ -- Report a notice message. -- ------------------------------ overriding procedure Notice (Console : in out Console_Type; Kind : in Notice_Type; Message : in String) is pragma Unreferenced (Console, Kind); begin Ada.Text_IO.Put_Line (Message); end Notice; -- ------------------------------ -- Print the field value for the given field. -- ------------------------------ overriding procedure Print_Field (Console : in out Console_Type; Field : in Field_Type; Value : in String; Justify : in Justify_Type := J_LEFT) is use type Ada.Text_IO.Count; Pos : constant Ada.Text_IO.Count := Ada.Text_IO.Count (Console.Cols (Field)); Size : constant Natural := Console.Sizes (Field); Start : Natural := Value'First; Last : constant Natural := Value'Last; Pad : Natural := 0; begin case Justify is when J_LEFT => if Value'Length > Size then Start := Last - Size + 1; end if; when J_RIGHT => if Value'Length < Size then Pad := Size - Value'Length - 1; else Start := Last - Size + 1; end if; when J_CENTER => if Value'Length < Size then Pad := (Size - Value'Length) / 2; else Start := Last - Size + 1; end if; when J_RIGHT_NO_FILL => if Value'Length >= Size then Start := Last - Size + 1; end if; end case; if Pad > 0 then Ada.Text_IO.Set_Col (Pos + Ada.Text_IO.Count (Pad)); elsif Pos > 1 then Ada.Text_IO.Set_Col (Pos); end if; Ada.Text_IO.Put (Value (Start .. Last)); end Print_Field; -- ------------------------------ -- Print the title for the given field. -- ------------------------------ overriding procedure Print_Title (Console : in out Console_Type; Field : in Field_Type; Title : in String) is use type Ada.Text_IO.Count; Pos : constant Ada.Text_IO.Count := Ada.Text_IO.Count (Console.Cols (Field)); begin if Pos > 1 then Ada.Text_IO.Set_Col (Pos); end if; Ada.Text_IO.Put (Title); end Print_Title; -- ------------------------------ -- Start a new title in a report. -- ------------------------------ overriding procedure Start_Title (Console : in out Console_Type) is begin Console.Field_Count := 0; Console.Sizes := (others => 0); Console.Cols := (others => 1); end Start_Title; -- ------------------------------ -- Finish a new title in a report. -- ------------------------------ procedure End_Title (Console : in out Console_Type) is pragma Unreferenced (Console); begin Ada.Text_IO.New_Line; end End_Title; -- ------------------------------ -- Start a new row in a report. -- ------------------------------ overriding procedure Start_Row (Console : in out Console_Type) is pragma Unreferenced (Console); begin null; end Start_Row; -- ------------------------------ -- Finish a new row in a report. -- ------------------------------ overriding procedure End_Row (Console : in out Console_Type) is pragma Unreferenced (Console); begin Ada.Text_IO.New_Line; end End_Row; end Util.Commands.Consoles.Text;
Fix header style
Fix header style
Ada
apache-2.0
stcarrez/ada-util,stcarrez/ada-util
46d59e1fda082ceeb3f8cb99e271272aa8ac10f3
src/asf-events-actions.ads
src/asf-events-actions.ads
----------------------------------------------------------------------- -- asf-events-actions -- Actions Events -- 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; with EL.Expressions; with EL.Beans.Methods.Proc_1; with ASF.Contexts.Faces; with ASF.Components.Base; package ASF.Events.Actions is package Action_Method is new EL.Beans.Methods.Proc_1 (Param1_Type => Ada.Strings.Unbounded.Unbounded_String); -- ------------------------------ -- Action event -- ------------------------------ -- The <b>Action_Event</b> is posted when a method bean action must be executed -- as a result of a command (such as button press). The method action must return -- an outcome string that indicates which view to return. type Action_Event is new Faces_Event with private; type Action_Event_Access is access all Action_Event'Class; -- Get the method expression to invoke function Get_Method (Event : in Action_Event) return EL.Expressions.Method_Expression; -- Post an <b>Action_Event</b> on the component. procedure Post_Event (UI : in out Components.Base.UIComponent'Class; Method : in EL.Expressions.Method_Expression); -- ------------------------------ -- Action Listener -- ------------------------------ -- The <b>Action_Listener</b> is the interface to receive the <b>Action_Event</b>. type Action_Listener is limited interface and Util.Events.Event_Listener; type Action_Listener_Access is access all Action_Listener'Class; -- Process the action associated with the action event. procedure Process_Action (Listener : in Action_Listener; Event : in Action_Event'Class; Context : in out Contexts.Faces.Faces_Context'Class) is abstract; private type Action_Event is new Faces_Event with record Method : EL.Expressions.Method_Expression; end record; end ASF.Events.Actions;
----------------------------------------------------------------------- -- asf-events-actions -- Actions Events -- 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; with EL.Expressions; with EL.Methods.Proc_1; with ASF.Contexts.Faces; with ASF.Components.Base; package ASF.Events.Actions is package Action_Method is new EL.Methods.Proc_1 (Param1_Type => Ada.Strings.Unbounded.Unbounded_String); -- ------------------------------ -- Action event -- ------------------------------ -- The <b>Action_Event</b> is posted when a method bean action must be executed -- as a result of a command (such as button press). The method action must return -- an outcome string that indicates which view to return. type Action_Event is new Faces_Event with private; type Action_Event_Access is access all Action_Event'Class; -- Get the method expression to invoke function Get_Method (Event : in Action_Event) return EL.Expressions.Method_Expression; -- Post an <b>Action_Event</b> on the component. procedure Post_Event (UI : in out Components.Base.UIComponent'Class; Method : in EL.Expressions.Method_Expression); -- ------------------------------ -- Action Listener -- ------------------------------ -- The <b>Action_Listener</b> is the interface to receive the <b>Action_Event</b>. type Action_Listener is limited interface and Util.Events.Event_Listener; type Action_Listener_Access is access all Action_Listener'Class; -- Process the action associated with the action event. procedure Process_Action (Listener : in Action_Listener; Event : in Action_Event'Class; Context : in out Contexts.Faces.Faces_Context'Class) is abstract; private type Action_Event is new Faces_Event with record Method : EL.Expressions.Method_Expression; end record; end ASF.Events.Actions;
Fix compilation after refactoring of Ada-El and Ada-Util
Fix compilation after refactoring of Ada-El and Ada-Util
Ada
apache-2.0
Letractively/ada-asf,Letractively/ada-asf,Letractively/ada-asf
da4abc6e15a41552047fe3a745fb460e947895a7
samples/mapping.ads
samples/mapping.ads
----------------------------------------------------------------------- -- mapping -- Example of serialization mappings -- 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; with Util.Beans.Objects; with Util.Serialize.Mappers.Record_Mapper; with Util.Serialize.Mappers.Vector_Mapper; with Util.Serialize.Mappers; with Ada.Containers.Vectors; with Util.Serialize.Contexts; package Mapping is use Ada.Strings.Unbounded; type Property is record Name : Unbounded_String; Value : Unbounded_String; end record; type Address is record City : Unbounded_String; Street : Unbounded_String; Country : Unbounded_String; Zip : Natural := 0; Info : Property; end record; type Person is record Name : Unbounded_String; First_Name : Unbounded_String; Last_Name : Unbounded_String; Username : Unbounded_String; Gender : Unbounded_String; Link : Unbounded_String; Age : Natural := 0; Addr : Address; Id : Long_Long_Integer := 0; end record; type Person_Access is access all Person; type Person_Fields is (FIELD_FIRST_NAME, FIELD_LAST_NAME, FIELD_AGE, FIELD_NAME, FIELD_USER_NAME, FIELD_GENDER, FIELD_LINK, FIELD_ID); -- Set the name/value pair on the current object. procedure Set_Member (P : in out Person; Field : in Person_Fields; Value : in Util.Beans.Objects.Object); function Get_Person_Member (From : in Person; Field : in Person_Fields) return Util.Beans.Objects.Object; package Person_Mapper is new Util.Serialize.Mappers.Record_Mapper (Element_Type => Person, Element_Type_Access => Person_Access, Fields => Person_Fields, Set_Member => Set_Member); subtype Person_Context is Person_Mapper.Element_Data; package Person_Vector is new Ada.Containers.Vectors (Element_Type => Person, Index_Type => Natural); package Person_Vector_Mapper is new Util.Serialize.Mappers.Vector_Mapper (Vectors => Person_Vector, Element_Mapper => Person_Mapper); subtype Person_Vector_Context is Person_Vector_Mapper.Vector_Data; -- Get the address mapper which describes how to load an Address. function Get_Address_Mapper return Util.Serialize.Mappers.Mapper_Access; -- Get the person mapper which describes how to load a Person. function Get_Person_Mapper return Person_Mapper.Mapper_Access; -- Get the person vector mapper which describes how to load a list of Person. function Get_Person_Vector_Mapper return Person_Vector_Mapper.Mapper_Access; end Mapping;
----------------------------------------------------------------------- -- mapping -- Example of serialization mappings -- Copyright (C) 2010, 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 Ada.Strings.Unbounded; with Util.Beans.Objects; with Util.Serialize.Mappers.Record_Mapper; with Util.Serialize.Mappers; with Ada.Containers.Vectors; package Mapping is use Ada.Strings.Unbounded; type Property is record Name : Unbounded_String; Value : Unbounded_String; end record; type Address is record City : Unbounded_String; Street : Unbounded_String; Country : Unbounded_String; Zip : Natural := 0; Info : Property; end record; type Person is record Name : Unbounded_String; First_Name : Unbounded_String; Last_Name : Unbounded_String; Username : Unbounded_String; Gender : Unbounded_String; Link : Unbounded_String; Age : Natural := 0; Addr : Address; Id : Long_Long_Integer := 0; end record; type Person_Access is access all Person; type Person_Fields is (FIELD_FIRST_NAME, FIELD_LAST_NAME, FIELD_AGE, FIELD_NAME, FIELD_USER_NAME, FIELD_GENDER, FIELD_LINK, FIELD_ID); -- Set the name/value pair on the current object. procedure Set_Member (P : in out Person; Field : in Person_Fields; Value : in Util.Beans.Objects.Object); function Get_Person_Member (From : in Person; Field : in Person_Fields) return Util.Beans.Objects.Object; package Person_Mapper is new Util.Serialize.Mappers.Record_Mapper (Element_Type => Person, Element_Type_Access => Person_Access, Fields => Person_Fields, Set_Member => Set_Member); subtype Person_Context is Person_Mapper.Element_Data; package Person_Vector is new Ada.Containers.Vectors (Element_Type => Person, Index_Type => Natural); -- Get the address mapper which describes how to load an Address. function Get_Address_Mapper return Util.Serialize.Mappers.Mapper_Access; -- Get the person mapper which describes how to load a Person. function Get_Person_Mapper return Person_Mapper.Mapper_Access; end Mapping;
Remove the Person_Vector_Mapper instantiation so that we don't depend on the Vector_Mapper generic package
Remove the Person_Vector_Mapper instantiation so that we don't depend on the Vector_Mapper generic package
Ada
apache-2.0
flottokarotto/ada-util,Letractively/ada-util,flottokarotto/ada-util,Letractively/ada-util
d34568cebe2a2e8f22a99ebac027480a404ffb22
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); -- Initialize the permissions. procedure Start (Manager : in out Permission_Manager); -- 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;
----------------------------------------------------------------------- -- 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 Util.Beans.Objects; with EL.Functions; with ADO; with ADO.Sessions; with ADO.Objects; with Security.Policies; with Security.Contexts; with Security.Policies.Roles; with AWA.Applications; with AWA.Services.Contexts; package AWA.Permissions.Services is package ASC renames AWA.Services.Contexts; -- 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 permission manager associated with the security context. -- Returns null if there is none. function Get_Permission_Manager (Context : in ASC.Service_Context_Access) 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); -- Initialize the permissions. procedure Start (Manager : in out Permission_Manager); -- 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 Security.Permissions.Permission_Index); -- 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 (Manager : in Permission_Manager; 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 Security.Permissions.Permission_Index); -- Add a permission for the user <b>User</b> to access the entity identified by -- <b>Entity</b>. procedure Add_Permission (Manager : in Permission_Manager; Session : in out ADO.Sessions.Master_Session; User : in ADO.Identifier; Entity : in ADO.Objects.Object_Ref'Class; Workspace : in ADO.Identifier; Permission : in Security.Permissions.Permission_Index); -- 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_Array is array (Security.Permissions.Permission_Index) of ADO.Identifier; type Permission_Manager is new Security.Policies.Policy_Manager with record App : AWA.Applications.Application_Access; Roles : Security.Policies.Roles.Role_Policy_Access; -- Mapping between the application permission index and the database permission identifier. Map : Permission_Array := (others => 0); end record; end AWA.Permissions.Services;
Refactor the permission manager - Declare the Get_Permission_Manager function - Add a permission index to the Add_Permission procedure - Declare the Permission_Array type
Refactor the permission manager - Declare the Get_Permission_Manager function - Add a permission index to the Add_Permission procedure - Declare the Permission_Array type
Ada
apache-2.0
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
435175f444bd217c5a51329bd8b2f86826116017
src/util-texts-formats.ads
src/util-texts-formats.ads
----------------------------------------------------------------------- -- Util-texts-formats -- Text Format ala Java MessageFormat -- Copyright (C) 2001, 2002, 2003, 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. ----------------------------------------------------------------------- generic type Stream is limited private; type Char is (<>); type Input is array (Positive range <>) of Char; type Value is limited private; type Value_List is array (Positive range <>) of Value; with procedure Put (Buffer : in out Stream; C : in Character); with function To_Input (Arg : in Value) return Input; package Util.Texts.Formats is -- Format the message and replace occurrences of argument patterns by -- their associated value. -- Returns the formatted message in the stream procedure Format (Message : in Input; Arguments : in Value_List; Into : in out Stream); private procedure Format (Argument : in Value; Into : in out Stream); end Util.Texts.Formats;
----------------------------------------------------------------------- -- Util-texts-formats -- Text Format ala Java MessageFormat -- Copyright (C) 2001, 2002, 2003, 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. ----------------------------------------------------------------------- generic type Stream is limited private; type Char is (<>); type Input is array (Positive range <>) of Char; type Value is limited private; type Value_List is array (Positive range <>) of Value; with procedure Put (Buffer : in out Stream; C : in Character); with function To_Input (Arg : in Value) return Input; package Util.Texts.Formats is pragma Preelaborate; -- Format the message and replace occurrences of argument patterns by -- their associated value. -- Returns the formatted message in the stream procedure Format (Message : in Input; Arguments : in Value_List; Into : in out Stream); private procedure Format (Argument : in Value; Into : in out Stream); end Util.Texts.Formats;
Add Preelaborate pragma
Add Preelaborate pragma
Ada
apache-2.0
stcarrez/ada-util,stcarrez/ada-util
a39c4d4cc751fe4ab541d294d3232b40e5b2c11d
src/asf-streams.ads
src/asf-streams.ads
----------------------------------------------------------------------- -- ASF.Streams -- Print streams for servlets -- 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.Streams; with Ada.Strings.Unbounded; with Ada.Finalization; with Util.Streams; with Util.Streams.Texts; with EL.Objects; package ASF.Streams is pragma Preelaborate; -- ----------------------- -- Print stream -- ----------------------- -- The <b>Print_Stream</b> is an output stream which provides helper methods -- for writing text streams. type Print_Stream is limited new Util.Streams.Output_Stream with private; procedure Initialize (Stream : in out Print_Stream; To : in Util.Streams.Texts.Print_Stream_Access); -- Initialize the stream procedure Initialize (Stream : in out Print_Stream; To : in Print_Stream'Class); -- Write an integer on the stream. procedure Write (Stream : in out Print_Stream; Item : in Integer); -- Write a string on the stream. procedure Write (Stream : in out Print_Stream; Item : in Ada.Strings.Unbounded.Unbounded_String); -- Write a raw character on the stream. procedure Write (Stream : in out Print_Stream; Char : in Character); -- Write a raw string on the stream. procedure Write (Stream : in out Print_Stream; Item : in String); -- Write the object converted into a string on the stream. procedure Write (Stream : in out Print_Stream; Item : in EL.Objects.Object); -- Write the buffer array to the output stream. procedure Write (Stream : in out Print_Stream; Buffer : in Ada.Streams.Stream_Element_Array); -- Flush the buffer by writing on the output stream. -- Raises Data_Error if there is no output stream. procedure Flush (Stream : in out Print_Stream); private type Print_Stream is new Ada.Finalization.Limited_Controlled and Util.Streams.Output_Stream with record Target : Util.Streams.Texts.Print_Stream_Access; end record; end ASF.Streams;
----------------------------------------------------------------------- -- ASF.Streams -- Print streams for servlets -- 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.Streams; with Ada.Strings.Unbounded; with Ada.Finalization; with Util.Streams; with Util.Streams.Texts; with EL.Objects; package ASF.Streams is pragma Preelaborate; -- ----------------------- -- Print stream -- ----------------------- -- The <b>Print_Stream</b> is an output stream which provides helper methods -- for writing text streams. type Print_Stream is new Ada.Finalization.Limited_Controlled and Util.Streams.Output_Stream with private; procedure Initialize (Stream : in out Print_Stream; To : in Util.Streams.Texts.Print_Stream_Access); -- Initialize the stream procedure Initialize (Stream : in out Print_Stream; To : in Print_Stream'Class); -- Write an integer on the stream. procedure Write (Stream : in out Print_Stream; Item : in Integer); -- Write a string on the stream. procedure Write (Stream : in out Print_Stream; Item : in Ada.Strings.Unbounded.Unbounded_String); -- Write a raw character on the stream. procedure Write (Stream : in out Print_Stream; Char : in Character); -- Write a raw string on the stream. procedure Write (Stream : in out Print_Stream; Item : in String); -- Write the object converted into a string on the stream. procedure Write (Stream : in out Print_Stream; Item : in EL.Objects.Object); -- Write the buffer array to the output stream. procedure Write (Stream : in out Print_Stream; Buffer : in Ada.Streams.Stream_Element_Array); -- Flush the buffer by writing on the output stream. -- Raises Data_Error if there is no output stream. procedure Flush (Stream : in out Print_Stream); private type Print_Stream is new Ada.Finalization.Limited_Controlled and Util.Streams.Output_Stream with record Target : Util.Streams.Texts.Print_Stream_Access; end record; end ASF.Streams;
Fix compilation with gcc 4.3
Fix compilation with gcc 4.3
Ada
apache-2.0
Letractively/ada-asf,Letractively/ada-asf,Letractively/ada-asf
3ecd2756029a5a3565cd7f4d82935fe30ad1a12a
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 := "63"; 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 := "64"; 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
9f591ca6139055c0f5166060d82138c5ee1f7c2c
tests/natools-s_expressions-lockable-tests.adb
tests/natools-s_expressions-lockable-tests.adb
------------------------------------------------------------------------------ -- Copyright (c) 2014, 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. -- ------------------------------------------------------------------------------ with Natools.S_Expressions.Test_Tools; with Natools.S_Expressions.Parsers; package body Natools.S_Expressions.Lockable.Tests is ------------------------------- -- Lockable.Descriptor Tests -- ------------------------------- function Test_Expression return Atom is begin return To_Atom ("(begin(command1 arg1.1 arg1.2)" & "(command2 (subcmd2.1 arg2.1.1) (subcmd2.3) arg2.4)" & "end)"); end Test_Expression; procedure Test_Interface (Test : in out NT.Test; Object : in out Lockable.Descriptor'Class) is Level_1, Level_2 : Lock_State; Base : Natural; begin Base := Object.Current_Level; Test_Tools.Next_And_Check (Test, Object, To_Atom ("begin"), Base); Test_Tools.Next_And_Check (Test, Object, Events.Open_List, Base + 1); Test_Tools.Next_And_Check (Test, Object, To_Atom ("command1"), Base + 1, "Before first lock:"); Object.Lock (Level_1); Test_Tools.Test_Atom_Accessors (Test, Object, To_Atom ("command1"), 0, "After first lock:"); Test_Tools.Next_And_Check (Test, Object, To_Atom ("arg1.1"), 0); Test_Tools.Next_And_Check (Test, Object, To_Atom ("arg1.2"), 0); Test_Tools.Next_And_Check (Test, Object, Events.End_Of_Input, 0, "Before first unlock:"); Test_Tools.Test_Atom_Accessor_Exceptions (Test, Object); Object.Unlock (Level_1); declare Event : constant Events.Event := Object.Current_Event; Level : constant Natural := Object.Current_Level; begin if Event /= Events.Close_List then Test.Fail ("Current event is " & Events.Event'Image (Event) & ", expected Close_List"); end if; if Level /= Base then Test.Fail ("Current level is" & Natural'Image (Level) & ", expected" & Natural'Image (Base)); end if; end; Test_Tools.Next_And_Check (Test, Object, Events.Open_List, Base + 1); Test_Tools.Next_And_Check (Test, Object, To_Atom ("command2"), Base + 1, "Before second lock:"); Object.Lock (Level_1); Test_Tools.Test_Atom_Accessors (Test, Object, To_Atom ("command2"), 0, "After second lock:"); Test_Tools.Next_And_Check (Test, Object, Events.Open_List, 1); Test_Tools.Next_And_Check (Test, Object, To_Atom ("subcmd2.1"), 1, "Before inner lock:"); Object.Lock (Level_2); Test_Tools.Test_Atom_Accessors (Test, Object, To_Atom ("subcmd2.1"), 0, "After inner lock:"); Test_Tools.Next_And_Check (Test, Object, To_Atom ("arg2.1.1"), 0, "Before inner unlock:"); Object.Unlock (Level_2, False); Test_Tools.Test_Atom_Accessors (Test, Object, To_Atom ("arg2.1.1"), 1, "After inner unlock:"); Test_Tools.Next_And_Check (Test, Object, Events.Close_List, 0); Test_Tools.Next_And_Check (Test, Object, Events.Open_List, 1); Test_Tools.Next_And_Check (Test, Object, To_Atom ("subcmd2.3"), 1, "Before inner lock:"); Object.Lock (Level_2); Test_Tools.Test_Atom_Accessors (Test, Object, To_Atom ("subcmd2.3"), 0, "After inner lock:"); Test_Tools.Next_And_Check (Test, Object, Events.End_Of_Input, 0, "Before inner unlock:"); Object.Unlock (Level_2, False); declare Event : constant Events.Event := Object.Current_Event; Level : constant Natural := Object.Current_Level; begin if Event /= Events.Close_List then Test.Fail ("Current event is " & Events.Event'Image (Event) & ", expected Close_List"); end if; if Level /= 1 then Test.Fail ("Current level is" & Natural'Image (Level) & ", expected 1"); end if; end; Object.Unlock (Level_1); Test_Tools.Next_And_Check (Test, Object, To_Atom ("end"), Base); Test_Tools.Next_And_Check (Test, Object, Events.Close_List, Base - 1); end Test_Interface; ------------------------- -- Complete Test Suite -- ------------------------- procedure All_Tests (Report : in out NT.Reporter'Class) is begin Test_Stack (Report); Test_Wrapper_Interface (Report); Test_Wrapper_Extra (Report); end All_Tests; --------------------------- -- Individual Test Cases -- --------------------------- procedure Test_Stack (Report : in out NT.Reporter'Class) is Test : NT.Test := Report.Item ("Level stack"); begin declare Stack : Lock_Stack; State : array (1 .. 4) of Lock_State; procedure Check_Level (Stack : in Lock_Stack; Expected : in Natural; Context : in String); procedure Dump_Data; procedure Check_Level (Stack : in Lock_Stack; Expected : in Natural; Context : in String) is Level : constant Natural := Current_Level (Stack); begin if Level /= Expected then Test.Fail (Context & ": level is" & Natural'Image (Level) & ", expected" & Natural'Image (Expected)); Dump_Data; end if; end Check_Level; procedure Dump_Data is begin Test.Info (" Stack: (Depth =>" & Natural'Image (Stack.Depth) & ", Level =>" & Natural'Image (Stack.Level) & ')'); for I in State'Range loop Test.Info (" State" & Natural'Image (I) & ": (Depth =>" & Natural'Image (Stack.Depth) & ", Level =>" & Natural'Image (Stack.Level) & ')'); end loop; end Dump_Data; begin Check_Level (Stack, 0, "1"); Push_Level (Stack, 14, State (1)); Check_Level (Stack, 14, "2"); begin Pop_Level (Stack, State (2)); Test.Fail ("No exception raised after popping blank state"); exception when Constraint_Error => null; when Error : others => Test.Fail ("Unexpected exception raised after popping blank state"); Test.Report_Exception (Error, NT.Fail); end; Pop_Level (Stack, State (1)); Check_Level (Stack, 0, "3"); Push_Level (Stack, 15, State (1)); Check_Level (Stack, 15, "4"); Push_Level (Stack, 92, State (2)); Check_Level (Stack, 92, "5"); Push_Level (Stack, 65, State (3)); Check_Level (Stack, 65, "6"); Pop_Level (Stack, State (3)); Check_Level (Stack, 92, "7"); Push_Level (Stack, 35, State (3)); Check_Level (Stack, 35, "8"); Push_Level (Stack, 89, State (4)); Check_Level (Stack, 89, "9"); begin Pop_Level (Stack, State (3)); Test.Fail ("No exception raised after popping a forbidden gap"); exception when Constraint_Error => null; when Error : others => Test.Fail ("Unexpected exception raised after popping a forbidden gap"); Test.Report_Exception (Error, NT.Fail); end; Check_Level (Stack, 89, "10"); Pop_Level (Stack, State (3), True); Check_Level (Stack, 92, "11"); begin Pop_Level (Stack, State (4)); Test.Fail ("No exception raised after popping stale state"); exception when Constraint_Error => null; when Error : others => Test.Fail ("Unexpected exception raised after popping stale state"); Test.Report_Exception (Error, NT.Fail); end; Check_Level (Stack, 92, "12"); Pop_Level (Stack, State (2)); Check_Level (Stack, 15, "13"); Pop_Level (Stack, State (1)); Check_Level (Stack, 0, "14"); end; exception when Error : others => Test.Report_Exception (Error); end Test_Stack; procedure Test_Wrapper_Extra (Report : in out NT.Reporter'Class) is Test : NT.Test := Report.Item ("Extra tests of wrapper"); begin declare Input : aliased Test_Tools.Memory_Stream; Parser : aliased Parsers.Parser; Subparser : aliased Parsers.Subparser (Parser'Access, Input'Access); Tested : Wrapper (Subparser'Access); State : Lock_State; begin Input.Set_Data (To_Atom ("(cmd1 arg1)(cmd2 4:arg2")); -- Check Events.Error is returned by Next when finished Test_Tools.Next_And_Check (Test, Tested, Events.Open_List, 1); Test_Tools.Next_And_Check (Test, Tested, To_Atom ("cmd1"), 1); Tested.Lock (State); Test_Tools.Next_And_Check (Test, Tested, To_Atom ("arg1"), 0); Test_Tools.Next_And_Check (Test, Tested, Events.End_Of_Input, 0); Test_Tools.Next_And_Check (Test, Tested, Events.Error, 0); Tested.Unlock (State); -- Run Unlock with End_Of_Input in backend Test_Tools.Next_And_Check (Test, Tested, Events.Open_List, 1); Test_Tools.Next_And_Check (Test, Tested, To_Atom ("cmd2"), 1); Tested.Lock (State); Test_Tools.Next_And_Check (Test, Tested, To_Atom ("arg2"), 0); Tested.Unlock (State); end; exception when Error : others => Test.Report_Exception (Error); end Test_Wrapper_Extra; procedure Test_Wrapper_Interface (Report : in out NT.Reporter'Class) is Test : NT.Test := Report.Item ("Lockable.Descriptor interface of wrapper"); begin declare Input : aliased Test_Tools.Memory_Stream; Parser : aliased Parsers.Parser; Subparser : aliased Parsers.Subparser (Parser'Access, Input'Access); Tested : Wrapper (Subparser'Access); begin Input.Set_Data (Test_Expression); Test_Tools.Next_And_Check (Test, Subparser, Events.Open_List, 1); Test_Interface (Test, Tested); end; exception when Error : others => Test.Report_Exception (Error); end Test_Wrapper_Interface; end Natools.S_Expressions.Lockable.Tests;
------------------------------------------------------------------------------ -- Copyright (c) 2014, 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. -- ------------------------------------------------------------------------------ with Natools.S_Expressions.Test_Tools; with Natools.S_Expressions.Parsers; package body Natools.S_Expressions.Lockable.Tests is ------------------------------- -- Lockable.Descriptor Tests -- ------------------------------- function Test_Expression return Atom is begin return To_Atom ("(begin(command1 arg1.1 arg1.2)" & "(command2 (subcmd2.1 arg2.1.1) (subcmd2.3) arg2.4)" & "end)"); end Test_Expression; procedure Test_Interface (Test : in out NT.Test; Object : in out Lockable.Descriptor'Class) is Level_1, Level_2 : Lock_State; Base : Natural; begin Base := Object.Current_Level; Test_Tools.Next_And_Check (Test, Object, To_Atom ("begin"), Base); Test_Tools.Next_And_Check (Test, Object, Events.Open_List, Base + 1); Test_Tools.Next_And_Check (Test, Object, To_Atom ("command1"), Base + 1, "Before first lock:"); Object.Lock (Level_1); Test_Tools.Test_Atom_Accessors (Test, Object, To_Atom ("command1"), 0, "After first lock:"); Test_Tools.Next_And_Check (Test, Object, To_Atom ("arg1.1"), 0); Test_Tools.Next_And_Check (Test, Object, To_Atom ("arg1.2"), 0); Test_Tools.Next_And_Check (Test, Object, Events.End_Of_Input, 0, "Before first unlock:"); Test_Tools.Test_Atom_Accessor_Exceptions (Test, Object); Object.Unlock (Level_1); declare Event : constant Events.Event := Object.Current_Event; Level : constant Natural := Object.Current_Level; begin if Event /= Events.Close_List then Test.Fail ("Current event is " & Events.Event'Image (Event) & ", expected Close_List"); end if; if Level /= Base then Test.Fail ("Current level is" & Natural'Image (Level) & ", expected" & Natural'Image (Base)); end if; end; Test_Tools.Next_And_Check (Test, Object, Events.Open_List, Base + 1); Test_Tools.Next_And_Check (Test, Object, To_Atom ("command2"), Base + 1, "Before second lock:"); Object.Lock (Level_1); Test_Tools.Test_Atom_Accessors (Test, Object, To_Atom ("command2"), 0, "After second lock:"); Test_Tools.Next_And_Check (Test, Object, Events.Open_List, 1); Test_Tools.Next_And_Check (Test, Object, To_Atom ("subcmd2.1"), 1, "Before inner lock:"); Object.Lock (Level_2); Test_Tools.Test_Atom_Accessors (Test, Object, To_Atom ("subcmd2.1"), 0, "After inner lock:"); Test_Tools.Next_And_Check (Test, Object, To_Atom ("arg2.1.1"), 0, "Before inner unlock:"); Object.Unlock (Level_2, False); Test_Tools.Test_Atom_Accessors (Test, Object, To_Atom ("arg2.1.1"), 1, "After inner unlock:"); Test_Tools.Next_And_Check (Test, Object, Events.Close_List, 0); Test_Tools.Next_And_Check (Test, Object, Events.Open_List, 1); Test_Tools.Next_And_Check (Test, Object, To_Atom ("subcmd2.3"), 1, "Before inner lock:"); Object.Lock (Level_2); Test_Tools.Test_Atom_Accessors (Test, Object, To_Atom ("subcmd2.3"), 0, "After inner lock:"); Test_Tools.Next_And_Check (Test, Object, Events.End_Of_Input, 0, "Before inner unlock:"); Object.Unlock (Level_2, False); declare Event : constant Events.Event := Object.Current_Event; Level : constant Natural := Object.Current_Level; begin if Event /= Events.Close_List then Test.Fail ("Current event is " & Events.Event'Image (Event) & ", expected Close_List"); end if; if Level /= 0 then Test.Fail ("Current level is" & Natural'Image (Level) & ", expected 0"); end if; end; Object.Unlock (Level_1); Test_Tools.Next_And_Check (Test, Object, To_Atom ("end"), Base); Test_Tools.Next_And_Check (Test, Object, Events.Close_List, Base - 1); end Test_Interface; ------------------------- -- Complete Test Suite -- ------------------------- procedure All_Tests (Report : in out NT.Reporter'Class) is begin Test_Stack (Report); Test_Wrapper_Interface (Report); Test_Wrapper_Extra (Report); end All_Tests; --------------------------- -- Individual Test Cases -- --------------------------- procedure Test_Stack (Report : in out NT.Reporter'Class) is Test : NT.Test := Report.Item ("Level stack"); begin declare Stack : Lock_Stack; State : array (1 .. 4) of Lock_State; procedure Check_Level (Stack : in Lock_Stack; Expected : in Natural; Context : in String); procedure Dump_Data; procedure Check_Level (Stack : in Lock_Stack; Expected : in Natural; Context : in String) is Level : constant Natural := Current_Level (Stack); begin if Level /= Expected then Test.Fail (Context & ": level is" & Natural'Image (Level) & ", expected" & Natural'Image (Expected)); Dump_Data; end if; end Check_Level; procedure Dump_Data is begin Test.Info (" Stack: (Depth =>" & Natural'Image (Stack.Depth) & ", Level =>" & Natural'Image (Stack.Level) & ')'); for I in State'Range loop Test.Info (" State" & Natural'Image (I) & ": (Depth =>" & Natural'Image (Stack.Depth) & ", Level =>" & Natural'Image (Stack.Level) & ')'); end loop; end Dump_Data; begin Check_Level (Stack, 0, "1"); Push_Level (Stack, 14, State (1)); Check_Level (Stack, 14, "2"); begin Pop_Level (Stack, State (2)); Test.Fail ("No exception raised after popping blank state"); exception when Constraint_Error => null; when Error : others => Test.Fail ("Unexpected exception raised after popping blank state"); Test.Report_Exception (Error, NT.Fail); end; Pop_Level (Stack, State (1)); Check_Level (Stack, 0, "3"); Push_Level (Stack, 15, State (1)); Check_Level (Stack, 15, "4"); Push_Level (Stack, 92, State (2)); Check_Level (Stack, 92, "5"); Push_Level (Stack, 65, State (3)); Check_Level (Stack, 65, "6"); Pop_Level (Stack, State (3)); Check_Level (Stack, 92, "7"); Push_Level (Stack, 35, State (3)); Check_Level (Stack, 35, "8"); Push_Level (Stack, 89, State (4)); Check_Level (Stack, 89, "9"); begin Pop_Level (Stack, State (3)); Test.Fail ("No exception raised after popping a forbidden gap"); exception when Constraint_Error => null; when Error : others => Test.Fail ("Unexpected exception raised after popping a forbidden gap"); Test.Report_Exception (Error, NT.Fail); end; Check_Level (Stack, 89, "10"); Pop_Level (Stack, State (3), True); Check_Level (Stack, 92, "11"); begin Pop_Level (Stack, State (4)); Test.Fail ("No exception raised after popping stale state"); exception when Constraint_Error => null; when Error : others => Test.Fail ("Unexpected exception raised after popping stale state"); Test.Report_Exception (Error, NT.Fail); end; Check_Level (Stack, 92, "12"); Pop_Level (Stack, State (2)); Check_Level (Stack, 15, "13"); Pop_Level (Stack, State (1)); Check_Level (Stack, 0, "14"); end; exception when Error : others => Test.Report_Exception (Error); end Test_Stack; procedure Test_Wrapper_Extra (Report : in out NT.Reporter'Class) is Test : NT.Test := Report.Item ("Extra tests of wrapper"); begin declare Input : aliased Test_Tools.Memory_Stream; Parser : aliased Parsers.Parser; Subparser : aliased Parsers.Subparser (Parser'Access, Input'Access); Tested : Wrapper (Subparser'Access); State : Lock_State; begin Input.Set_Data (To_Atom ("(cmd1 arg1)(cmd2 4:arg2")); -- Check Events.Error is returned by Next when finished Test_Tools.Next_And_Check (Test, Tested, Events.Open_List, 1); Test_Tools.Next_And_Check (Test, Tested, To_Atom ("cmd1"), 1); Tested.Lock (State); Test_Tools.Next_And_Check (Test, Tested, To_Atom ("arg1"), 0); Test_Tools.Next_And_Check (Test, Tested, Events.End_Of_Input, 0); Test_Tools.Next_And_Check (Test, Tested, Events.Error, 0); Tested.Unlock (State); -- Run Unlock with End_Of_Input in backend Test_Tools.Next_And_Check (Test, Tested, Events.Open_List, 1); Test_Tools.Next_And_Check (Test, Tested, To_Atom ("cmd2"), 1); Tested.Lock (State); Test_Tools.Next_And_Check (Test, Tested, To_Atom ("arg2"), 0); Tested.Unlock (State); end; exception when Error : others => Test.Report_Exception (Error); end Test_Wrapper_Extra; procedure Test_Wrapper_Interface (Report : in out NT.Reporter'Class) is Test : NT.Test := Report.Item ("Lockable.Descriptor interface of wrapper"); begin declare Input : aliased Test_Tools.Memory_Stream; Parser : aliased Parsers.Parser; Subparser : aliased Parsers.Subparser (Parser'Access, Input'Access); Tested : Wrapper (Subparser'Access); begin Input.Set_Data (Test_Expression); Test_Tools.Next_And_Check (Test, Subparser, Events.Open_List, 1); Test_Interface (Test, Tested); end; exception when Error : others => Test.Report_Exception (Error); end Test_Wrapper_Interface; end Natools.S_Expressions.Lockable.Tests;
fix bad expected value in interface test
s_expressions-lockable-tests: fix bad expected value in interface test
Ada
isc
faelys/natools
cdc8804ccfdb6de5b3f1f3fa7a780ef9ad261842
samples/render.adb
samples/render.adb
----------------------------------------------------------------------- -- render -- XHTML Rendering example -- 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.Text_IO; with Ada.Exceptions; with Ada.IO_Exceptions; with Ada.Strings.Unbounded; with Ada.Strings.Fixed; with GNAT.Command_Line; with ASF.Applications.Main; with ASF.Requests.Mockup; with ASF.Responses.Mockup; with ASF.Contexts.Faces; with EL.Objects; with EL.Contexts; with EL.Contexts.Default; with EL.Variables; with EL.Variables.Default; with ASF.Streams; -- This example reads an XHTML file and renders the result. procedure Render is use GNAT.Command_Line; use Ada.Strings.Fixed; use ASF; use ASF.Contexts.Faces; use EL.Contexts.Default; use EL.Variables; use EL.Variables.Default; use EL.Contexts; use EL.Objects; App : Applications.Main.Application; Conf : Applications.Config; begin loop case Getopt ("D:") is when 'D' => declare Value : constant String := Parameter; Pos : constant Natural := Index (Value, "="); begin -- if Pos > 0 then -- Variables.Set_Variable (Value (1 .. Pos - 1), -- To_Object (Value (Pos + 1 .. Value'Last))); -- else -- Variables.Set_Variable (Value, To_Object(True)); -- end if; null; end; when others => exit; end case; end loop; Conf.Set ("view.ignore_white_spaces", "false"); Conf.Set ("view.escape_unknown_tags", "false"); Conf.Set ("view.ignore_empty_lines", "true"); declare View_Name : constant String := Get_Argument; Req : ASF.Requests.Mockup.Request; Reply : ASF.Responses.Mockup.Response; Content : Ada.Strings.Unbounded.Unbounded_String; begin App.Initialize (Conf); App.Dispatch (Page => View_Name, Request => Req, Response => Reply); Reply.Read_Content (Content); Ada.Text_IO.Put_Line (Ada.Strings.Unbounded.To_String (Content)); exception when Ada.IO_Exceptions.Name_Error => Ada.Text_IO.Put_Line ("Cannot read file '" & View_Name & "'"); end; end Render;
----------------------------------------------------------------------- -- render -- XHTML Rendering example -- 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.Text_IO; with Ada.IO_Exceptions; with Ada.Strings.Unbounded; with Ada.Strings.Fixed; with GNAT.Command_Line; with ASF.Applications.Main; with ASF.Requests.Mockup; with ASF.Responses.Mockup; with EL.Objects; -- This example reads an XHTML file and renders the result. procedure Render is use GNAT.Command_Line; use Ada.Strings.Fixed; use ASF; use EL.Objects; Factory : ASF.Applications.Main.Application_Factory; App : Applications.Main.Application; Conf : Applications.Config; begin Conf.Set ("view.ignore_white_spaces", "false"); Conf.Set ("view.escape_unknown_tags", "false"); Conf.Set ("view.ignore_empty_lines", "true"); App.Initialize (Conf, Factory); loop case Getopt ("D:") is when 'D' => declare Value : constant String := Parameter; Pos : constant Natural := Index (Value, "="); begin if Pos > 0 then App.Set_Global (Name => Value (1 .. Pos - 1), Value => To_Object (Value (Pos + 1 .. Value'Last))); else App.Set_Global (Name => Value (1 .. Pos - 1), Value => To_Object(True)); end if; end; when others => exit; end case; end loop; declare View_Name : constant String := Get_Argument; Req : ASF.Requests.Mockup.Request; Reply : ASF.Responses.Mockup.Response; Content : Ada.Strings.Unbounded.Unbounded_String; begin App.Dispatch (Page => View_Name, Request => Req, Response => Reply); Reply.Read_Content (Content); Ada.Text_IO.Put_Line (Ada.Strings.Unbounded.To_String (Content)); exception when Ada.IO_Exceptions.Name_Error => Ada.Text_IO.Put_Line ("Cannot read file '" & View_Name & "'"); end; end Render;
Update the render example
Update the render example
Ada
apache-2.0
stcarrez/ada-asf,stcarrez/ada-asf,stcarrez/ada-asf
67d9f0ddc037acfae0d3eff75e4380a74e88b112
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 Ada.Strings.Unbounded; 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; -- Get an 8-bit value from the buffer. function Get_Uint8 (Buffer : in Buffer_Ptr) return MAT.Types.Uint8; -- Get a 16-bit value either from big-endian or little endian. 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; -- Extract a string from the buffer. The string starts with a byte that -- indicates the string length. function Get_String (Msg : in Buffer_Ptr) return Ada.Strings.Unbounded.Unbounded_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); function Get_Target_Size (Msg : in Buffer_Ptr; Kind : in MAT.Events.Attribute_Type) return MAT.Types.Target_Size; function Get_Target_Addr (Msg : in Buffer_Ptr; Kind : in MAT.Events.Attribute_Type) return MAT.Types.Target_Addr; function Get_Target_Uint32 (Msg : in Buffer_Ptr; Kind : in MAT.Events.Attribute_Type) return MAT.Types.Uint32; -- Skip the given number of bytes from the message. procedure Skip (Buffer : 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 Ada.Strings.Unbounded; 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; -- Get an 8-bit value from the buffer. function Get_Uint8 (Buffer : in Buffer_Ptr) return MAT.Types.Uint8; -- Get a 16-bit value either from big-endian or little endian. function Get_Uint16 (Buffer : in Buffer_Ptr) return MAT.Types.Uint16; -- Get a 32-bit value either from big-endian or little endian. 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; -- Extract a string from the buffer. The string starts with a byte that -- indicates the string length. function Get_String (Msg : in Buffer_Ptr) return Ada.Strings.Unbounded.Unbounded_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); function Get_Target_Size (Msg : in Buffer_Ptr; Kind : in MAT.Events.Attribute_Type) return MAT.Types.Target_Size; function Get_Target_Addr (Msg : in Buffer_Ptr; Kind : in MAT.Events.Attribute_Type) return MAT.Types.Target_Addr; function Get_Target_Uint32 (Msg : in Buffer_Ptr; Kind : in MAT.Events.Attribute_Type) return MAT.Types.Uint32; -- Skip the given number of bytes from the message. procedure Skip (Buffer : in Buffer_Ptr; Size : in Natural); end MAT.Readers.Marshaller;
Document Get_Uint32
Document Get_Uint32
Ada
apache-2.0
stcarrez/mat,stcarrez/mat,stcarrez/mat
727461babd0305344427bf8a56cdae2b68d08caf
src/babel-files.adb
src/babel-files.adb
-- bkp-files -- File and directories ----------------------------------------------------------------------- -- 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.Calendar.Conversions; with Interfaces.C; with Util.Log.Loggers; with Util.Files; with Util.Encoders.Base16; package body Babel.Files is Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("Bkp.Files"); Hex_Encoder : Util.Encoders.Base16.Encoder; -- ------------------------------ -- Compare two files on their name and directory. -- ------------------------------ function "<" (Left, Right : in File_Type) return Boolean is use type Ada.Strings.Unbounded.Unbounded_String; begin if Left = NO_FILE then return False; elsif Right = NO_FILE then return True; elsif Left.Dir = Right.Dir then return Left.Name < Right.Name; elsif Left.Dir = NO_DIRECTORY then return True; elsif Right.Dir = NO_DIRECTORY then return False; else return Left.Dir.Path < Right.Dir.Path; end if; end "<"; -- ------------------------------ -- Allocate a File_Type entry with the given name for the directory. -- ------------------------------ function Allocate (Name : in String; Dir : in Directory_Type) return File_Type is use Ada.Strings.Unbounded; Result : constant File_Type := new File '(Len => Name'Length, Id => NO_IDENTIFIER, Dir => Dir, Name => Name, others => <>); begin return Result; end Allocate; -- ------------------------------ -- Allocate a Directory_Type entry with the given name for the directory. -- ------------------------------ function Allocate (Name : in String; Dir : in Directory_Type) return Directory_Type is use Ada.Strings.Unbounded; Dir_Name : constant String_Access := new String '(Name); Result : constant Directory_Type := new Directory '(-- Len => Name'Length, Id => NO_IDENTIFIER, Parent => Dir, Name => Dir_Name, others => <>); begin if Dir /= null then Result.Path := To_Unbounded_String (Util.Files.Compose (To_String (Dir.Path), Name)); else Result.Path := To_Unbounded_String (Name); end if; return Result; end Allocate; -- ------------------------------ -- Return true if the file was modified and need a backup. -- ------------------------------ function Is_Modified (Element : in File_Type) return Boolean is use type ADO.Identifier; begin if Element.Id = NO_IDENTIFIER then return True; elsif (Element.Status and FILE_MODIFIED) /= 0 then return True; else return False; end if; end Is_Modified; -- ------------------------------ -- Return true if the file is a new file. -- ------------------------------ function Is_New (Element : in File_Type) return Boolean is use type ADO.Identifier; begin return Element.Id = NO_IDENTIFIER; end Is_New; -- ------------------------------ -- Set the file as modified. -- ------------------------------ procedure Set_Modified (Element : in File_Type) is begin Element.Status := Element.Status or FILE_MODIFIED; end Set_Modified; -- ------------------------------ -- Set the SHA1 signature that was computed for this file. -- If the computed signature is different from the current signature, -- the FILE_MODIFIED flag is set on the file. The FILE_HAS_SHA1 flag -- is set on the file. -- ------------------------------ procedure Set_Signature (Element : in File_Type; Signature : in Util.Encoders.SHA1.Hash_Array) is use type Util.Encoders.SHA1.Hash_Array; begin if (Element.Status and FILE_HAS_SHA1) /= 0 and then Element.SHA1 /= Signature then Element.Status := Element.Status or FILE_MODIFIED; end if; Element.Status := Element.Status or FILE_HAS_SHA1; Element.SHA1 := Signature; end Set_Signature; -- ------------------------------ -- Set the file size. If the new size is different, the FILE_MODIFIED -- flag is set on the file. -- ------------------------------ procedure Set_Size (Element : in File_Type; Size : in File_Size) is begin if Element.Size /= Size then Element.Size := Size; Element.Status := Element.Status or FILE_MODIFIED; end if; end Set_Size; -- ------------------------------ -- Set the owner and group of the file. -- ------------------------------ procedure Set_Owner (Element : in File_Type; User : in Uid_Type; Group : in Gid_Type) is begin Element.User := User; Element.Group := Group; end Set_Owner; -- ------------------------------ -- Set the file modification date. -- ------------------------------ procedure Set_Date (Element : in File_Type; Date : in Util.Systems.Types.Timespec) is begin Set_Date (Element, Ada.Calendar.Conversions.To_Ada_Time (Interfaces.C.long (Date.tv_sec))); end Set_Date; procedure Set_Date (Element : in File_Type; Date : in Ada.Calendar.Time) is use type Ada.Calendar.Time; begin if Element.Date /= Date then Element.Date := Date; Element.Status := Element.Status or FILE_MODIFIED; end if; end Set_Date; -- ------------------------------ -- Return the path for the file. -- ------------------------------ function Get_Path (Element : in File_Type) return String is begin if Element.Dir = null then return Element.Name; else return Util.Files.Compose (Get_Path (Element.Dir), Element.Name); end if; end Get_Path; -- ------------------------------ -- Return the path for the directory. -- ------------------------------ function Get_Path (Element : in Directory_Type) return String is begin return Ada.Strings.Unbounded.To_String (Element.Path); end Get_Path; -- ------------------------------ -- Return the SHA1 signature computed for the file. -- ------------------------------ function Get_SHA1 (Element : in File_Type) return String is begin return Hex_Encoder.Transform (Element.SHA1); end Get_SHA1; -- ------------------------------ -- Return the file size. -- ------------------------------ function Get_Size (Element : in File_Type) return File_Size is begin return Element.Size; end Get_Size; -- ------------------------------ -- Return the file modification date. -- ------------------------------ function Get_Date (Element : in File_Type) return Ada.Calendar.Time is begin return Element.Date; end Get_Date; -- ------------------------------ -- Return the user uid. -- ------------------------------ function Get_User (Element : in File_Type) return Uid_Type is begin return Element.User; end Get_User; -- ------------------------------ -- Return the group gid. -- ------------------------------ function Get_Group (Element : in File_Type) return Gid_Type is begin return Element.Group; end Get_Group; -- ------------------------------ -- Return the file unix mode. -- ------------------------------ function Get_Mode (Element : in File_Type) return File_Mode is begin return Element.Mode; end Get_Mode; -- ------------------------------ -- Add the file with the given name in the container. -- ------------------------------ overriding procedure Add_File (Into : in out Default_Container; Element : in File_Type) is begin Into.Files.Append (Element); end Add_File; -- ------------------------------ -- Add the directory with the given name in the container. -- ------------------------------ overriding procedure Add_Directory (Into : in out Default_Container; Element : in Directory_Type) is begin Into.Dirs.Append (Element); end Add_Directory; -- ------------------------------ -- Create a new file instance with the given name in the container. -- ------------------------------ overriding function Create (Into : in Default_Container; Name : in String) return File_Type is begin return Allocate (Name => Name, Dir => Into.Current); end Create; -- ------------------------------ -- Create a new directory instance with the given name in the container. -- ------------------------------ overriding function Create (Into : in Default_Container; Name : in String) return Directory_Type is begin return Allocate (Name => Name, Dir => Into.Current); end Create; -- ------------------------------ -- Find the file with the given name in this file container. -- Returns NO_FILE if the file was not found. -- ------------------------------ overriding function Find (From : in Default_Container; Name : in String) return File_Type is pragma Unreferenced (From, Name); begin return NO_FILE; end Find; -- ------------------------------ -- Find the directory with the given name in this file container. -- Returns NO_DIRECTORY if the directory was not found. -- ------------------------------ overriding function Find (From : in Default_Container; Name : in String) return Directory_Type is pragma Unreferenced (From, Name); begin return NO_DIRECTORY; end Find; -- ------------------------------ -- Set the directory object associated with the container. -- ------------------------------ procedure Set_Directory (Into : in out Default_Container; Directory : in Directory_Type) is begin Into.Current := Directory; Into.Files.Clear; Into.Dirs.Clear; end Set_Directory; -- ------------------------------ -- Execute the Process procedure on each directory found in the container. -- ------------------------------ overriding procedure Each_Directory (Container : in Default_Container; Process : not null access procedure (Dir : in Directory_Type)) is Iter : Directory_Vectors.Cursor := Container.Dirs.First; begin while Directory_Vectors.Has_Element (Iter) loop Process (Directory_Vectors.Element (Iter)); Directory_Vectors.Next (Iter); end loop; end Each_Directory; -- ------------------------------ -- Execute the Process procedure on each file found in the container. -- ------------------------------ overriding procedure Each_File (Container : in Default_Container; Process : not null access procedure (F : in File_Type)) is Iter : File_Vectors.Cursor := Container.Files.First; begin while File_Vectors.Has_Element (Iter) loop Process (File_Vectors.Element (Iter)); File_Vectors.Next (Iter); end loop; end Each_File; end Babel.Files;
-- bkp-files -- File and directories ----------------------------------------------------------------------- -- 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.Calendar.Conversions; with Interfaces.C; with Util.Log.Loggers; with Util.Files; with Util.Encoders.Base16; package body Babel.Files is Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("Bkp.Files"); Hex_Encoder : Util.Encoders.Base16.Encoder; -- ------------------------------ -- Compare two files on their name and directory. -- ------------------------------ function "<" (Left, Right : in File_Type) return Boolean is use type Ada.Strings.Unbounded.Unbounded_String; begin if Left = NO_FILE then return False; elsif Right = NO_FILE then return True; elsif Left.Dir = Right.Dir then return Left.Name < Right.Name; elsif Left.Dir = NO_DIRECTORY then return True; elsif Right.Dir = NO_DIRECTORY then return False; else return Left.Dir.Name.all < Right.Dir.Name.all; end if; end "<"; -- ------------------------------ -- Allocate a File_Type entry with the given name for the directory. -- ------------------------------ function Allocate (Name : in String; Dir : in Directory_Type) return File_Type is use Ada.Strings.Unbounded; Result : constant File_Type := new File '(Len => Name'Length, Id => NO_IDENTIFIER, Dir => Dir, Name => Name, others => <>); begin return Result; end Allocate; -- ------------------------------ -- Allocate a Directory_Type entry with the given name for the directory. -- ------------------------------ function Allocate (Name : in String; Dir : in Directory_Type) return Directory_Type is Path : String_Access; Result : constant Directory_Type := new Directory '(Id => NO_IDENTIFIER, Parent => Dir, others => <>); begin if Dir /= null then Path := new String '(Util.Files.Compose (Dir.Name.all, Name)); Result.Name_Pos := Dir.Name'Length + 1; else Path := new String '(Name); Result.Name_Pos := 1; end if; Result.Name := Path; return Result; end Allocate; -- ------------------------------ -- Return true if the file was modified and need a backup. -- ------------------------------ function Is_Modified (Element : in File_Type) return Boolean is use type ADO.Identifier; begin if Element.Id = NO_IDENTIFIER then return True; elsif (Element.Status and FILE_MODIFIED) /= 0 then return True; else return False; end if; end Is_Modified; -- ------------------------------ -- Return true if the file is a new file. -- ------------------------------ function Is_New (Element : in File_Type) return Boolean is use type ADO.Identifier; begin return Element.Id = NO_IDENTIFIER; end Is_New; -- ------------------------------ -- Set the file as modified. -- ------------------------------ procedure Set_Modified (Element : in File_Type) is begin Element.Status := Element.Status or FILE_MODIFIED; end Set_Modified; -- ------------------------------ -- Set the SHA1 signature that was computed for this file. -- If the computed signature is different from the current signature, -- the FILE_MODIFIED flag is set on the file. The FILE_HAS_SHA1 flag -- is set on the file. -- ------------------------------ procedure Set_Signature (Element : in File_Type; Signature : in Util.Encoders.SHA1.Hash_Array) is use type Util.Encoders.SHA1.Hash_Array; begin if (Element.Status and FILE_HAS_SHA1) /= 0 and then Element.SHA1 /= Signature then Element.Status := Element.Status or FILE_MODIFIED; end if; Element.Status := Element.Status or FILE_HAS_SHA1; Element.SHA1 := Signature; end Set_Signature; -- ------------------------------ -- Set the file size. If the new size is different, the FILE_MODIFIED -- flag is set on the file. -- ------------------------------ procedure Set_Size (Element : in File_Type; Size : in File_Size) is begin if Element.Size /= Size then Element.Size := Size; Element.Status := Element.Status or FILE_MODIFIED; end if; end Set_Size; -- ------------------------------ -- Set the owner and group of the file. -- ------------------------------ procedure Set_Owner (Element : in File_Type; User : in Uid_Type; Group : in Gid_Type) is begin Element.User := User; Element.Group := Group; end Set_Owner; -- ------------------------------ -- Set the file modification date. -- ------------------------------ procedure Set_Date (Element : in File_Type; Date : in Util.Systems.Types.Timespec) is begin Set_Date (Element, Ada.Calendar.Conversions.To_Ada_Time (Interfaces.C.long (Date.tv_sec))); end Set_Date; procedure Set_Date (Element : in File_Type; Date : in Ada.Calendar.Time) is use type Ada.Calendar.Time; begin if Element.Date /= Date then Element.Date := Date; Element.Status := Element.Status or FILE_MODIFIED; end if; end Set_Date; -- ------------------------------ -- Return the path for the file. -- ------------------------------ function Get_Path (Element : in File_Type) return String is begin if Element.Dir = null then return Element.Name; else return Util.Files.Compose (Get_Path (Element.Dir), Element.Name); end if; end Get_Path; -- ------------------------------ -- Return the path for the directory. -- ------------------------------ function Get_Path (Element : in Directory_Type) return String is begin return Element.Name.all; end Get_Path; -- ------------------------------ -- Return the SHA1 signature computed for the file. -- ------------------------------ function Get_SHA1 (Element : in File_Type) return String is begin return Hex_Encoder.Transform (Element.SHA1); end Get_SHA1; -- ------------------------------ -- Return the file size. -- ------------------------------ function Get_Size (Element : in File_Type) return File_Size is begin return Element.Size; end Get_Size; -- ------------------------------ -- Return the file modification date. -- ------------------------------ function Get_Date (Element : in File_Type) return Ada.Calendar.Time is begin return Element.Date; end Get_Date; -- ------------------------------ -- Return the user uid. -- ------------------------------ function Get_User (Element : in File_Type) return Uid_Type is begin return Element.User; end Get_User; -- ------------------------------ -- Return the group gid. -- ------------------------------ function Get_Group (Element : in File_Type) return Gid_Type is begin return Element.Group; end Get_Group; -- ------------------------------ -- Return the file unix mode. -- ------------------------------ function Get_Mode (Element : in File_Type) return File_Mode is begin return Element.Mode; end Get_Mode; -- ------------------------------ -- Add the file with the given name in the container. -- ------------------------------ overriding procedure Add_File (Into : in out Default_Container; Element : in File_Type) is begin Into.Files.Append (Element); end Add_File; -- ------------------------------ -- Add the directory with the given name in the container. -- ------------------------------ overriding procedure Add_Directory (Into : in out Default_Container; Element : in Directory_Type) is begin Into.Dirs.Append (Element); end Add_Directory; -- ------------------------------ -- Create a new file instance with the given name in the container. -- ------------------------------ overriding function Create (Into : in Default_Container; Name : in String) return File_Type is begin return Allocate (Name => Name, Dir => Into.Current); end Create; -- ------------------------------ -- Create a new directory instance with the given name in the container. -- ------------------------------ overriding function Create (Into : in Default_Container; Name : in String) return Directory_Type is begin return Allocate (Name => Name, Dir => Into.Current); end Create; -- ------------------------------ -- Find the file with the given name in this file container. -- Returns NO_FILE if the file was not found. -- ------------------------------ overriding function Find (From : in Default_Container; Name : in String) return File_Type is pragma Unreferenced (From, Name); begin return NO_FILE; end Find; -- ------------------------------ -- Find the directory with the given name in this file container. -- Returns NO_DIRECTORY if the directory was not found. -- ------------------------------ overriding function Find (From : in Default_Container; Name : in String) return Directory_Type is pragma Unreferenced (From, Name); begin return NO_DIRECTORY; end Find; -- ------------------------------ -- Set the directory object associated with the container. -- ------------------------------ procedure Set_Directory (Into : in out Default_Container; Directory : in Directory_Type) is begin Into.Current := Directory; Into.Files.Clear; Into.Dirs.Clear; end Set_Directory; -- ------------------------------ -- Execute the Process procedure on each directory found in the container. -- ------------------------------ overriding procedure Each_Directory (Container : in Default_Container; Process : not null access procedure (Dir : in Directory_Type)) is Iter : Directory_Vectors.Cursor := Container.Dirs.First; begin while Directory_Vectors.Has_Element (Iter) loop Process (Directory_Vectors.Element (Iter)); Directory_Vectors.Next (Iter); end loop; end Each_Directory; -- ------------------------------ -- Execute the Process procedure on each file found in the container. -- ------------------------------ overriding procedure Each_File (Container : in Default_Container; Process : not null access procedure (F : in File_Type)) is Iter : File_Vectors.Cursor := Container.Files.First; begin while File_Vectors.Has_Element (Iter) loop Process (File_Vectors.Element (Iter)); File_Vectors.Next (Iter); end loop; end Each_File; end Babel.Files;
Update the directory management to use the full path stored in the directory instance
Update the directory management to use the full path stored in the directory instance
Ada
apache-2.0
stcarrez/babel
bf608f8be0057e5a21c6541d9cf04f60d933b18b
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; -- ------------------------------ -- 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 (Memory : in out Target_Memory; Addr : in MAT.Types.Target_Addr; Slot : in Allocation) is begin Memory.Memory.Probe_Malloc (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 (Memory : in out Target_Memory; Addr : in MAT.Types.Target_Addr; Slot : in Allocation) is begin Memory.Memory.Probe_Free (Addr, Slot); end Probe_Free; -- ------------------------------ -- 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;
----------------------------------------------------------------------- -- 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; -- ------------------------------ -- 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 (Memory : in out Target_Memory; Addr : in MAT.Types.Target_Addr; Slot : in Allocation) is begin Memory.Memory.Probe_Malloc (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 (Memory : in out Target_Memory; Addr : in MAT.Types.Target_Addr; Slot : in Allocation) is begin Memory.Memory.Probe_Free (Addr, Slot); 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 (Memory : in out Target_Memory; Addr : in MAT.Types.Target_Addr; Old_Addr : in MAT.Types.Target_Addr; Slot : in Allocation) is begin Memory.Memory.Probe_Realloc (Addr, Old_Addr, Slot); end Probe_Realloc; -- ------------------------------ -- 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 the Probe_Free operation
Implement the Probe_Free operation
Ada
apache-2.0
stcarrez/mat,stcarrez/mat,stcarrez/mat
3cdaffcd7a117b74b9a747e0a9f16add04b58283
mat/src/mat-expressions.adb
mat/src/mat-expressions.adb
----------------------------------------------------------------------- -- mat-expressions -- Expressions for memory slot selection -- 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.Unchecked_Deallocation; with MAT.Types; with MAT.Memory; with MAT.Expressions.Parser; package body MAT.Expressions is procedure Free is new Ada.Unchecked_Deallocation (Object => Node_Type, Name => Node_Type_Access); -- Destroy recursively the node, releasing the storage. procedure Destroy (Node : in out Node_Type_Access); -- ------------------------------ -- Create a NOT expression node. -- ------------------------------ function Create_Not (Expr : in Expression_Type) return Expression_Type is Result : Expression_Type; begin Result.Node := new Node_Type'(Ref_Counter => Util.Concurrent.Counters.ONE, Kind => N_NOT, Expr => Expr.Node); Util.Concurrent.Counters.Increment (Expr.Node.Ref_Counter); return Result; end Create_Not; -- ------------------------------ -- Create a AND expression node. -- ------------------------------ function Create_And (Left : in Expression_Type; Right : in Expression_Type) return Expression_Type is Result : Expression_Type; begin Result.Node := new Node_Type'(Ref_Counter => Util.Concurrent.Counters.ONE, Kind => N_AND, Left => Left.Node, Right => Right.Node); Util.Concurrent.Counters.Increment (Left.Node.Ref_Counter); Util.Concurrent.Counters.Increment (Right.Node.Ref_Counter); return Result; end Create_And; -- ------------------------------ -- Create a OR expression node. -- ------------------------------ function Create_Or (Left : in Expression_Type; Right : in Expression_Type) return Expression_Type is Result : Expression_Type; begin Result.Node := new Node_Type'(Ref_Counter => Util.Concurrent.Counters.ONE, Kind => N_OR, Left => Left.Node, Right => Right.Node); Util.Concurrent.Counters.Increment (Left.Node.Ref_Counter); Util.Concurrent.Counters.Increment (Right.Node.Ref_Counter); return Result; end Create_Or; -- ------------------------------ -- Create an INSIDE expression node. -- ------------------------------ function Create_Inside (Name : in Ada.Strings.Unbounded.Unbounded_String; Kind : in Inside_Type) return Expression_Type is Result : Expression_Type; begin Result.Node := new Node_Type'(Ref_Counter => Util.Concurrent.Counters.ONE, Kind => N_INSIDE, Name => Name, Inside => Kind); return Result; end Create_Inside; -- ------------------------------ -- Create an size range expression node. -- ------------------------------ function Create_Size (Min : in MAT.Types.Target_Size; Max : in MAT.Types.Target_Size) return Expression_Type is Result : Expression_Type; begin Result.Node := new Node_Type'(Ref_Counter => Util.Concurrent.Counters.ONE, Kind => N_RANGE_SIZE, Min_Size => Min, Max_Size => Max); return Result; end Create_Size; -- ------------------------------ -- Create an addr range expression node. -- ------------------------------ function Create_Addr (Min : in MAT.Types.Target_Addr; Max : in MAT.Types.Target_Addr) return Expression_Type is Result : Expression_Type; begin Result.Node := new Node_Type'(Ref_Counter => Util.Concurrent.Counters.ONE, Kind => N_RANGE_ADDR, Min_Addr => Min, Max_Addr => Max); return Result; end Create_Addr; -- ------------------------------ -- Create an time range expression node. -- ------------------------------ function Create_Time (Min : in MAT.Types.Target_Tick_Ref; Max : in MAT.Types.Target_Tick_Ref) return Expression_Type is Result : Expression_Type; begin Result.Node := new Node_Type'(Ref_Counter => Util.Concurrent.Counters.ONE, Kind => N_RANGE_TIME, Min_Time => Min, Max_Time => Max); return Result; end Create_Time; -- ------------------------------ -- Evaluate the expression to check if the memory slot described by the -- context is selected. Returns True if the memory slot is selected. -- ------------------------------ function Is_Selected (Node : in Expression_Type; Addr : in MAT.Types.Target_Addr; Allocation : in MAT.Memory.Allocation) return Boolean is begin if Node.Node = null then return True; else return Is_Selected (Node.Node.all, Addr, Allocation); end if; end Is_Selected; -- ------------------------------ -- Evaluate the expression to check if the event described by the -- context is selected. Returns True if the event is selected. -- ------------------------------ function Is_Selected (Node : in Expression_Type; Event : in MAT.Events.Targets.Probe_Event_Type) return Boolean is begin return Is_Selected (Node.Node.all, Event); end Is_Selected; -- ------------------------------ -- Evaluate the node against the context. Returns True if the node expression -- selects the memory slot defined by the context. -- ------------------------------ function Is_Selected (Node : in Node_Type; Addr : in MAT.Types.Target_Addr; Allocation : in MAT.Memory.Allocation) return Boolean is use type MAT.Types.Target_Size; use type MAT.Types.Target_Tick_Ref; begin case Node.Kind is when N_NOT => return not Is_Selected (Node.Expr.all, Addr, Allocation); when N_AND => return Is_Selected (Node.Left.all, Addr, Allocation) and then Is_Selected (Node.Right.all, Addr, Allocation); when N_OR => return Is_Selected (Node.Left.all, Addr, Allocation) or else Is_Selected (Node.Right.all, Addr, Allocation); when N_RANGE_SIZE => return Allocation.Size >= Node.Min_Size and Allocation.Size <= Node.Max_Size; when N_RANGE_ADDR => return Addr >= Node.Min_Addr and Addr <= Node.Max_Addr; when N_RANGE_TIME => return Allocation.Time >= Node.Min_Time and Allocation.Time <= Node.Max_Time; when others => return False; end case; end Is_Selected; -- ------------------------------ -- Parse the string and return the expression tree. -- ------------------------------ function Parse (Expr : in String) return Expression_Type is begin return MAT.Expressions.Parser.Parse (Expr); end Parse; -- ------------------------------ -- Destroy recursively the node, releasing the storage. -- ------------------------------ procedure Destroy (Node : in out Node_Type_Access) is Release : Boolean; begin if Node /= null then Util.Concurrent.Counters.Decrement (Node.Ref_Counter, Release); case Node.Kind is when N_NOT => Destroy (Node.Expr); when N_AND | N_OR => Destroy (Node.Left); Destroy (Node.Right); when others => null; end case; if Release then Free (Node); else Node := null; end if; end if; end Destroy; -- ------------------------------ -- Release the reference and destroy the expression tree if it was the last reference. -- ------------------------------ overriding procedure Finalize (Obj : in out Expression_Type) is begin if Obj.Node /= null then Destroy (Obj.Node); end if; end Finalize; -- ------------------------------ -- Update the reference after an assignment. -- ------------------------------ overriding procedure Adjust (Obj : in out Expression_Type) is begin if Obj.Node /= null then Util.Concurrent.Counters.Increment (Obj.Node.Ref_Counter); end if; end Adjust; end MAT.Expressions;
----------------------------------------------------------------------- -- mat-expressions -- Expressions for memory slot selection -- 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.Unchecked_Deallocation; with MAT.Types; with MAT.Memory; with MAT.Expressions.Parser; package body MAT.Expressions is procedure Free is new Ada.Unchecked_Deallocation (Object => Node_Type, Name => Node_Type_Access); -- Destroy recursively the node, releasing the storage. procedure Destroy (Node : in out Node_Type_Access); -- ------------------------------ -- Create a NOT expression node. -- ------------------------------ function Create_Not (Expr : in Expression_Type) return Expression_Type is Result : Expression_Type; begin Result.Node := new Node_Type'(Ref_Counter => Util.Concurrent.Counters.ONE, Kind => N_NOT, Expr => Expr.Node); Util.Concurrent.Counters.Increment (Expr.Node.Ref_Counter); return Result; end Create_Not; -- ------------------------------ -- Create a AND expression node. -- ------------------------------ function Create_And (Left : in Expression_Type; Right : in Expression_Type) return Expression_Type is Result : Expression_Type; begin Result.Node := new Node_Type'(Ref_Counter => Util.Concurrent.Counters.ONE, Kind => N_AND, Left => Left.Node, Right => Right.Node); Util.Concurrent.Counters.Increment (Left.Node.Ref_Counter); Util.Concurrent.Counters.Increment (Right.Node.Ref_Counter); return Result; end Create_And; -- ------------------------------ -- Create a OR expression node. -- ------------------------------ function Create_Or (Left : in Expression_Type; Right : in Expression_Type) return Expression_Type is Result : Expression_Type; begin Result.Node := new Node_Type'(Ref_Counter => Util.Concurrent.Counters.ONE, Kind => N_OR, Left => Left.Node, Right => Right.Node); Util.Concurrent.Counters.Increment (Left.Node.Ref_Counter); Util.Concurrent.Counters.Increment (Right.Node.Ref_Counter); return Result; end Create_Or; -- ------------------------------ -- Create an INSIDE expression node. -- ------------------------------ function Create_Inside (Name : in Ada.Strings.Unbounded.Unbounded_String; Kind : in Inside_Type) return Expression_Type is Result : Expression_Type; begin Result.Node := new Node_Type'(Ref_Counter => Util.Concurrent.Counters.ONE, Kind => N_INSIDE, Name => Name, Inside => Kind); return Result; end Create_Inside; -- ------------------------------ -- Create an size range expression node. -- ------------------------------ function Create_Size (Min : in MAT.Types.Target_Size; Max : in MAT.Types.Target_Size) return Expression_Type is Result : Expression_Type; begin Result.Node := new Node_Type'(Ref_Counter => Util.Concurrent.Counters.ONE, Kind => N_RANGE_SIZE, Min_Size => Min, Max_Size => Max); return Result; end Create_Size; -- ------------------------------ -- Create an addr range expression node. -- ------------------------------ function Create_Addr (Min : in MAT.Types.Target_Addr; Max : in MAT.Types.Target_Addr) return Expression_Type is Result : Expression_Type; begin Result.Node := new Node_Type'(Ref_Counter => Util.Concurrent.Counters.ONE, Kind => N_RANGE_ADDR, Min_Addr => Min, Max_Addr => Max); return Result; end Create_Addr; -- ------------------------------ -- Create an time range expression node. -- ------------------------------ function Create_Time (Min : in MAT.Types.Target_Tick_Ref; Max : in MAT.Types.Target_Tick_Ref) return Expression_Type is Result : Expression_Type; begin Result.Node := new Node_Type'(Ref_Counter => Util.Concurrent.Counters.ONE, Kind => N_RANGE_TIME, Min_Time => Min, Max_Time => Max); return Result; end Create_Time; -- ------------------------------ -- Evaluate the expression to check if the memory slot described by the -- context is selected. Returns True if the memory slot is selected. -- ------------------------------ function Is_Selected (Node : in Expression_Type; Addr : in MAT.Types.Target_Addr; Allocation : in MAT.Memory.Allocation) return Boolean is begin if Node.Node = null then return True; else return Is_Selected (Node.Node.all, Addr, Allocation); end if; end Is_Selected; -- ------------------------------ -- Evaluate the expression to check if the event described by the -- context is selected. Returns True if the event is selected. -- ------------------------------ function Is_Selected (Node : in Expression_Type; Event : in MAT.Events.Targets.Probe_Event_Type) return Boolean is begin return Is_Selected (Node.Node.all, Event); end Is_Selected; -- ------------------------------ -- Evaluate the node against the context. Returns True if the node expression -- selects the memory slot defined by the context. -- ------------------------------ function Is_Selected (Node : in Node_Type; Addr : in MAT.Types.Target_Addr; Allocation : in MAT.Memory.Allocation) return Boolean is use type MAT.Types.Target_Size; use type MAT.Types.Target_Tick_Ref; begin case Node.Kind is when N_NOT => return not Is_Selected (Node.Expr.all, Addr, Allocation); when N_AND => return Is_Selected (Node.Left.all, Addr, Allocation) and then Is_Selected (Node.Right.all, Addr, Allocation); when N_OR => return Is_Selected (Node.Left.all, Addr, Allocation) or else Is_Selected (Node.Right.all, Addr, Allocation); when N_RANGE_SIZE => return Allocation.Size >= Node.Min_Size and Allocation.Size <= Node.Max_Size; when N_RANGE_ADDR => return Addr >= Node.Min_Addr and Addr <= Node.Max_Addr; when N_RANGE_TIME => return Allocation.Time >= Node.Min_Time and Allocation.Time <= Node.Max_Time; when others => return False; end case; end Is_Selected; -- ------------------------------ -- Evaluate the expression to check if the event described by the -- context is selected. Returns True if the event is selected. -- ------------------------------ function Is_Selected (Node : in Node_Type; Event : in MAT.Events.Targets.Probe_Event_Type) return Boolean is use type MAT.Types.Target_Size; use type MAT.Types.Target_Tick_Ref; begin case Node.Kind is when N_NOT => return not Is_Selected (Node.Expr.all, Event); when N_AND => return Is_Selected (Node.Left.all, Event) and then Is_Selected (Node.Right.all, Event); when N_OR => return Is_Selected (Node.Left.all, Event) or else Is_Selected (Node.Right.all, Event); when N_RANGE_SIZE => return Event.Size >= Node.Min_Size and Event.Size <= Node.Max_Size; when N_RANGE_ADDR => return Event.Addr >= Node.Min_Addr and Event.Addr <= Node.Max_Addr; when N_RANGE_TIME => return Event.Time >= Node.Min_Time and Event.Time <= Node.Max_Time; when others => return False; end case; end Is_Selected; -- ------------------------------ -- Parse the string and return the expression tree. -- ------------------------------ function Parse (Expr : in String) return Expression_Type is begin return MAT.Expressions.Parser.Parse (Expr); end Parse; -- ------------------------------ -- Destroy recursively the node, releasing the storage. -- ------------------------------ procedure Destroy (Node : in out Node_Type_Access) is Release : Boolean; begin if Node /= null then Util.Concurrent.Counters.Decrement (Node.Ref_Counter, Release); case Node.Kind is when N_NOT => Destroy (Node.Expr); when N_AND | N_OR => Destroy (Node.Left); Destroy (Node.Right); when others => null; end case; if Release then Free (Node); else Node := null; end if; end if; end Destroy; -- ------------------------------ -- Release the reference and destroy the expression tree if it was the last reference. -- ------------------------------ overriding procedure Finalize (Obj : in out Expression_Type) is begin if Obj.Node /= null then Destroy (Obj.Node); end if; end Finalize; -- ------------------------------ -- Update the reference after an assignment. -- ------------------------------ overriding procedure Adjust (Obj : in out Expression_Type) is begin if Obj.Node /= null then Util.Concurrent.Counters.Increment (Obj.Node.Ref_Counter); end if; end Adjust; end MAT.Expressions;
Implement the Is_Selected operation on the Node_Type
Implement the Is_Selected operation on the Node_Type
Ada
apache-2.0
stcarrez/mat,stcarrez/mat,stcarrez/mat
6aac57bb8c29ebefa27611473b03ff24b4c816f3
mat/src/mat-expressions.ads
mat/src/mat-expressions.ads
----------------------------------------------------------------------- -- mat-expressions -- Expressions for memory slot selection -- 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.Refs; with MAT.Types; with MAT.Memory; package MAT.Expressions is type Context_Type is record Addr : MAT.Types.Target_Addr; Allocation : MAT.Memory.Allocation; end record; type Kind_Type is (N_NOT, N_OR, N_AND, N_TRUE, N_FALSE, N_IN_FILE, N_IN_FILE_DIRECT, N_CALL_ADDR, N_CALL_ADDR_DIRECT, N_IN_FUNC, N_IN_FUNC_DIRECT, N_RANGE_SIZE, N_RANGE_ADDR, N_CONDITION, N_THREAD); type Expression_Type is tagged private; -- Create a NOT expression node. function Create_Not (Expr : in Expression_Type) return Expression_Type; -- Create a new expression node. function Create (Kindx : in Kind_Type; Expr : in Expression_Type) return Expression_Type; -- Evaluate the expression to check if the memory slot described by the -- context is selected. Returns True if the memory slot is selected. function Is_Selected (Node : in Expression_Type; Context : in Context_Type) return Boolean; private type Node_Type; type Node_Type_Access is access all Node_Type; type Node_Type (Kind : Kind_Type) is new Util.Refs.Ref_Entity with record case Kind is when N_NOT => Expr : Node_Type_Access; when N_OR | N_AND => Left, Right : Node_Type_Access; when N_IN_FILE | N_IN_FILE_DIRECT | N_IN_FUNC | N_IN_FUNC_DIRECT => Name : Ada.Strings.Unbounded.Unbounded_String; when N_RANGE_SIZE => Min_Size : MAT.Types.Target_Size; Max_Size : MAT.Types.Target_Size; when N_RANGE_ADDR | N_CALL_ADDR | N_CALL_ADDR_DIRECT => Min_Addr : MAT.Types.Target_Addr; Max_Addr : MAT.Types.Target_Addr; when N_THREAD => Thread : MAT.Types.Target_Thread_Ref; when others => null; end case; end record; function Is_Selected (Node : in Node_Type; Context : in Context_Type) return Boolean; package Node_Refs is new Util.Refs.Indefinite_References (Node_Type, Node_Type_Access); type Expression_Type is new Node_Refs.Ref with null record; end MAT.Expressions;
----------------------------------------------------------------------- -- mat-expressions -- Expressions for memory slot selection -- 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; private with Util.Concurrent.Counters; with MAT.Types; with MAT.Memory; package MAT.Expressions is type Context_Type is record Addr : MAT.Types.Target_Addr; Allocation : MAT.Memory.Allocation; end record; type Kind_Type is (N_NOT, N_OR, N_AND, N_TRUE, N_FALSE, N_IN_FILE, N_IN_FILE_DIRECT, N_CALL_ADDR, N_CALL_ADDR_DIRECT, N_IN_FUNC, N_IN_FUNC_DIRECT, N_RANGE_SIZE, N_RANGE_ADDR, N_CONDITION, N_THREAD); type Expression_Type is tagged private; -- Create a NOT expression node. function Create_Not (Expr : in Expression_Type) return Expression_Type; -- Create a new expression node. function Create (Kindx : in Kind_Type; Expr : in Expression_Type) return Expression_Type; -- Evaluate the expression to check if the memory slot described by the -- context is selected. Returns True if the memory slot is selected. function Is_Selected (Node : in Expression_Type; Context : in Context_Type) return Boolean; private type Node_Type; type Node_Type_Access is access all Node_Type; type Node_Type (Kind : Kind_Type) is record Ref_Counter : Util.Concurrent.Counters.Counter; case Kind is when N_NOT => Expr : Node_Type_Access; when N_OR | N_AND => Left, Right : Node_Type_Access; when N_IN_FILE | N_IN_FILE_DIRECT | N_IN_FUNC | N_IN_FUNC_DIRECT => Name : Ada.Strings.Unbounded.Unbounded_String; when N_RANGE_SIZE => Min_Size : MAT.Types.Target_Size; Max_Size : MAT.Types.Target_Size; when N_RANGE_ADDR | N_CALL_ADDR | N_CALL_ADDR_DIRECT => Min_Addr : MAT.Types.Target_Addr; Max_Addr : MAT.Types.Target_Addr; when N_THREAD => Thread : MAT.Types.Target_Thread_Ref; when others => null; end case; end record; function Is_Selected (Node : in Node_Type; Context : in Context_Type) return Boolean; type Expression_Type is tagged record Node : Node_Type_Access; end record; end MAT.Expressions;
Fix the definition of Expression_Type and Node_Type
Fix the definition of Expression_Type and Node_Type
Ada
apache-2.0
stcarrez/mat,stcarrez/mat,stcarrez/mat
4449440e9e2da6d2301111b3e8e22a7735ca6cbc
src/win32/win32.ads
src/win32/win32.ads
------------------------------------------------------------------------------- -- Copyright 2012 Julian Schutsch -- -- This file is part of ParallelSim -- -- ParallelSim is free software: you can redistribute it and/or modify -- it under the terms of the GNU Affero General Public License as published -- by the Free Software Foundation, either version 3 of the License, or -- (at your option) any later version. -- -- ParallelSim is distributed in the hope that it will be useful, -- but WITHOUT ANY WARRANTY; without even the implied warranty of -- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -- GNU Affero General Public License for more details. -- -- You should have received a copy of the GNU Affero General Public License -- along with ParallelSim. If not, see <http://www.gnu.org/licenses/>. ------------------------------------------------------------------------------- -- Revision History -- 18.Mar 2012 Julian Schutsch -- - Original version pragma Ada_2005; with Interfaces; with Interfaces.C; with Interfaces.C.Strings; with System; with Ada.Unchecked_Conversion; package Win32 is pragma Linker_Options ("-lgdi32"); pragma Linker_Options ("-lopengl32"); pragma Linker_Options ("-lglu32"); type UINT_Type is new Interfaces.Unsigned_32; type DWORD_Type is new Interfaces.Unsigned_32; type HANDLE_Type is new System.Address; type HANDLE_Access is access HANDLE_Type; type UINT_PTR_Type is new Interfaces.C.ptrdiff_t; subtype LONG_PTR_Type is System.Address; type LONG_Type is new Interfaces.C.ptrdiff_t; subtype ULONG_PTR_Type is System.Address; subtype HWND_Type is HANDLE_Type; type WPARAM_Type is new Interfaces.C.ptrdiff_t; subtype LPARAM_Type is LONG_PTR_Type; subtype HINSTANCE_Type is HANDLE_Type; subtype HICON_Type is HANDLE_Type; subtype HCURSOR_Type is HICON_Type; subtype HBRUSH_Type is HANDLE_Type; subtype LPCTSTR_Type is Interfaces.C.Strings.chars_ptr; type WORD_Type is new Interfaces.Unsigned_16; type ATOM_Type is new WORD_Type; subtype HMENU_Type is HANDLE_TYPE; type LRESULT_Type is new LONG_Type; subtype HDC_Type is HANDLE_Type; type BOOL_Type is new Interfaces.C.int; type BYTE_Type is new Interfaces.Unsigned_8; subtype HGLRC_Type is HANDLE_Type; function HANDLEToInteger is new Ada.Unchecked_Conversion (Source => HANDLE_Type, Target => Interfaces.C.ptrdiff_t); NULLHANDLE : constant HANDLE_Type:=HANDLE_Type(System.Null_Address); TRUE : constant BOOL_Type:=1; FALSE : constant BOOL_Type:=0; function MAKEINTRESOURCE (wInteger : WORD_Type) return LPCTSTR_Type; function GET_X_LPARAM (lParam : LPARAM_Type) return Integer; function GET_Y_LPARAM (lParam : LPARAM_Type) return Integer; function LOWORD (lParam : LPARAM_Type) return WORD_Type; function HIWORD (lParam : LPARAM_Type) return WORD_Type; CS_HREDRAW : constant UINT_Type:=2; CS_VREDRAW : constant UINT_Type:=1; CS_OWNDC : constant UINT_Type:=32; WS_OVERLAPPEDWINDOW : constant DWORD_Type:=16#cf0000#; WS_CLIPCHILDREN : constant DWORD_Type:=16#2000000#; WS_CLIPSIBLINGS : constant DWORD_Type:=16#4000000#; WS_EX_APPWINDOW : constant DWORD_Type:=16#40000#; WS_EX_CLIENTEDGE : constant DWORD_Type:=512; WM_MOUSELEAVE : constant := 16#2A3#; WM_PAINT : constant := 15; WM_CREATE : constant := 1; WM_SIZE : constant := 5; WM_SIZING : constant := 532; WM_LBUTTONDBLCLK : constant := 515; WM_RBUTTONDBLCLK : constant := 518; WM_LBUTTONDOWN : constant := 513; WM_LBUTTONUP : constant := 514; WM_RBUTTONDOWN : constant := 516; WM_RBUTTONUP : constant := 517; WM_MOUSEMOVE : constant := 512; WM_DESTROY : constant := 2; WM_ERASEBKGND : constant := 20; WM_KEYDOWN : constant := 256; WM_KEYUP : constant := 257; WM_CHAR : constant := 258; WM_TIMER : constant := 275; WM_QUIT : constant := 18; SW_SHOW : constant := 5; PM_NOREMOVE : constant := 0; PM_REMOVE : constant := 1; PM_NOYIELD : constant := 2; PFD_DRAW_TO_WINDOW : constant:=4; PFD_SUPPORT_OPENGL : constant:=16#20#; PFD_TYPE_RGBA : constant:=0; PFD_MAIN_PLANE : constant:=0; IDI_WINLOGO : constant:=32517; IDI_ASTERISK : constant:=32516; IDI_APPLICATION : constant:=32512; IDI_ERROR : constant:=32513; IDI_EXCLAMATION : constant:=32515; IDC_ARROW : constant:=32512; SW_SHOWNOACTIVATE : constant:=8; STILL_ACTIVE : constant DWORD_Type:=259; type WNDPROC_Access is access function (hWnd : HWND_Type; message : UINT_Type; wParam : WPARAM_Type; lParam : LPARAM_Type) return LRESULT_Type; pragma Convention(C,WNDPROC_Access); type WNDCLASS_Type is record style : UINT_Type := 0; lpfnWndProc : WNDPROC_Access := null; cbClsExtra : Interfaces.C.int := 0; cbWndExtra : Interfaces.C.int := 0; hInstance : HINSTANCE_Type := Win32.NULLHANDLE; hIcon : HICON_Type := Win32.NULLHANDLE; hCursor : HCURSOR_Type := Win32.NULLHANDLE; hbrBackground : HBRUSH_Type := Win32.NULLHANDLE; lpszMenuName : LPCTSTR_Type := Interfaces.C.Strings.Null_Ptr; lpszClassName : LPCTSTR_Type := Interfaces.C.Strings.Null_Ptr; end record; pragma Convention(C,WNDCLASS_Type); type CREATESTRUCT_Type is record lpCreateParams : System.Address:=System.Null_Address; hInstance : HINSTANCE_Type:=Win32.NULLHANDLE; hMenu : HMENU_Type:=Win32.NULLHANDLE; hwndParent : HWND_Type:=Win32.NULLHANDLE; cy : Interfaces.C.int:=0; cx : Interfaces.C.int:=0; y : Interfaces.C.int:=0; x : Interfaces.C.int:=0; style : LONG_Type:=0; lpszName : LPCTSTR_Type:=Interfaces.C.Strings.Null_Ptr; lpszClass : LPCTSTR_Type:=Interfaces.C.Strings.Null_Ptr; dwExStyle : DWORD_Type:=0; end record; type CREATESTRUCT_Access is access CREATESTRUCT_Type; pragma Convention(C,CREATESTRUCT_Type); type POINT_Type is record x : LONG_Type; y : LONG_Type; end record; type MSG_Type is record hwnd : HWND_Type; message : UINT_Type; wParam : UINT_Type; lParam : UINT_Type; time : DWORD_Type; pt : POINT_Type; end record; pragma Convention(C,MSG_Type); HANDLE_FLAG_INHERIT : constant DWORD_Type:=1; HANDLE_FLAG_PROTECT_FROM_CLOSE : constant DWORD_Type:=2; type COMMTIMEOUTS_Type is record ReadIntervalTimeout : DWORD_Type:=DWORD_Type'Last; ReadTotalTimeoutMultiplier : DWORD_Type:=0; ReadTotalTimeoutConstant : DWORD_Type:=0; WriteTotalTimeoutMultiplier : DWORD_Type:=0; WriteTotalTimeoutConstant : DWORD_Type:=0; end record; pragma Convention(C,COMMTIMEOUTS_Type); type SECURITY_ATTRIBUTES_Type is record nLength : DWORD_Type; lpSecurityDescriptor : System.Address:=System.Null_Address; bInheritHandle : BOOL_Type; end record; pragma Convention(C,SECURITY_ATTRIBUTES_Type); type SECURITY_ATTRIBUTES_Access is access SECURITY_ATTRIBUTES_Type; type OVERLAPPED_Type is record Internal : ULONG_PTR_Type := System.Null_Address; InternalHigh : ULONG_PTR_Type := System.Null_Address; Pointer : System.Address := System.Null_Address; hEvent : HANDLE_Type := NULLHANDLE; end record; pragma Convention(C,OVERLAPPED_Type); type PIXELFORMATDESCRIPTOR_Type is record nSize : WORD_Type := 0; nVersion : WORD_Type := 0; dwFlags : DWORD_Type := 0; iPixelType : BYTE_Type := 0; cColorBits : BYTE_Type := 0; cRedBits : BYTE_Type := 0; cRedShift : BYTE_Type := 0; cGreenBits : BYTE_Type := 0; cGreenShift : BYTE_Type := 0; cBlueBits : BYTE_Type := 0; cBlueShift : BYTE_Type := 0; cAlphaBits : BYTE_Type := 0; cAlphaShift : BYTE_Type := 0; cAccumBits : BYTE_Type := 0; cAccumRedBits : BYTE_Type := 0; cAccumGreenBits : BYTE_Type := 0; cAccumBlueBits : BYTE_Type := 0; cAccumAlphaBits : BYTE_Type := 0; cDepthBits : BYTE_Type := 0; cStencilBits : BYTE_Type := 0; cAuxBuffers : BYTE_Type := 0; iLayerType : BYTE_Type := 0; bReserved : BYTE_Type := 0; dwLayerMask : DWORD_Type := 0; dwVisibleMask : DWORD_Type := 0; dwDamageMask : DWORD_Type := 0; end record; pragma Convention(C,PIXELFORMATDESCRIPTOR_Type); type STARTUPINFO_Type is record cb : Interfaces.Unsigned_32; lpReserved : Interfaces.C.Strings.chars_ptr := Interfaces.C.Strings.Null_Ptr; lpDesktop : Interfaces.C.Strings.chars_ptr := Interfaces.C.Strings.Null_Ptr; lpTitle : Interfaces.C.Strings.chars_ptr := Interfaces.C.Strings.Null_Ptr; dwX : Interfaces.Unsigned_32 := 0; dwY : Interfaces.Unsigned_32 := 0; dwXSize : Interfaces.Unsigned_32 := 0; dwYSize : Interfaces.Unsigned_32 := 0; dwXCountChars : Interfaces.Unsigned_32 := 0; dwYCountChars : Interfaces.Unsigned_32 := 0; dwFillAttribute : Interfaces.Unsigned_32 := 0; dwFlags : Interfaces.Unsigned_32 := 0; wShowWindow : Interfaces.Unsigned_16 := 0; cbReserved2 : Interfaces.Unsigned_16 := 0; hStdInput : HANDLE_Type := NULLHANDLE; hStdOutput : HANDLE_Type := NULLHANDLE; hStderr : HANDLE_Type := NULLHANDLE; end record; pragma Convention(C,STARTUPINFO_Type); type PROCESS_INFORMATION_Type is record hProcess : HANDLE_Type := NULLHANDLE; hThread : HANDLE_Type := NULLHANDLE; dwProcessID : Interfaces.Unsigned_32 := 0; dwThreadID : Interfaces.Unsigned_32 := 0; end record; pragma Convention(C,PROCESS_INFORMATION_Type); function GetLastError return DWORD_TYPE; pragma Import(StdCall,GetLastError,"GetLastError"); STARTF_USESTDHANDLES : constant:=16#100#; end Win32;
------------------------------------------------------------------------------- -- Copyright 2012 Julian Schutsch -- -- This file is part of ParallelSim -- -- ParallelSim is free software: you can redistribute it and/or modify -- it under the terms of the GNU Affero General Public License as published -- by the Free Software Foundation, either version 3 of the License, or -- (at your option) any later version. -- -- ParallelSim is distributed in the hope that it will be useful, -- but WITHOUT ANY WARRANTY; without even the implied warranty of -- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -- GNU Affero General Public License for more details. -- -- You should have received a copy of the GNU Affero General Public License -- along with ParallelSim. If not, see <http://www.gnu.org/licenses/>. ------------------------------------------------------------------------------- -- Revision History -- 18.Mar 2012 Julian Schutsch -- - Original version pragma Ada_2005; with Interfaces; with Interfaces.C; with Interfaces.C.Strings; with System; with Ada.Unchecked_Conversion; package Win32 is type UINT_Type is new Interfaces.Unsigned_32; type DWORD_Type is new Interfaces.Unsigned_32; type HANDLE_Type is new System.Address; type HANDLE_Access is access HANDLE_Type; type UINT_PTR_Type is new Interfaces.C.ptrdiff_t; subtype LONG_PTR_Type is System.Address; type LONG_Type is new Interfaces.C.ptrdiff_t; subtype ULONG_PTR_Type is System.Address; subtype HWND_Type is HANDLE_Type; type WPARAM_Type is new Interfaces.C.ptrdiff_t; subtype LPARAM_Type is LONG_PTR_Type; subtype HINSTANCE_Type is HANDLE_Type; subtype HICON_Type is HANDLE_Type; subtype HCURSOR_Type is HICON_Type; subtype HBRUSH_Type is HANDLE_Type; subtype LPCTSTR_Type is Interfaces.C.Strings.chars_ptr; type WORD_Type is new Interfaces.Unsigned_16; type ATOM_Type is new WORD_Type; subtype HMENU_Type is HANDLE_TYPE; type LRESULT_Type is new LONG_Type; subtype HDC_Type is HANDLE_Type; type BOOL_Type is new Interfaces.C.int; type BYTE_Type is new Interfaces.Unsigned_8; subtype HGLRC_Type is HANDLE_Type; function HANDLEToInteger is new Ada.Unchecked_Conversion (Source => HANDLE_Type, Target => Interfaces.C.ptrdiff_t); NULLHANDLE : constant HANDLE_Type:=HANDLE_Type(System.Null_Address); TRUE : constant BOOL_Type:=1; FALSE : constant BOOL_Type:=0; function MAKEINTRESOURCE (wInteger : WORD_Type) return LPCTSTR_Type; function GET_X_LPARAM (lParam : LPARAM_Type) return Integer; function GET_Y_LPARAM (lParam : LPARAM_Type) return Integer; function LOWORD (lParam : LPARAM_Type) return WORD_Type; function HIWORD (lParam : LPARAM_Type) return WORD_Type; CS_HREDRAW : constant UINT_Type:=2; CS_VREDRAW : constant UINT_Type:=1; CS_OWNDC : constant UINT_Type:=32; WS_OVERLAPPEDWINDOW : constant DWORD_Type:=16#cf0000#; WS_CLIPCHILDREN : constant DWORD_Type:=16#2000000#; WS_CLIPSIBLINGS : constant DWORD_Type:=16#4000000#; WS_EX_APPWINDOW : constant DWORD_Type:=16#40000#; WS_EX_CLIENTEDGE : constant DWORD_Type:=512; WM_MOUSELEAVE : constant := 16#2A3#; WM_PAINT : constant := 15; WM_CREATE : constant := 1; WM_SIZE : constant := 5; WM_SIZING : constant := 532; WM_LBUTTONDBLCLK : constant := 515; WM_RBUTTONDBLCLK : constant := 518; WM_LBUTTONDOWN : constant := 513; WM_LBUTTONUP : constant := 514; WM_RBUTTONDOWN : constant := 516; WM_RBUTTONUP : constant := 517; WM_MOUSEMOVE : constant := 512; WM_DESTROY : constant := 2; WM_ERASEBKGND : constant := 20; WM_KEYDOWN : constant := 256; WM_KEYUP : constant := 257; WM_CHAR : constant := 258; WM_TIMER : constant := 275; WM_QUIT : constant := 18; SW_SHOW : constant := 5; PM_NOREMOVE : constant := 0; PM_REMOVE : constant := 1; PM_NOYIELD : constant := 2; PFD_DRAW_TO_WINDOW : constant:=4; PFD_SUPPORT_OPENGL : constant:=16#20#; PFD_TYPE_RGBA : constant:=0; PFD_MAIN_PLANE : constant:=0; IDI_WINLOGO : constant:=32517; IDI_ASTERISK : constant:=32516; IDI_APPLICATION : constant:=32512; IDI_ERROR : constant:=32513; IDI_EXCLAMATION : constant:=32515; IDC_ARROW : constant:=32512; SW_SHOWNOACTIVATE : constant:=8; STILL_ACTIVE : constant DWORD_Type:=259; type WNDPROC_Access is access function (hWnd : HWND_Type; message : UINT_Type; wParam : WPARAM_Type; lParam : LPARAM_Type) return LRESULT_Type; pragma Convention(C,WNDPROC_Access); type WNDCLASS_Type is record style : UINT_Type := 0; lpfnWndProc : WNDPROC_Access := null; cbClsExtra : Interfaces.C.int := 0; cbWndExtra : Interfaces.C.int := 0; hInstance : HINSTANCE_Type := Win32.NULLHANDLE; hIcon : HICON_Type := Win32.NULLHANDLE; hCursor : HCURSOR_Type := Win32.NULLHANDLE; hbrBackground : HBRUSH_Type := Win32.NULLHANDLE; lpszMenuName : LPCTSTR_Type := Interfaces.C.Strings.Null_Ptr; lpszClassName : LPCTSTR_Type := Interfaces.C.Strings.Null_Ptr; end record; pragma Convention(C,WNDCLASS_Type); type CREATESTRUCT_Type is record lpCreateParams : System.Address:=System.Null_Address; hInstance : HINSTANCE_Type:=Win32.NULLHANDLE; hMenu : HMENU_Type:=Win32.NULLHANDLE; hwndParent : HWND_Type:=Win32.NULLHANDLE; cy : Interfaces.C.int:=0; cx : Interfaces.C.int:=0; y : Interfaces.C.int:=0; x : Interfaces.C.int:=0; style : LONG_Type:=0; lpszName : LPCTSTR_Type:=Interfaces.C.Strings.Null_Ptr; lpszClass : LPCTSTR_Type:=Interfaces.C.Strings.Null_Ptr; dwExStyle : DWORD_Type:=0; end record; type CREATESTRUCT_Access is access CREATESTRUCT_Type; pragma Convention(C,CREATESTRUCT_Type); type POINT_Type is record x : LONG_Type; y : LONG_Type; end record; type MSG_Type is record hwnd : HWND_Type; message : UINT_Type; wParam : UINT_Type; lParam : UINT_Type; time : DWORD_Type; pt : POINT_Type; end record; pragma Convention(C,MSG_Type); HANDLE_FLAG_INHERIT : constant DWORD_Type:=1; HANDLE_FLAG_PROTECT_FROM_CLOSE : constant DWORD_Type:=2; type COMMTIMEOUTS_Type is record ReadIntervalTimeout : DWORD_Type:=DWORD_Type'Last; ReadTotalTimeoutMultiplier : DWORD_Type:=0; ReadTotalTimeoutConstant : DWORD_Type:=0; WriteTotalTimeoutMultiplier : DWORD_Type:=0; WriteTotalTimeoutConstant : DWORD_Type:=0; end record; pragma Convention(C,COMMTIMEOUTS_Type); type SECURITY_ATTRIBUTES_Type is record nLength : DWORD_Type; lpSecurityDescriptor : System.Address:=System.Null_Address; bInheritHandle : BOOL_Type; end record; pragma Convention(C,SECURITY_ATTRIBUTES_Type); type SECURITY_ATTRIBUTES_Access is access SECURITY_ATTRIBUTES_Type; type OVERLAPPED_Type is record Internal : ULONG_PTR_Type := System.Null_Address; InternalHigh : ULONG_PTR_Type := System.Null_Address; Pointer : System.Address := System.Null_Address; hEvent : HANDLE_Type := NULLHANDLE; end record; pragma Convention(C,OVERLAPPED_Type); type PIXELFORMATDESCRIPTOR_Type is record nSize : WORD_Type := 0; nVersion : WORD_Type := 0; dwFlags : DWORD_Type := 0; iPixelType : BYTE_Type := 0; cColorBits : BYTE_Type := 0; cRedBits : BYTE_Type := 0; cRedShift : BYTE_Type := 0; cGreenBits : BYTE_Type := 0; cGreenShift : BYTE_Type := 0; cBlueBits : BYTE_Type := 0; cBlueShift : BYTE_Type := 0; cAlphaBits : BYTE_Type := 0; cAlphaShift : BYTE_Type := 0; cAccumBits : BYTE_Type := 0; cAccumRedBits : BYTE_Type := 0; cAccumGreenBits : BYTE_Type := 0; cAccumBlueBits : BYTE_Type := 0; cAccumAlphaBits : BYTE_Type := 0; cDepthBits : BYTE_Type := 0; cStencilBits : BYTE_Type := 0; cAuxBuffers : BYTE_Type := 0; iLayerType : BYTE_Type := 0; bReserved : BYTE_Type := 0; dwLayerMask : DWORD_Type := 0; dwVisibleMask : DWORD_Type := 0; dwDamageMask : DWORD_Type := 0; end record; pragma Convention(C,PIXELFORMATDESCRIPTOR_Type); type STARTUPINFO_Type is record cb : Interfaces.Unsigned_32; lpReserved : Interfaces.C.Strings.chars_ptr := Interfaces.C.Strings.Null_Ptr; lpDesktop : Interfaces.C.Strings.chars_ptr := Interfaces.C.Strings.Null_Ptr; lpTitle : Interfaces.C.Strings.chars_ptr := Interfaces.C.Strings.Null_Ptr; dwX : Interfaces.Unsigned_32 := 0; dwY : Interfaces.Unsigned_32 := 0; dwXSize : Interfaces.Unsigned_32 := 0; dwYSize : Interfaces.Unsigned_32 := 0; dwXCountChars : Interfaces.Unsigned_32 := 0; dwYCountChars : Interfaces.Unsigned_32 := 0; dwFillAttribute : Interfaces.Unsigned_32 := 0; dwFlags : Interfaces.Unsigned_32 := 0; wShowWindow : Interfaces.Unsigned_16 := 0; cbReserved2 : Interfaces.Unsigned_16 := 0; hStdInput : HANDLE_Type := NULLHANDLE; hStdOutput : HANDLE_Type := NULLHANDLE; hStderr : HANDLE_Type := NULLHANDLE; end record; pragma Convention(C,STARTUPINFO_Type); type PROCESS_INFORMATION_Type is record hProcess : HANDLE_Type := NULLHANDLE; hThread : HANDLE_Type := NULLHANDLE; dwProcessID : Interfaces.Unsigned_32 := 0; dwThreadID : Interfaces.Unsigned_32 := 0; end record; pragma Convention(C,PROCESS_INFORMATION_Type); function GetLastError return DWORD_TYPE; pragma Import(StdCall,GetLastError,"GetLastError"); STARTF_USESTDHANDLES : constant:=16#100#; end Win32;
Revert "add linker_options pragmas for opengl/win"
Revert "add linker_options pragmas for opengl/win" This reverts commit 9d9a7ac0322c82a56675e0a87a8ea5215e554425.
Ada
isc
darkestkhan/lumen2,darkestkhan/lumen
d1620b9dbcaf339e879416ae1798847dd04b3372
src/wiki-nodes.ads
src/wiki-nodes.ads
----------------------------------------------------------------------- -- wiki-nodes -- Wiki Document Internal representation -- Copyright (C) 2016, 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 Wiki.Attributes; with Wiki.Strings; package Wiki.Nodes is pragma Preelaborate; type Node_Kind is (N_LINE_BREAK, N_HORIZONTAL_RULE, N_TOC_DISPLAY, N_PARAGRAPH, N_NEWLINE, N_HEADER, N_TOC, N_TOC_ENTRY, N_BLOCKQUOTE, N_QUOTE, N_TAG_START, N_PREFORMAT, N_LIST, N_NUM_LIST, N_INDENT, N_TEXT, N_LINK, N_IMAGE); -- Node kinds which are simple markers in the document. subtype Simple_Node_Kind is Node_Kind range N_LINE_BREAK .. N_NEWLINE; type Node_List is limited private; type Node_List_Access is access all Node_List; type Node_Type; type Node_Type_Access is access all Node_Type; type Node_Type (Kind : Node_Kind; Len : Natural) is limited record case Kind is when N_HEADER | N_BLOCKQUOTE | N_INDENT | N_LIST | N_NUM_LIST | N_TOC_ENTRY => Level : Natural := 0; Header : Wiki.Strings.WString (1 .. Len); when N_TEXT => Format : Format_Map; Text : Wiki.Strings.WString (1 .. Len); when N_LINK | N_IMAGE | N_QUOTE => Link_Attr : Wiki.Attributes.Attribute_List; Title : Wiki.Strings.WString (1 .. Len); when N_TAG_START => Tag_Start : Html_Tag; Attributes : Wiki.Attributes.Attribute_List; Children : Node_List_Access; Parent : Node_Type_Access; when N_PREFORMAT => Preformatted : Wiki.Strings.WString (1 .. Len); when N_TOC => Entries : Node_List_Access; when others => null; end case; end record; -- Append a node to the tag node. procedure Append (Into : in Node_Type_Access; Node : in Node_Type_Access); -- Append a node to the document. procedure Append (Into : in out Node_List; Node : in Node_Type_Access); -- Finalize the node list to release the allocated memory. procedure Finalize (List : in out Node_List); private NODE_LIST_BLOCK_SIZE : constant Positive := 16; type Node_Array is array (Positive range <>) of Node_Type_Access; type Node_List_Block; type Node_List_Block_Access is access all Node_List_Block; type Node_List_Block (Max : Positive) is limited record Next : Node_List_Block_Access; Last : Natural := 0; List : Node_Array (1 .. Max); end record; type Node_List is limited record Current : Node_List_Block_Access; Length : Natural := 0; First : aliased Node_List_Block (NODE_LIST_BLOCK_SIZE); end record; end Wiki.Nodes;
----------------------------------------------------------------------- -- wiki-nodes -- Wiki Document Internal representation -- Copyright (C) 2016, 2019, 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 Wiki.Attributes; with Wiki.Strings; package Wiki.Nodes is pragma Preelaborate; type Node_Kind is (N_LINE_BREAK, N_HORIZONTAL_RULE, N_TOC_DISPLAY, N_PARAGRAPH, N_NEWLINE, N_HEADER, N_TOC, N_TOC_ENTRY, N_BLOCKQUOTE, N_QUOTE, N_TAG_START, N_PREFORMAT, N_LIST, N_NUM_LIST, N_INDENT, N_TEXT, N_LINK, N_IMAGE); -- Node kinds which are simple markers in the document. subtype Simple_Node_Kind is Node_Kind range N_LINE_BREAK .. N_NEWLINE; type Node_List is limited private; type Node_List_Access is access all Node_List; type Node_Type; type Node_Type_Access is access all Node_Type; type Node_Type (Kind : Node_Kind; Len : Natural) is limited record case Kind is when N_HEADER | N_BLOCKQUOTE | N_INDENT | N_LIST | N_NUM_LIST | N_TOC_ENTRY => Level : Natural := 0; Header : Wiki.Strings.WString (1 .. Len); when N_TEXT => Format : Format_Map; Text : Wiki.Strings.WString (1 .. Len); when N_LINK | N_IMAGE | N_QUOTE => Link_Attr : Wiki.Attributes.Attribute_List; Title : Wiki.Strings.WString (1 .. Len); when N_TAG_START => Tag_Start : Html_Tag; Attributes : Wiki.Attributes.Attribute_List; Children : Node_List_Access; Parent : Node_Type_Access; when N_PREFORMAT => Language : Wiki.Strings.UString; Preformatted : Wiki.Strings.WString (1 .. Len); when N_TOC => Entries : Node_List_Access; when others => null; end case; end record; -- Append a node to the tag node. procedure Append (Into : in Node_Type_Access; Node : in Node_Type_Access); -- Append a node to the document. procedure Append (Into : in out Node_List; Node : in Node_Type_Access); -- Finalize the node list to release the allocated memory. procedure Finalize (List : in out Node_List); private NODE_LIST_BLOCK_SIZE : constant Positive := 16; type Node_Array is array (Positive range <>) of Node_Type_Access; type Node_List_Block; type Node_List_Block_Access is access all Node_List_Block; type Node_List_Block (Max : Positive) is limited record Next : Node_List_Block_Access; Last : Natural := 0; List : Node_Array (1 .. Max); end record; type Node_List is limited record Current : Node_List_Block_Access; Length : Natural := 0; First : aliased Node_List_Block (NODE_LIST_BLOCK_SIZE); end record; end Wiki.Nodes;
Add Language record member for the pre-formatted node
Add Language record member for the pre-formatted node
Ada
apache-2.0
stcarrez/ada-wiki,stcarrez/ada-wiki
4da473ab82633279d9a2fc71fccde135ef918a61
regtests/util-dates-formats-tests.ads
regtests/util-dates-formats-tests.ads
----------------------------------------------------------------------- -- util-dates-formats-tests - Test for date formats -- Copyright (C) 2011, 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.Tests; package Util.Dates.Formats.Tests is procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite); type Test is new Util.Tests.Test with null record; procedure Test_Format (T : in out Test); -- Test the Get_Day_Start operation. procedure Test_Get_Day_Start (T : in out Test); -- Test the Get_Week_Start operation. procedure Test_Get_Week_Start (T : in out Test); -- Test the Get_Month_Start operation. procedure Test_Get_Month_Start (T : in out Test); -- Test the Get_Day_End operation. procedure Test_Get_Day_End (T : in out Test); -- Test the Get_Week_End operation. procedure Test_Get_Week_End (T : in out Test); -- Test the Get_Month_End operation. procedure Test_Get_Month_End (T : in out Test); -- Test the Split operation. procedure Test_Split (T : in out Test); -- Test the Append_Date operation procedure Test_Append_Date (T : in out Test); end Util.Dates.Formats.Tests;
----------------------------------------------------------------------- -- util-dates-formats-tests - Test for date formats -- Copyright (C) 2011, 2013, 2014, 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 Util.Tests; package Util.Dates.Formats.Tests is procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite); type Test is new Util.Tests.Test with null record; procedure Test_Format (T : in out Test); -- Test the Get_Day_Start operation. procedure Test_Get_Day_Start (T : in out Test); -- Test the Get_Week_Start operation. procedure Test_Get_Week_Start (T : in out Test); -- Test the Get_Month_Start operation. procedure Test_Get_Month_Start (T : in out Test); -- Test the Get_Day_End operation. procedure Test_Get_Day_End (T : in out Test); -- Test the Get_Week_End operation. procedure Test_Get_Week_End (T : in out Test); -- Test the Get_Month_End operation. procedure Test_Get_Month_End (T : in out Test); -- Test the Split operation. procedure Test_Split (T : in out Test); -- Test the Append_Date operation procedure Test_Append_Date (T : in out Test); -- Test the ISO8601 operations. procedure Test_ISO8601 (T : in out Test); end Util.Dates.Formats.Tests;
Declare Test_ISO8601 procedure
Declare Test_ISO8601 procedure
Ada
apache-2.0
stcarrez/ada-util,stcarrez/ada-util
efd4d3d20990dff98ecef870bfb3604f1795a794
regtests/security-random-tests.ads
regtests/security-random-tests.ads
----------------------------------------------------------------------- -- security-random-tests - Tests for random package -- 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 Util.Strings.Maps; with Util.Tests; package Security.Random.Tests is procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite); type Test is new Util.Tests.Test with null record; procedure Test_Generate (T : in out Test); end Security.Random.Tests;
----------------------------------------------------------------------- -- security-random-tests - Tests for random package -- 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 Util.Tests; package Security.Random.Tests is procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite); type Test is new Util.Tests.Test with null record; procedure Test_Generate (T : in out Test); end Security.Random.Tests;
Remove unused with clause
Remove unused with clause
Ada
apache-2.0
stcarrez/ada-security
97a6b76f387c784a722789889f59ecbde08b963d
regtests/babel-base-users-tests.adb
regtests/babel-base-users-tests.adb
----------------------------------------------------------------------- -- babel-base-users-tests - Unit tests for babel users -- 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; package body Babel.Base.Users.Tests is use type Util.Strings.Name_Access; package Caller is new Util.Test_Caller (Test, "Base.Users"); procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is begin Caller.Add_Test (Suite, "Test Babel.Base.Users.Find", Test_Find'Access); end Add_Tests; -- ------------------------------ -- Test the Find function resolving some existing user. -- ------------------------------ procedure Test_Find (T : in out Test) is Db : Babel.Base.Users.Database; User : User_Type; begin User := Db.Find (0, 0); T.Assert (User.Name /= null, "User uid=0 was not found"); T.Assert (User.Group /= null, "User gid=0 was not found"); Util.Tests.Assert_Equals (T, "root", User.Name.all, "Invalid root user name"); Util.Tests.Assert_Equals (T, "root", User.Group.all, "Invalid root group name"); end Test_Find; end Babel.Base.Users.Tests;
----------------------------------------------------------------------- -- babel-base-users-tests - Unit tests for babel users -- 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; package body Babel.Base.Users.Tests is use type Util.Strings.Name_Access; package Caller is new Util.Test_Caller (Test, "Base.Users"); procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is begin Caller.Add_Test (Suite, "Test Babel.Base.Users.Find", Test_Find'Access); end Add_Tests; -- ------------------------------ -- Test the Find function resolving some existing user. -- ------------------------------ procedure Test_Find (T : in out Test) is Db : Babel.Base.Users.Database; User : User_Type; begin User := Db.Find (0, 0); T.Assert (User.Name /= null, "User uid=0 was not found"); T.Assert (User.Group /= null, "User gid=0 was not found"); Util.Tests.Assert_Equals (T, "root", User.Name.all, "Invalid root user name"); Util.Tests.Assert_Equals (T, "root", User.Group.all, "Invalid root group name"); User := Db.Find ("bin", "daemon"); T.Assert (User.Name /= null, "User bin was not found"); T.Assert (User.Group /= null, "Group daemon was not found"); Util.Tests.Assert_Equals (T, "bin", User.Name.all, "Invalid 'bin' user name"); Util.Tests.Assert_Equals (T, "daemon", User.Group.all, "Invalid 'daemon' group name"); T.Assert (User.Uid > 0, "Invalid 'bin' uid"); T.Assert (User.Gid > 0, "Invalid 'daemon' gid"); end Test_Find; end Babel.Base.Users.Tests;
Add more test case for the Find operation
Add more test case for the Find operation
Ada
apache-2.0
stcarrez/babel
d2607bb61e1921545d9bbdf9ef8100e520c72730
src/asf-components-utils-escapes.ads
src/asf-components-utils-escapes.ads
----------------------------------------------------------------------- -- components-utils-escape -- Escape generated content produced by component children -- 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.Components.Core; with ASF.Contexts.Faces; with ASF.Contexts.Writer; package ASF.Components.Utils.Escapes is -- ------------------------------ -- UIEscape -- ------------------------------ -- The <b>UIEscape</b> component catches the rendering of child components to -- perform specific escape actions on the content. type UIEscape is new ASF.Components.Core.UIComponentBase with private; -- 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); -- Encode the children components in a local buffer. overriding procedure Encode_Children (UI : in UIEscape; Context : in out ASF.Contexts.Faces.Faces_Context'Class); private type UIEscape is new ASF.Components.Core.UIComponentBase with null record; 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 ASF.Components.Core; with ASF.Contexts.Faces; with ASF.Contexts.Writer; package ASF.Components.Utils.Escapes is -- Name of the attribute that control the escape mode. -- When the attribute is set to 'xml', the content is escaped using XML -- escape rules. Otherwise, the content is escaped using Javascript rules. ESCAPE_MODE_NAME : constant String := "mode"; -- ------------------------------ -- UIEscape -- ------------------------------ -- The <b>UIEscape</b> component catches the rendering of child components to -- perform specific escape actions on the content. type UIEscape is new ASF.Components.Core.UIComponentBase with private; -- 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); -- Encode the children components in a local buffer. overriding procedure Encode_Children (UI : in UIEscape; Context : in out ASF.Contexts.Faces.Faces_Context'Class); private type UIEscape is new ASF.Components.Core.UIComponentBase with null record; end ASF.Components.Utils.Escapes;
Define ESCAPE_MODE_NAME to allow escaping using XML or Javascript rules
Define ESCAPE_MODE_NAME to allow escaping using XML or Javascript rules
Ada
apache-2.0
stcarrez/ada-asf,stcarrez/ada-asf,stcarrez/ada-asf
af48226a2df9ff07016ffd8e8fe4351f4add5d25
samples/print_user.adb
samples/print_user.adb
----------------------------------------------------------------------- -- Print_User -- Example to find an object from the database -- 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 ADO; with ADO.Drivers; with ADO.Sessions; with ADO.SQL; with ADO.Sessions.Factory; with Samples.User.Model; with Util.Log.Loggers; with Ada.Text_IO; with Ada.Command_Line; procedure Print_User is use ADO; use Ada; use Samples.User.Model; Factory : ADO.Sessions.Factory.Session_Factory; User : User_Ref; begin Util.Log.Loggers.Initialize ("log4j.properties"); if Ada.Command_Line.Argument_Count < 2 then Ada.Text_IO.Put_Line ("Usage: print_user connection user-name ..."); Ada.Text_IO.Put_Line ("Example: print_user 'mysql://localhost:3306/ado_test?user=root' joe"); Ada.Command_Line.Set_Exit_Status (2); return; end if; -- Initialize the database drivers. ADO.Drivers.Initialize; -- Create and configure the connection pool Factory.Create (Ada.Command_Line.Argument (1)); declare Session : ADO.Sessions.Session := Factory.Get_Session; Found : Boolean; begin for I in 2 .. Ada.Command_Line.Argument_Count loop declare User_Name : constant String := Ada.Command_Line.Argument (I); Query : ADO.SQL.Query; begin Ada.Text_IO.Put_Line ("Searching '" & User_Name & "'..."); Query.Bind_Param (1, User_Name); Query.Set_Filter ("name = ?"); User.Find (Session => Session, Query => Query, Found => Found); if Found then Ada.Text_IO.Put_Line (" Id : " & Identifier'Image (User.Get_Id)); Ada.Text_IO.Put_Line (" User : " & User.Get_Name); Ada.Text_IO.Put_Line (" Email : " & User.Get_Email); else Ada.Text_IO.Put_Line (" User '" & User_Name & "' does not exist"); end if; end; end loop; end; end Print_User;
----------------------------------------------------------------------- -- Print_User -- Example to find an object from the database -- 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 ADO; with ADO.Drivers; with ADO.Sessions; with ADO.SQL; with ADO.Sessions.Factory; with Samples.User.Model; with Util.Log.Loggers; with Ada.Text_IO; with Ada.Command_Line; procedure Print_User is use ADO; use Ada; use Samples.User.Model; Factory : ADO.Sessions.Factory.Session_Factory; begin Util.Log.Loggers.Initialize ("samples.properties"); -- Initialize the database drivers. ADO.Drivers.Initialize ("samples.properties"); if Ada.Command_Line.Argument_Count < 1 then Ada.Text_IO.Put_Line ("Usage: print_user user-name ..."); Ada.Text_IO.Put_Line ("Example: print_user joe"); Ada.Command_Line.Set_Exit_Status (2); return; end if; -- Create and configure the connection pool Factory.Create (ADO.Drivers.Get_Config ("ado.database")); declare Session : ADO.Sessions.Session := Factory.Get_Session; User : User_Ref; Found : Boolean; begin for I in 1 .. Ada.Command_Line.Argument_Count loop declare User_Name : constant String := Ada.Command_Line.Argument (I); Query : ADO.SQL.Query; begin Ada.Text_IO.Put_Line ("Searching '" & User_Name & "'..."); Query.Bind_Param (1, User_Name); Query.Set_Filter ("name = ?"); User.Find (Session => Session, Query => Query, Found => Found); if Found then Ada.Text_IO.Put_Line (" Id : " & Identifier'Image (User.Get_Id)); Ada.Text_IO.Put_Line (" User : " & User.Get_Name); Ada.Text_IO.Put_Line (" Email : " & User.Get_Email); else Ada.Text_IO.Put_Line (" User '" & User_Name & "' does not exist"); end if; end; end loop; end; end Print_User;
Update the print example
Update the print example
Ada
apache-2.0
stcarrez/ada-ado
d7aff9baf25828cf5dff38a8818e7a1e969c4a72
testcases/spawn_fields/spawn_fields.adb
testcases/spawn_fields/spawn_fields.adb
with AdaBase.Results.Field; with Ada.Strings.Unbounded; with Ada.Integer_Text_IO; with Ada.Text_IO; with Ada.Wide_Text_IO; procedure Spawn_Fields is package TIO renames Ada.Text_IO; package WIO renames Ada.Wide_Text_IO; package IIO renames Ada.Integer_Text_IO; package SU renames Ada.Strings.Unbounded; package ARC renames AdaBase.Results; FA : ARC.Field.field_access := ARC.Field.spawn_field (binob => (50, 15, 4, 8)); BR : ARC.Field.field_access := ARC.Field.spawn_field (data => (datatype => AdaBase.ft_textual, v13 => SU.To_Unbounded_String ("Baltimore Ravens"))); myset : ARC.settype (1 .. 3) := ((enumeration => SU.To_Unbounded_String ("hockey")), (enumeration => SU.To_Unbounded_String ("baseball")), (enumeration => SU.To_Unbounded_String ("tennis"))); ST : ARC.Field.field_access := ARC.Field.spawn_field (enumset => myset); chain_len : Natural := FA.as_chain'Length; begin TIO.Put_Line ("Chain #1 length:" & chain_len'Img); TIO.Put_Line ("Chain #1 type: " & FA.native_type'Img); for x in 1 .. chain_len loop TIO.Put (" block" & x'Img & " value:" & FA.as_chain (x)'Img); IIO.Put (Item => Natural (FA.as_chain (x)), Base => 16); TIO.Put_Line (""); end loop; TIO.Put ("Chain #1 converted to 4-byte unsigned integer:" & FA.as_nbyte4'Img & " "); IIO.Put (Item => Natural (FA.as_nbyte4), Base => 16); TIO.Put_Line (""); TIO.Put_Line (""); WIO.Put_Line ("Convert BR field to wide string: " & BR.as_wstring); TIO.Put_Line ("Convert ST settype to string: " & ST.as_string); TIO.Put_Line ("Length of ST set: " & myset'Length'Img); end Spawn_Fields;
with AdaBase.Results.Field; with AdaBase.Results.Converters; with Ada.Strings.Unbounded; with Ada.Integer_Text_IO; with Ada.Text_IO; with Ada.Wide_Text_IO; procedure Spawn_Fields is package TIO renames Ada.Text_IO; package WIO renames Ada.Wide_Text_IO; package IIO renames Ada.Integer_Text_IO; package SU renames Ada.Strings.Unbounded; package AR renames AdaBase.Results; package ARC renames AdaBase.Results.Converters; SF : AR.Field.std_field := AR.Field.spawn_field (binob => (50, 15, 4, 8)); BR : AR.Field.std_field := AR.Field.spawn_field (data => (datatype => AdaBase.ft_textual, v13 => SU.To_Unbounded_String ("Baltimore Ravens"))); myset : AR.settype (1 .. 3) := ((enumeration => SU.To_Unbounded_String ("hockey")), (enumeration => SU.To_Unbounded_String ("baseball")), (enumeration => SU.To_Unbounded_String ("tennis"))); ST : AR.Field.std_field := AR.Field.spawn_field (enumset => ARC.convert (myset)); chain_len : Natural := SF.as_chain'Length; begin TIO.Put_Line ("Chain #1 length:" & chain_len'Img); TIO.Put_Line ("Chain #1 type: " & SF.native_type'Img); for x in 1 .. chain_len loop TIO.Put (" block" & x'Img & " value:" & SF.as_chain (x)'Img); IIO.Put (Item => Natural (SF.as_chain (x)), Base => 16); TIO.Put_Line (""); end loop; TIO.Put ("Chain #1 converted to 4-byte unsigned integer:" & SF.as_nbyte4'Img & " "); IIO.Put (Item => Natural (SF.as_nbyte4), Base => 16); TIO.Put_Line (""); TIO.Put_Line (""); WIO.Put_Line ("Convert BR field to wide string: " & BR.as_wstring); TIO.Put_Line ("Convert ST settype to string: " & ST.as_string); TIO.Put_Line ("Length of ST set: " & myset'Length'Img); end Spawn_Fields;
Adjust spawn fields test case after recent change
Adjust spawn fields test case after recent change
Ada
isc
jrmarino/AdaBase
e78640fa58a9cd68d4049a96f8b8a6c917b1856e
src/gen-model-list.adb
src/gen-model-list.adb
----------------------------------------------------------------------- -- gen-model-list -- List bean interface for model objects -- Copyright (C) 2009, 2010, 2011, 2012, 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. ----------------------------------------------------------------------- package body Gen.Model.List is -- ------------------------------ -- Make an iterator for the list. -- ------------------------------ function Iterate (Container : in List_Definition) return List_Iterator.Forward_Iterator'Class is begin return Result : constant Iterator := (List => Container.Self); end Iterate; -- ------------------------------ -- Make an iterator for the list. -- ------------------------------ function Element_Value (Container : in List_Definition; Pos : in Cursor) return T_Access is pragma Unreferenced (Container); begin return Element (Pos); end Element_Value; overriding function First (Object : in Iterator) return Cursor is begin return Object.List.First; end First; overriding function Next (Object : in Iterator; Pos : in Cursor) return Cursor is pragma Unreferenced (Object); C : Cursor := Pos; begin Next (C); return C; end Next; -- ------------------------------ -- Compare the two definitions. -- ------------------------------ function "<" (Left, Right : in T_Access) return Boolean is Left_Name : constant String := Left.Get_Name; Right_Name : constant String := Right.Get_Name; begin return Left_Name < Right_Name; end "<"; -- ------------------------------ -- Get the first item of the list -- ------------------------------ function First (Def : List_Definition) return Cursor is begin return Def.Nodes.First; end First; -- ------------------------------ -- Get the number of elements in the list. -- ------------------------------ overriding function Get_Count (From : List_Definition) return Natural is Count : constant Natural := Natural (From.Nodes.Length); begin return Count; end Get_Count; -- ------------------------------ -- Set the current row index. Valid row indexes start at 1. -- ------------------------------ overriding procedure Set_Row_Index (From : in out List_Definition; Index : in Natural) is begin From.Row := Index; if Index > 0 then declare Current : constant T_Access := From.Nodes.Element (Index - 1); Bean : constant Util.Beans.Basic.Readonly_Bean_Access := Current.all'Access; begin Current.Row_Index := Index; From.Value_Bean := Util.Beans.Objects.To_Object (Bean, Util.Beans.Objects.STATIC); end; else From.Value_Bean := Util.Beans.Objects.Null_Object; end if; end Set_Row_Index; -- ------------------------------ -- Get the element at the current row index. -- ------------------------------ overriding function Get_Row (From : List_Definition) return Util.Beans.Objects.Object is begin return From.Value_Bean; end Get_Row; -- ------------------------------ -- 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 : List_Definition; Name : String) return Util.Beans.Objects.Object is begin if Name = "size" then return Util.Beans.Objects.To_Object (From.Get_Count); else return Util.Beans.Objects.Null_Object; end if; end Get_Value; -- ------------------------------ -- Append the item in the list -- ------------------------------ procedure Append (Def : in out List_Definition; Item : in T_Access) is begin Def.Nodes.Append (Item); end Append; -- ------------------------------ -- Sort the list of items on their names. -- ------------------------------ procedure Sort (List : in out List_Definition) is begin Sorting.Sort (List.Nodes); end Sort; procedure Sort_On (List : in out List_Definition) is package Sorting is new Vectors.Generic_Sorting; begin Sorting.Sort (List.Nodes); end Sort_On; -- ------------------------------ -- Find a definition given the name. -- Returns the definition object or null. -- ------------------------------ function Find (Def : in List_Definition; Name : in String) return T_Access is Iter : Vectors.Cursor := Def.Nodes.First; begin while Vectors.Has_Element (Iter) loop if Vectors.Element (Iter).Get_Name = Name then return Vectors.Element (Iter); end if; Vectors.Next (Iter); end loop; return null; end Find; -- ------------------------------ -- Iterate over the elements of the list executing the <tt>Process</tt> procedure. -- ------------------------------ procedure Iterate (Def : in List_Definition; Process : not null access procedure (Item : in T_Access)) is Iter : Vectors.Cursor := Def.Nodes.First; begin while Vectors.Has_Element (Iter) loop Process (Vectors.Element (Iter)); Vectors.Next (Iter); end loop; end Iterate; end Gen.Model.List;
----------------------------------------------------------------------- -- gen-model-list -- List bean interface for model objects -- Copyright (C) 2009, 2010, 2011, 2012, 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. ----------------------------------------------------------------------- package body Gen.Model.List is -- ------------------------------ -- Make an iterator for the list. -- ------------------------------ function Iterate (Container : in List_Definition) return List_Iterator.Forward_Iterator'Class is begin return Result : constant Iterator := (List => Container.Self); end Iterate; -- ------------------------------ -- Make an iterator for the list. -- ------------------------------ function Element_Value (Container : in List_Definition; Pos : in Cursor) return T_Access is pragma Unreferenced (Container); begin return Element (Pos); end Element_Value; overriding function First (Object : in Iterator) return Cursor is begin return Object.List.First; end First; overriding function Next (Object : in Iterator; Pos : in Cursor) return Cursor is pragma Unreferenced (Object); C : Cursor := Pos; begin Next (C); return C; end Next; -- ------------------------------ -- Compare the two definitions. -- ------------------------------ function "<" (Left, Right : in T_Access) return Boolean is Left_Name : constant String := Left.Get_Name; Right_Name : constant String := Right.Get_Name; begin return Left_Name < Right_Name; end "<"; -- ------------------------------ -- Get the first item of the list -- ------------------------------ function First (Def : List_Definition) return Cursor is begin return Def.Nodes.First; end First; -- ------------------------------ -- Get the number of elements in the list. -- ------------------------------ overriding function Get_Count (From : List_Definition) return Natural is Count : constant Natural := Natural (From.Nodes.Length); begin return Count; end Get_Count; -- ------------------------------ -- Set the current row index. Valid row indexes start at 1. -- ------------------------------ overriding procedure Set_Row_Index (From : in out List_Definition; Index : in Natural) is begin From.Row := Index; if Index > 0 then declare Current : constant T_Access := From.Nodes.Element (Index - 1); Bean : constant Util.Beans.Basic.Readonly_Bean_Access := Current.all'Access; begin Current.Set_Index (Index); From.Value_Bean := Util.Beans.Objects.To_Object (Bean, Util.Beans.Objects.STATIC); end; else From.Value_Bean := Util.Beans.Objects.Null_Object; end if; end Set_Row_Index; -- ------------------------------ -- Get the element at the current row index. -- ------------------------------ overriding function Get_Row (From : List_Definition) return Util.Beans.Objects.Object is begin return From.Value_Bean; end Get_Row; -- ------------------------------ -- 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 : List_Definition; Name : String) return Util.Beans.Objects.Object is begin if Name = "size" then return Util.Beans.Objects.To_Object (From.Get_Count); else return Util.Beans.Objects.Null_Object; end if; end Get_Value; -- ------------------------------ -- Append the item in the list -- ------------------------------ procedure Append (Def : in out List_Definition; Item : in T_Access) is begin Def.Nodes.Append (Item); end Append; -- ------------------------------ -- Sort the list of items on their names. -- ------------------------------ procedure Sort (List : in out List_Definition) is begin Sorting.Sort (List.Nodes); end Sort; procedure Sort_On (List : in out List_Definition) is package Sorting is new Vectors.Generic_Sorting; begin Sorting.Sort (List.Nodes); end Sort_On; -- ------------------------------ -- Find a definition given the name. -- Returns the definition object or null. -- ------------------------------ function Find (Def : in List_Definition; Name : in String) return T_Access is Iter : Vectors.Cursor := Def.Nodes.First; begin while Vectors.Has_Element (Iter) loop if Vectors.Element (Iter).Get_Name = Name then return Vectors.Element (Iter); end if; Vectors.Next (Iter); end loop; return null; end Find; -- ------------------------------ -- Iterate over the elements of the list executing the <tt>Process</tt> procedure. -- ------------------------------ procedure Iterate (Def : in List_Definition; Process : not null access procedure (Item : in T_Access)) is Iter : Vectors.Cursor := Def.Nodes.First; begin while Vectors.Has_Element (Iter) loop Process (Vectors.Element (Iter)); Vectors.Next (Iter); end loop; end Iterate; end Gen.Model.List;
Fix GNAT 2020 compilation issue: use Set_Index procedure instead of setting the Row_Index member directory Trying to set the member generates a crash of the GNAT compiler
Fix GNAT 2020 compilation issue: use Set_Index procedure instead of setting the Row_Index member directory Trying to set the member generates a crash of the GNAT compiler
Ada
apache-2.0
stcarrez/dynamo,stcarrez/dynamo,stcarrez/dynamo
b5d7ca4acc41b3fcd7045fc0e5cf3144a32f74df
src/asf-components-html.adb
src/asf-components-html.adb
----------------------------------------------------------------------- -- html -- ASF HTML Components -- 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 EL.Objects; package body ASF.Components.Html is use EL.Objects; procedure Render_Attributes (UI : in UIHtmlComponent; Context : in out Faces_Context'Class; Writer : in ResponseWriter_Access) is Style : constant Object := UI.Get_Attribute (Context, "style"); Class : constant Object := UI.Get_Attribute (Context, "styleClass"); begin Writer.Write_Attribute ("id", UI.Get_Client_Id); if not Is_Null (Class) then Writer.Write_Attribute ("class", Class); end if; if not Is_Null (Style) then Writer.Write_Attribute ("style", Style); end if; end Render_Attributes; end ASF.Components.Html;
----------------------------------------------------------------------- -- html -- ASF HTML Components -- 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 EL.Objects; package body ASF.Components.Html is use EL.Objects; procedure Render_Attributes (UI : in UIHtmlComponent; Context : in out Faces_Context'Class; Writer : in ResponseWriter_Access) is Style : constant Object := UI.Get_Attribute (Context, "style"); Class : constant Object := UI.Get_Attribute (Context, "styleClass"); Title : constant Object := UI.Get_Attribute (Context, "title"); begin Writer.Write_Attribute ("id", UI.Get_Client_Id); if not Is_Null (Class) then Writer.Write_Attribute ("class", Class); end if; if not Is_Null (Style) then Writer.Write_Attribute ("style", Style); end if; if not Is_Null (Title) then Writer.Write_Attribute ("title", Title); end if; end Render_Attributes; end ASF.Components.Html;
Add support for the title attribute
Add support for the title attribute
Ada
apache-2.0
stcarrez/ada-asf,stcarrez/ada-asf,stcarrez/ada-asf
8b161841e13befd806208959c8850f0a3d49143e
regtests/security-policies-tests.adb
regtests/security-policies-tests.adb
----------------------------------------------------------------------- -- Security-policies-tests - Unit tests for Security.Permissions -- 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 Util.Files; with Util.Test_Caller; with Util.Measures; with Security.Contexts; with Security.Policies.Roles; with Security.Permissions.Tests; with Security.Policies.URLs; 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); Caller.Add_Test (Suite, "Test Security.Contexts.Has_Permission (all-permission)", Test_Anonymous_Permission'Access); Caller.Add_Test (Suite, "Test Security.Contexts.Has_Permission (auth-permission)", Test_Anonymous_Permission'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; 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"); 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 : constant Security.Policies.Roles.Role_Policy_Access := new Roles.Role_Policy; U : constant 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; Context : aliased Security.Contexts.Security_Context; R : Security.Policies.Roles.Role_Policy_Access; 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; Result : Boolean; begin for I in 1 .. 1_000 loop Result := Contexts.Has_Permission (Permission => P_Admin.Permission); end loop; Util.Measures.Report (S, "Has_Permission role based (1000 calls)"); T.Assert (Result, "Permission not granted"); end; declare S : Util.Measures.Stamp; begin for I in 1 .. 1_000 loop declare URL : constant String := "/admin/list.html"; P : constant URLs.URL_Permission (URL'Length) := URLs.URL_Permission '(Len => URL'Length, URL => URL); begin T.Assert (Contexts.Has_Permission (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; URL : in String; Anonymous : in Boolean := False; Granted : in Boolean := True) is M : aliased Security.Policies.Policy_Manager (2); User : aliased Test_Principal; Admin : Roles.Role_Type; Context : aliased Security.Contexts.Security_Context; R : Security.Policies.Roles.Role_Policy_Access; U : Security.Policies.URLs.URL_Policy_Access; begin Configure_Policy (M, File); if Anonymous then Context.Set_Context (Manager => M'Unchecked_Access, Principal => null); else Context.Set_Context (Manager => M'Unchecked_Access, Principal => User'Unchecked_Access); end if; R := Security.Policies.Roles.Get_Role_Policy (M); U := Security.Policies.URLs.Get_URL_Policy (M); Admin := R.Find_Role (Role); declare P : constant URLs.URL_Permission (URL'Length) := URLs.URL_Permission '(Len => URL'Length, URL => URL); begin if not Anonymous then -- A user without the role should not have the permission. T.Assert (not U.Has_Permission (Context => Context, Permission => P), "Permission was granted for user without role. URL=" & URL); -- Set the role. User.Roles (Admin) := True; end if; if Granted then T.Assert (U.Has_Permission (Context => Context, Permission => P), "Permission was not granted for user with role. URL=" & URL); else T.Assert (not U.Has_Permission (Context => Context, Permission => P), "Permission was granted for user with role. URL=" & URL); end if; 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", URL => "/developer/user-should-have-developer-role"); T.Check_Policy (File => "policy-with-role.xml", Role => "manager", URL => "/developer/user-should-have-manager-role"); T.Check_Policy (File => "policy-with-role.xml", Role => "manager", URL => "/manager/user-should-have-manager-role"); T.Check_Policy (File => "policy-with-role.xml", Role => "admin", URL => "/manager/user-should-have-admin-role"); T.Check_Policy (File => "policy-with-role.xml", Role => "admin", URL => "/admin/user-should-have-admin-role"); T.Check_Policy (File => "policy-with-role.xml", Role => "developer", URL => "/admin/user-with-developer-role-should-not-access-admin", Granted => False); end Test_Role_Policy; -- ------------------------------ -- Test anonymous users and permissions. -- ------------------------------ procedure Test_Anonymous_Permission (T : in out Test) is begin T.Check_Policy (File => "simple-policy.xml", Role => "admin", URL => "/admin/page.html", Anonymous => True, Granted => False); T.Check_Policy (File => "simple-policy.xml", Role => "admin", URL => "/user/totopage.html", Anonymous => True, Granted => False); -- Anonymous users can access the page. T.Check_Policy (File => "simple-policy.xml", Role => "admin", URL => "/page.html", Anonymous => True, Granted => True); end Test_Anonymous_Permission; end Security.Policies.Tests;
----------------------------------------------------------------------- -- Security-policies-tests - Unit tests for Security.Permissions -- 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 Util.Files; with Util.Test_Caller; with Util.Measures; with Security.Contexts; with Security.Policies.Roles; with Security.Permissions.Tests; with Security.Policies.URLs; 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); Caller.Add_Test (Suite, "Test Security.Contexts.Has_Permission (all-permission)", Test_Anonymous_Permission'Access); Caller.Add_Test (Suite, "Test Security.Contexts.Has_Permission (auth-permission)", Test_Anonymous_Permission'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"); 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 : constant Security.Policies.Roles.Role_Policy_Access := new Roles.Role_Policy; U : constant 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; 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; Context : aliased Security.Contexts.Security_Context; R : Security.Policies.Roles.Role_Policy_Access; 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; Result : Boolean; begin for I in 1 .. 1_000 loop Result := Contexts.Has_Permission (Permission => P_Admin.Permission); end loop; Util.Measures.Report (S, "Has_Permission role based (1000 calls)"); T.Assert (Result, "Permission not granted"); end; declare S : Util.Measures.Stamp; begin for I in 1 .. 1_000 loop declare URL : constant String := "/admin/list.html"; P : constant URLs.URL_Permission (URL'Length) := URLs.URL_Permission '(Len => URL'Length, URL => URL); begin T.Assert (Contexts.Has_Permission (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; URL : in String; Anonymous : in Boolean := False; Granted : in Boolean := True) is M : aliased Security.Policies.Policy_Manager (2); User : aliased Test_Principal; Admin : Roles.Role_Type; Context : aliased Security.Contexts.Security_Context; R : Security.Policies.Roles.Role_Policy_Access; U : Security.Policies.URLs.URL_Policy_Access; begin Configure_Policy (M, File); if Anonymous then Context.Set_Context (Manager => M'Unchecked_Access, Principal => null); else Context.Set_Context (Manager => M'Unchecked_Access, Principal => User'Unchecked_Access); end if; R := Security.Policies.Roles.Get_Role_Policy (M); U := Security.Policies.URLs.Get_URL_Policy (M); Admin := R.Find_Role (Role); declare P : constant URLs.URL_Permission (URL'Length) := URLs.URL_Permission '(Len => URL'Length, URL => URL); begin if not Anonymous then -- A user without the role should not have the permission. T.Assert (not U.Has_Permission (Context => Context, Permission => P), "Permission was granted for user without role. URL=" & URL); -- Set the role. User.Roles (Admin) := True; end if; if Granted then T.Assert (U.Has_Permission (Context => Context, Permission => P), "Permission was not granted for user with role. URL=" & URL); else T.Assert (not U.Has_Permission (Context => Context, Permission => P), "Permission was granted for user with role. URL=" & URL); end if; 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", URL => "/developer/user-should-have-developer-role"); T.Check_Policy (File => "policy-with-role.xml", Role => "manager", URL => "/developer/user-should-have-manager-role"); T.Check_Policy (File => "policy-with-role.xml", Role => "manager", URL => "/manager/user-should-have-manager-role"); T.Check_Policy (File => "policy-with-role.xml", Role => "admin", URL => "/manager/user-should-have-admin-role"); T.Check_Policy (File => "policy-with-role.xml", Role => "admin", URL => "/admin/user-should-have-admin-role"); T.Check_Policy (File => "policy-with-role.xml", Role => "developer", URL => "/admin/user-with-developer-role-should-not-access-admin", Granted => False); end Test_Role_Policy; -- ------------------------------ -- Test anonymous users and permissions. -- ------------------------------ procedure Test_Anonymous_Permission (T : in out Test) is begin T.Check_Policy (File => "simple-policy.xml", Role => "admin", URL => "/admin/page.html", Anonymous => True, Granted => False); T.Check_Policy (File => "simple-policy.xml", Role => "admin", URL => "/user/totopage.html", Anonymous => True, Granted => False); -- Anonymous users can access the page. T.Check_Policy (File => "simple-policy.xml", Role => "admin", URL => "/page.html", Anonymous => True, Granted => True); end Test_Anonymous_Permission; end Security.Policies.Tests;
Fix compilation warnings
Fix compilation warnings
Ada
apache-2.0
stcarrez/ada-security
c36951d362073351100b12994ad97d74de479bbb
resources/scripts/cert/digitorus.ads
resources/scripts/cert/digitorus.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. name = "Digitorus" type = "cert" function start() set_rate_limit(2) end function vertical(ctx, domain) scrape(ctx, {['url']=build_url(domain)}) end function build_url(domain) return "https://certificatedetails.com/api/list/" .. 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. name = "Digitorus" type = "cert" function start() set_rate_limit(2) end function vertical(ctx, domain) scrape(ctx, {['url']=build_url(domain)}) end function build_url(domain) return "https://certificatedetails.com/" .. domain end
Fix Digitorus datasource
Fix Digitorus datasource
Ada
apache-2.0
caffix/amass,caffix/amass
85e5569f7c4dc98556c8f3d0ddab82e6f1165d2b
src/gen-commands-layout.adb
src/gen-commands-layout.adb
----------------------------------------------------------------------- -- gen-commands-layout -- Layout creation command for dynamo -- 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.Directories; with Ada.Text_IO; with Gen.Artifacts; with GNAT.Command_Line; with Util.Strings; with Util.Files; package body Gen.Commands.Layout is -- ------------------------------ -- Execute the command with the arguments. -- ------------------------------ procedure Execute (Cmd : in Command; Generator : in out Gen.Generator.Handler) is pragma Unreferenced (Cmd); use GNAT.Command_Line; use Ada.Strings.Unbounded; function Get_Layout return String; Dir : constant String := Generator.Get_Result_Directory; Layout_Dir : constant String := Util.Files.Compose (Dir, "web/WEB-INF/layouts"); function Get_Name return String is Name : constant String := Get_Argument; Pos : constant Natural := Util.Strings.Rindex (Name, '.'); begin if Pos = 0 then return Name; elsif Name (Pos .. Name'Last) = ".xhtml" then return Name (Name'First .. Pos - 1); elsif Name (Pos .. Name'Last) = ".html" then return Name (Name'First .. Pos - 1); else return Name; end if; end Get_Name; function Get_Layout return String is Layout : constant String := Get_Argument; begin if Layout'Length = 0 then return "layout"; end if; if Ada.Directories.Exists (Dir & "WEB-INF/layouts/" & Layout & ".xhtml") then return Layout; end if; Generator.Error ("Layout file {0} not found. Using 'layout' instead.", Layout); return "layout"; end Get_Layout; Name : constant String := Get_Name; Layout : constant String := Get_Layout; begin if Name'Length = 0 then Gen.Commands.Usage; return; end if; Generator.Set_Force_Save (False); Generator.Set_Result_Directory (Layout_Dir); Generator.Set_Global ("pageName", Name); Generator.Set_Global ("layout", Layout); Gen.Generator.Generate_All (Generator, Gen.Artifacts.ITERATION_TABLE, "layout"); end Execute; -- ------------------------------ -- Write the help associated with the command. -- ------------------------------ procedure Help (Cmd : in Command; Generator : in out Gen.Generator.Handler) is pragma Unreferenced (Cmd, Generator); use Ada.Text_IO; begin Put_Line ("add-layout: Add a new layout page to the application"); Put_Line ("Usage: add-layout NAME [FORM]"); New_Line; Put_Line (" The layout page allows to give a common look to a set of pages."); Put_Line (" You can create several layouts for your application."); Put_Line (" Each layout can reference one or several building blocks that are defined"); Put_Line (" in the original page."); New_Line; Put_Line (" The following files are generated:"); Put_Line (" web/WEB-INF/layouts/<name>.xhtml"); end Help; end Gen.Commands.Layout;
----------------------------------------------------------------------- -- gen-commands-layout -- Layout creation command for dynamo -- 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.Directories; with Ada.Text_IO; with Gen.Artifacts; with GNAT.Command_Line; with Util.Strings; with Util.Files; package body Gen.Commands.Layout is -- ------------------------------ -- Execute the command with the arguments. -- ------------------------------ procedure Execute (Cmd : in Command; Generator : in out Gen.Generator.Handler) is pragma Unreferenced (Cmd); use GNAT.Command_Line; use Ada.Strings.Unbounded; function Get_Layout return String; function Get_Name return String; Dir : constant String := Generator.Get_Result_Directory; Layout_Dir : constant String := Util.Files.Compose (Dir, "web/WEB-INF/layouts"); function Get_Name return String is Name : constant String := Get_Argument; Pos : constant Natural := Util.Strings.Rindex (Name, '.'); begin if Pos = 0 then return Name; elsif Name (Pos .. Name'Last) = ".xhtml" then return Name (Name'First .. Pos - 1); elsif Name (Pos .. Name'Last) = ".html" then return Name (Name'First .. Pos - 1); else return Name; end if; end Get_Name; function Get_Layout return String is Layout : constant String := Get_Argument; begin if Layout'Length = 0 then return "layout"; end if; if Ada.Directories.Exists (Dir & "WEB-INF/layouts/" & Layout & ".xhtml") then return Layout; end if; Generator.Error ("Layout file {0} not found. Using 'layout' instead.", Layout); return "layout"; end Get_Layout; Name : constant String := Get_Name; Layout : constant String := Get_Layout; begin if Name'Length = 0 then Gen.Commands.Usage; return; end if; Generator.Set_Force_Save (False); Generator.Set_Result_Directory (Layout_Dir); Generator.Set_Global ("pageName", Name); Generator.Set_Global ("layout", Layout); Gen.Generator.Generate_All (Generator, Gen.Artifacts.ITERATION_TABLE, "layout"); end Execute; -- ------------------------------ -- Write the help associated with the command. -- ------------------------------ procedure Help (Cmd : in Command; Generator : in out Gen.Generator.Handler) is pragma Unreferenced (Cmd, Generator); use Ada.Text_IO; begin Put_Line ("add-layout: Add a new layout page to the application"); Put_Line ("Usage: add-layout NAME [FORM]"); New_Line; Put_Line (" The layout page allows to give a common look to a set of pages."); Put_Line (" You can create several layouts for your application."); Put_Line (" Each layout can reference one or several building blocks that are defined"); Put_Line (" in the original page."); New_Line; Put_Line (" The following files are generated:"); Put_Line (" web/WEB-INF/layouts/<name>.xhtml"); end Help; end Gen.Commands.Layout;
Fix compilation warning
Fix compilation warning
Ada
apache-2.0
stcarrez/dynamo,stcarrez/dynamo,stcarrez/dynamo
93dd54d383537e737c7a6055983e93a995499940
src/babel-base.ads
src/babel-base.ads
----------------------------------------------------------------------- -- babel-base -- Database for files -- 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.Finalization; with ADO; with Babel.Files; package Babel.Base is type Database is abstract new Ada.Finalization.Limited_Controlled with private; -- Insert the file in the database. procedure Insert (Into : in out Database; File : in Babel.Files.File_Type) is abstract; private type Database is abstract new Ada.Finalization.Limited_Controlled with record Name : Integer; end record; end Babel.Base;
----------------------------------------------------------------------- -- babel-base -- Database for files -- 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.Finalization; with ADO; with Babel.Files; package Babel.Base is type Database is abstract new Ada.Finalization.Limited_Controlled with private; type Database_Access is access all Database'Class; -- Insert the file in the database. procedure Insert (Into : in out Database; File : in Babel.Files.File_Type) is abstract; private type Database is abstract new Ada.Finalization.Limited_Controlled with record Name : Integer; end record; end Babel.Base;
Define the Database_Access type
Define the Database_Access type
Ada
apache-2.0
stcarrez/babel
eefdbbb2f485ad9c16fec43a4a838097cc8c0501
src/security-oauth-file_registry.ads
src/security-oauth-file_registry.ads
----------------------------------------------------------------------- -- security-oauth-file_registry -- File Based Application and Realm -- 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 Ada.Strings.Hash; with Ada.Containers.Indefinite_Hashed_Maps; with Util.Strings; with Util.Properties; with Security.OAuth.Servers; private with Util.Strings.Maps; private with Security.Random; package Security.OAuth.File_Registry is type File_Principal is new Security.Principal with private; type File_Principal_Access is access all File_Principal'Class; -- Get the principal name. overriding function Get_Name (From : in File_Principal) return String; type File_Application_Manager is new Servers.Application_Manager with private; -- Find the application that correspond to the given client id. -- The <tt>Invalid_Application</tt> exception should be raised if there is no such application. overriding function Find_Application (Realm : in File_Application_Manager; Client_Id : in String) return Servers.Application'Class; -- Add the application to the application repository. procedure Add_Application (Realm : in out File_Application_Manager; App : in Servers.Application); -- Load from the properties the definition of applications. The list of applications -- is controled by the property <prefix>.list which contains a comma separated list of -- application names or ids. The application definition are represented by properties -- of the form: -- <prefix>.<app>.client_id -- <prefix>.<app>.client_secret -- <prefix>.<app>.callback_url procedure Load (Realm : in out File_Application_Manager; Props : in Util.Properties.Manager'Class; Prefix : in String); procedure Load (Realm : in out File_Application_Manager; Path : in String; Prefix : in String); type File_Realm_Manager is limited new Servers.Realm_Manager with private; -- Authenticate the token and find the associated authentication principal. -- The access token has been verified and the token represents the identifier -- of the Tuple (client_id, user, session) that describes the authentication. -- The <tt>Authenticate</tt> procedure should look in its database (internal -- or external) to find the authentication principal that was granted for -- the token Tuple. When the token was not found (because it was revoked), -- the procedure should return a null principal. If the authentication -- principal can be cached, the <tt>Cacheable</tt> value should be set. -- In that case, the access token and authentication principal are inserted -- in a cache. overriding procedure Authenticate (Realm : in out File_Realm_Manager; Token : in String; Auth : out Principal_Access; Cacheable : out Boolean); -- Create an auth token string that identifies the given principal. The returned -- token will be used by <tt>Authenticate</tt> to retrieve back the principal. The -- returned token does not need to be signed. It will be inserted in the public part -- of the returned access token. overriding function Authorize (Realm : in File_Realm_Manager; App : in Servers.Application'Class; Scope : in String; Auth : in Principal_Access) return String; overriding procedure Verify (Realm : in out File_Realm_Manager; Username : in String; Password : in String; Auth : out Principal_Access); overriding procedure Verify (Realm : in out File_Realm_Manager; Token : in String; Auth : out Principal_Access); overriding procedure Revoke (Realm : in out File_Realm_Manager; Auth : in Principal_Access); -- Crypt the password using the given salt and return the string composed with -- the salt in clear text and the crypted password. function Crypt_Password (Realm : in File_Realm_Manager; Salt : in String; Password : in String) return String; -- Add a username with the associated password. procedure Add_User (Realm : in out File_Realm_Manager; Username : in String; Password : in String); private use Ada.Strings.Unbounded; package Application_Maps is new Ada.Containers.Indefinite_Hashed_Maps (Key_Type => String, Element_Type => Servers.Application, Hash => Ada.Strings.Hash, Equivalent_Keys => "=", "=" => Servers."="); package Token_Maps is new Ada.Containers.Indefinite_Hashed_Maps (Key_Type => String, Element_Type => File_Principal_Access, Hash => Ada.Strings.Hash, Equivalent_Keys => "=", "=" => "="); package User_Maps renames Util.Strings.Maps; type File_Principal is new Security.Principal with record Token : Ada.Strings.Unbounded.Unbounded_String; Name : Ada.Strings.Unbounded.Unbounded_String; end record; type File_Application_Manager is new Servers.Application_Manager with record Applications : Application_Maps.Map; end record; type File_Realm_Manager is limited new Servers.Realm_Manager with record Users : User_Maps.Map; Tokens : Token_Maps.Map; Random : Security.Random.Generator; Token_Bits : Positive := 256; end record; end Security.OAuth.File_Registry;
----------------------------------------------------------------------- -- security-oauth-file_registry -- File Based Application and Realm -- 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 Ada.Strings.Hash; with Ada.Containers.Indefinite_Hashed_Maps; with Util.Strings; with Util.Properties; with Security.OAuth.Servers; private with Util.Strings.Maps; private with Security.Random; package Security.OAuth.File_Registry is type File_Principal is new Security.Principal with private; type File_Principal_Access is access all File_Principal'Class; -- Get the principal name. overriding function Get_Name (From : in File_Principal) return String; type File_Application_Manager is new Servers.Application_Manager with private; -- Find the application that correspond to the given client id. -- The <tt>Invalid_Application</tt> exception should be raised if there is no such application. overriding function Find_Application (Realm : in File_Application_Manager; Client_Id : in String) return Servers.Application'Class; -- Add the application to the application repository. procedure Add_Application (Realm : in out File_Application_Manager; App : in Servers.Application); -- Load from the properties the definition of applications. The list of applications -- is controled by the property <prefix>.list which contains a comma separated list of -- application names or ids. The application definition are represented by properties -- of the form: -- <prefix>.<app>.client_id -- <prefix>.<app>.client_secret -- <prefix>.<app>.callback_url procedure Load (Realm : in out File_Application_Manager; Props : in Util.Properties.Manager'Class; Prefix : in String); procedure Load (Realm : in out File_Application_Manager; Path : in String; Prefix : in String); type File_Realm_Manager is limited new Servers.Realm_Manager with private; -- Authenticate the token and find the associated authentication principal. -- The access token has been verified and the token represents the identifier -- of the Tuple (client_id, user, session) that describes the authentication. -- The <tt>Authenticate</tt> procedure should look in its database (internal -- or external) to find the authentication principal that was granted for -- the token Tuple. When the token was not found (because it was revoked), -- the procedure should return a null principal. If the authentication -- principal can be cached, the <tt>Cacheable</tt> value should be set. -- In that case, the access token and authentication principal are inserted -- in a cache. overriding procedure Authenticate (Realm : in out File_Realm_Manager; Token : in String; Auth : out Principal_Access; Cacheable : out Boolean); -- Create an auth token string that identifies the given principal. The returned -- token will be used by <tt>Authenticate</tt> to retrieve back the principal. The -- returned token does not need to be signed. It will be inserted in the public part -- of the returned access token. overriding function Authorize (Realm : in File_Realm_Manager; App : in Servers.Application'Class; Scope : in String; Auth : in Principal_Access) return String; overriding procedure Verify (Realm : in out File_Realm_Manager; Username : in String; Password : in String; Auth : out Principal_Access); overriding procedure Verify (Realm : in out File_Realm_Manager; Token : in String; Auth : out Principal_Access); overriding procedure Revoke (Realm : in out File_Realm_Manager; Auth : in Principal_Access); -- Crypt the password using the given salt and return the string composed with -- the salt in clear text and the crypted password. function Crypt_Password (Realm : in File_Realm_Manager; Salt : in String; Password : in String) return String; -- Load from the properties the definition of users. The list of users -- is controled by the property <prefix>.list which contains a comma separated list of -- users names or ids. The user definition are represented by properties -- of the form: -- <prefix>.<user>.username -- <prefix>.<user>.password -- <prefix>.<user>.salt -- When a 'salt' property is defined, it is assumed that the password is encrypted using -- the salt and SHA1 and base64url. Otherwise, the password is in clear text. procedure Load (Realm : in out File_Realm_Manager; Props : in Util.Properties.Manager'Class; Prefix : in String); procedure Load (Realm : in out File_Realm_Manager; Path : in String; Prefix : in String); -- Add a username with the associated password. procedure Add_User (Realm : in out File_Realm_Manager; Username : in String; Password : in String); private use Ada.Strings.Unbounded; package Application_Maps is new Ada.Containers.Indefinite_Hashed_Maps (Key_Type => String, Element_Type => Servers.Application, Hash => Ada.Strings.Hash, Equivalent_Keys => "=", "=" => Servers."="); package Token_Maps is new Ada.Containers.Indefinite_Hashed_Maps (Key_Type => String, Element_Type => File_Principal_Access, Hash => Ada.Strings.Hash, Equivalent_Keys => "=", "=" => "="); package User_Maps renames Util.Strings.Maps; type File_Principal is new Security.Principal with record Token : Ada.Strings.Unbounded.Unbounded_String; Name : Ada.Strings.Unbounded.Unbounded_String; end record; type File_Application_Manager is new Servers.Application_Manager with record Applications : Application_Maps.Map; end record; type File_Realm_Manager is limited new Servers.Realm_Manager with record Users : User_Maps.Map; Tokens : Token_Maps.Map; Random : Security.Random.Generator; Token_Bits : Positive := 256; end record; end Security.OAuth.File_Registry;
Declare Load procedures to load the definition of users in the File_Realm_Manager
Declare Load procedures to load the definition of users in the File_Realm_Manager
Ada
apache-2.0
stcarrez/ada-security
59cd50235947171447d5fb2dd1386a3f6e47a195
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; with MAT.Expressions; 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); -- Collect the information about threads and the memory allocations they've made. procedure Thread_Information (Memory : in MAT.Memory.Allocation_Map; Threads : in out Memory_Info_Map); -- Find from the <tt>Memory</tt> map the memory slots whose address intersects -- the region [From .. To] and which is selected by the given filter expression. -- 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; Filter : in MAT.Expressions.Expression_Type; 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; with MAT.Expressions; 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); -- Collect the information about threads and the memory allocations they've made. procedure Thread_Information (Memory : in MAT.Memory.Allocation_Map; Threads : in out Memory_Info_Map); -- Collect the information about frames and the memory allocations they've made. procedure Frame_Information (Memory : in MAT.Memory.Allocation_Map; Level : in Natural; Frames : in out Frame_Info_Map); -- Find from the <tt>Memory</tt> map the memory slots whose address intersects -- the region [From .. To] and which is selected by the given filter expression. -- 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; Filter : in MAT.Expressions.Expression_Type; Into : in out MAT.Memory.Allocation_Map); end MAT.Memory.Tools;
Declare the Frame_Information procedure
Declare the Frame_Information procedure
Ada
apache-2.0
stcarrez/mat,stcarrez/mat,stcarrez/mat
fa7cf9a1e71cefe30b58efb979bf3fed10bf0fd3
src/gen-utils-gnat.adb
src/gen-utils-gnat.adb
----------------------------------------------------------------------- -- gen-utils-gnat -- GNAT utilities -- Copyright (C) 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 Util.Log.Loggers; with Csets; with Snames; with Namet; with Prj.Pars; with Prj.Tree; with Prj.Env; with Prj.Util; with Makeutl; with Output; package body Gen.Utils.GNAT is use Util.Log; Log : constant Loggers.Logger := Loggers.Create ("Gen.Utils.GNAT"); Project_Node_Tree : Prj.Tree.Project_Node_Tree_Ref; Main_Project : Prj.Project_Id; -- ------------------------------ -- Initialize the GNAT project runtime for reading the GNAT project tree. -- Configure it according to the dynamo configuration properties. -- ------------------------------ procedure Initialize (Config : in Util.Properties.Manager'Class) is Project_Dirs : constant String := Config.Get ("generator.gnat.projects.dir", DEFAULT_GNAT_PROJECT_DIR); begin Log.Info ("Initializing GNAT runtime to read projects from: {0}", Project_Dirs); Project_Node_Tree := new Prj.Tree.Project_Node_Tree_Data; Prj.Tree.Initialize (Project_Node_Tree); Output.Set_Standard_Error; Csets.Initialize; Snames.Initialize; Prj.Initialize (Makeutl.Project_Tree); Prj.Env.Add_Directories (Project_Node_Tree.Project_Path, Project_Dirs); end Initialize; -- ------------------------------ -- Read the GNAT project file identified by <b>Project_File_Name</b> and get -- in <b>Project_List</b> an ordered list of absolute project paths used by -- the root project. -- ------------------------------ procedure Read_GNAT_Project_List (Project_File_Name : in String; Project_List : out Project_Info_Vectors.Vector) is procedure Recursive_Add (Proj : in Prj.Project_Id; Dummy : in out Boolean); function Get_Variable_Value (Proj : in Prj.Project_Id; Name : in String) return String; -- Get the variable value represented by the name <b>Name</b>. -- ??? There are probably other efficient ways to get this but I couldn't find them. function Get_Variable_Value (Proj : in Prj.Project_Id; Name : in String) return String is use type Prj.Variable_Id; Current : Prj.Variable_Id; The_Variable : Prj.Variable; In_Tree : constant Prj.Project_Tree_Ref := Makeutl.Project_Tree; begin Current := Proj.Decl.Variables; while Current /= Prj.No_Variable loop The_Variable := In_Tree.Variable_Elements.Table (Current); if Namet.Get_Name_String (The_Variable.Name) = Name then return Prj.Util.Value_Of (The_Variable.Value, ""); end if; Current := The_Variable.Next; end loop; return ""; end Get_Variable_Value; -- ------------------------------ -- Add the full path of the GNAT project in the project list. -- ------------------------------ procedure Recursive_Add (Proj : in Prj.Project_Id; Dummy : in out Boolean) is pragma Unreferenced (Dummy); Path : constant String := Namet.Get_Name_String (Proj.Path.Name); Name : constant String := Get_Variable_Value (Proj, "name"); Project : Project_Info; begin Log.Info ("Using GNAT project: {0}", Path); Project.Path := To_Unbounded_String (Path); Project.Name := To_Unbounded_String (Name); Project_List.Append (Project); end Recursive_Add; procedure For_All_Projects is new Prj.For_Every_Project_Imported (Boolean, Recursive_Add); use type Prj.Project_Id; begin Log.Info ("Reading GNAT project {0}", Project_File_Name); -- Parse the GNAT project files and build the tree. Prj.Pars.Parse (Project => Main_Project, In_Tree => Makeutl.Project_Tree, Project_File_Name => Project_File_Name, Flags => Prj.Gnatmake_Flags, In_Node_Tree => Project_Node_Tree); if Main_Project /= Prj.No_Project then declare Dummy : Boolean := False; begin -- Scan the tree to get the list of projects (in dependency order). For_All_Projects (Main_Project, Dummy, Imported_First => True); end; end if; end Read_GNAT_Project_List; end Gen.Utils.GNAT;
----------------------------------------------------------------------- -- gen-utils-gnat -- GNAT utilities -- 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 Gen.Configs; with Csets; with Snames; with Namet; with Prj.Pars; with Prj.Tree; with Prj.Env; with Prj.Util; with Makeutl; with Output; package body Gen.Utils.GNAT is use Util.Log; Log : constant Loggers.Logger := Loggers.Create ("Gen.Utils.GNAT"); Project_Node_Tree : Prj.Tree.Project_Node_Tree_Ref; Main_Project : Prj.Project_Id; -- ------------------------------ -- Initialize the GNAT project runtime for reading the GNAT project tree. -- Configure it according to the dynamo configuration properties. -- ------------------------------ procedure Initialize (Config : in Util.Properties.Manager'Class) is Project_Dirs : constant String := Config.Get (Gen.Configs.GEN_GNAT_PROJECT_DIRS, DEFAULT_GNAT_PROJECT_DIR); begin Log.Info ("Initializing GNAT runtime to read projects from: {0}", Project_Dirs); Project_Node_Tree := new Prj.Tree.Project_Node_Tree_Data; Prj.Tree.Initialize (Project_Node_Tree); Output.Set_Standard_Error; Csets.Initialize; Snames.Initialize; Prj.Initialize (Makeutl.Project_Tree); Prj.Env.Add_Directories (Project_Node_Tree.Project_Path, Project_Dirs); end Initialize; -- ------------------------------ -- Read the GNAT project file identified by <b>Project_File_Name</b> and get -- in <b>Project_List</b> an ordered list of absolute project paths used by -- the root project. -- ------------------------------ procedure Read_GNAT_Project_List (Project_File_Name : in String; Project_List : out Project_Info_Vectors.Vector) is procedure Recursive_Add (Proj : in Prj.Project_Id; Dummy : in out Boolean); function Get_Variable_Value (Proj : in Prj.Project_Id; Name : in String) return String; -- Get the variable value represented by the name <b>Name</b>. -- ??? There are probably other efficient ways to get this but I couldn't find them. function Get_Variable_Value (Proj : in Prj.Project_Id; Name : in String) return String is use type Prj.Variable_Id; Current : Prj.Variable_Id; The_Variable : Prj.Variable; In_Tree : constant Prj.Project_Tree_Ref := Makeutl.Project_Tree; begin Current := Proj.Decl.Variables; while Current /= Prj.No_Variable loop The_Variable := In_Tree.Variable_Elements.Table (Current); if Namet.Get_Name_String (The_Variable.Name) = Name then return Prj.Util.Value_Of (The_Variable.Value, ""); end if; Current := The_Variable.Next; end loop; return ""; end Get_Variable_Value; -- ------------------------------ -- Add the full path of the GNAT project in the project list. -- ------------------------------ procedure Recursive_Add (Proj : in Prj.Project_Id; Dummy : in out Boolean) is pragma Unreferenced (Dummy); Path : constant String := Namet.Get_Name_String (Proj.Path.Name); Name : constant String := Get_Variable_Value (Proj, "name"); Project : Project_Info; begin Log.Info ("Using GNAT project: {0}", Path); Project.Path := To_Unbounded_String (Path); Project.Name := To_Unbounded_String (Name); Project_List.Append (Project); end Recursive_Add; procedure For_All_Projects is new Prj.For_Every_Project_Imported (Boolean, Recursive_Add); use type Prj.Project_Id; begin Log.Info ("Reading GNAT project {0}", Project_File_Name); -- Parse the GNAT project files and build the tree. Prj.Pars.Parse (Project => Main_Project, In_Tree => Makeutl.Project_Tree, Project_File_Name => Project_File_Name, Flags => Prj.Gnatmake_Flags, In_Node_Tree => Project_Node_Tree); if Main_Project /= Prj.No_Project then declare Dummy : Boolean := False; begin -- Scan the tree to get the list of projects (in dependency order). For_All_Projects (Main_Project, Dummy, Imported_First => True); end; end if; end Read_GNAT_Project_List; end Gen.Utils.GNAT;
Use the configuration variable
Use the configuration variable
Ada
apache-2.0
Letractively/ada-gen,Letractively/ada-gen,Letractively/ada-gen,Letractively/ada-gen
75eaaf54c7a1aecef4b0ad1197a868834527db6d
src/ado-drivers-connections.ads
src/ado-drivers-connections.ads
----------------------------------------------------------------------- -- ADO Drivers -- Database Drivers -- Copyright (C) 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 Ada.Finalization; with ADO.Statements; with ADO.Schemas; with Util.Properties; with Util.Strings; with Util.Refs; -- The <b>ADO.Drivers</b> package represents the database driver that will create -- database connections and provide the database specific implementation. package ADO.Drivers.Connections is use ADO.Statements; type Driver is abstract tagged limited private; type Driver_Access is access all Driver'Class; -- ------------------------------ -- Database connection implementation -- ------------------------------ -- type Database_Connection is abstract new Util.Refs.Ref_Entity with record Ident : String (1 .. 8) := (others => ' '); end record; type Database_Connection_Access is access all Database_Connection'Class; -- Get the database driver index. function Get_Driver_Index (Database : in Database_Connection) return Driver_Index; function Create_Statement (Database : in Database_Connection; Table : in ADO.Schemas.Class_Mapping_Access) return Query_Statement_Access is abstract; function Create_Statement (Database : in Database_Connection; Query : in String) return Query_Statement_Access is abstract; -- Create a delete statement. function Create_Statement (Database : in Database_Connection; Table : in ADO.Schemas.Class_Mapping_Access) return Delete_Statement_Access is abstract; -- Create an insert statement. function Create_Statement (Database : in Database_Connection; Table : in ADO.Schemas.Class_Mapping_Access) return Insert_Statement_Access is abstract; -- Create an update statement. function Create_Statement (Database : in Database_Connection; Table : in ADO.Schemas.Class_Mapping_Access) return Update_Statement_Access is abstract; -- Start a transaction. procedure Begin_Transaction (Database : in out Database_Connection) is abstract; -- Commit the current transaction. procedure Commit (Database : in out Database_Connection) is abstract; -- Rollback the current transaction. procedure Rollback (Database : in out Database_Connection) is abstract; -- Load the database schema definition for the current database. procedure Load_Schema (Database : in Database_Connection; Schema : out ADO.Schemas.Schema_Definition) is abstract; -- Get the database driver which manages this connection. function Get_Driver (Database : in Database_Connection) return Driver_Access is abstract; -- Closes the database connection procedure Close (Database : in out Database_Connection) is abstract; package Ref is new Util.Refs.Indefinite_References (Element_Type => Database_Connection'Class, Element_Access => Database_Connection_Access); -- ------------------------------ -- The database configuration properties -- ------------------------------ type Configuration is new Ada.Finalization.Controlled with private; type Configuration_Access is access all Configuration'Class; -- Set the connection URL to connect to the database. -- The driver connection is a string of the form: -- -- driver://[host][:port]/[database][?property1][=value1]... -- -- If the string is invalid or if the driver cannot be found, -- the Connection_Error exception is raised. procedure Set_Connection (Controller : in out Configuration; URI : in String); -- Set a property on the datasource for the driver. -- The driver can retrieve the property to configure and open -- the database connection. procedure Set_Property (Controller : in out Configuration; Name : in String; Value : in String); -- Get a property from the data source configuration. -- If the property does not exist, an empty string is returned. function Get_Property (Controller : in Configuration; Name : in String) return String; -- Set the server hostname. procedure Set_Server (Controller : in out Configuration; Server : in String); -- Get the server hostname. function Get_Server (Controller : in Configuration) return String; -- Set the server port. procedure Set_Port (Controller : in out Configuration; Port : in Natural); -- Get the server port. function Get_Port (Controller : in Configuration) return Natural; -- Set the database name. procedure Set_Database (Controller : in out Configuration; Database : in String); -- Get the database name. function Get_Database (Controller : in Configuration) return String; -- Get the database driver name. function Get_Driver (Controller : in Configuration) return String; -- Create a new connection using the configuration parameters. procedure Create_Connection (Config : in Configuration'Class; Result : in out Ref.Ref'Class); -- ------------------------------ -- Database Driver -- ------------------------------ -- Create a new connection using the configuration parameters. procedure Create_Connection (D : in out Driver; Config : in Configuration'Class; Result : in out Ref.Ref'Class) is abstract; -- Get the driver unique index. function Get_Driver_Index (D : in Driver) return Driver_Index; -- Get the driver name. function Get_Driver_Name (D : in Driver) return String; -- Register a database driver. procedure Register (Driver : in Driver_Access); -- Get a database driver given its name. function Get_Driver (Name : in String) return Driver_Access; private type Driver is abstract new Ada.Finalization.Limited_Controlled with record Name : Util.Strings.Name_Access; Index : Driver_Index; end record; type Configuration is new Ada.Finalization.Controlled with record URI : Unbounded_String; Log_URI : Unbounded_String; Server : Unbounded_String; Port : Natural := 0; Database : Unbounded_String; Properties : Util.Properties.Manager; Driver : Driver_Access; end record; end ADO.Drivers.Connections;
----------------------------------------------------------------------- -- ADO Drivers -- Database Drivers -- Copyright (C) 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 Ada.Finalization; with ADO.Statements; with ADO.Schemas; with Util.Properties; with Util.Strings; with Util.Refs; -- The <b>ADO.Drivers</b> package represents the database driver that will create -- database connections and provide the database specific implementation. package ADO.Drivers.Connections is use ADO.Statements; type Driver is abstract tagged limited private; type Driver_Access is access all Driver'Class; -- ------------------------------ -- Database connection implementation -- ------------------------------ -- type Database_Connection is abstract new Util.Refs.Ref_Entity with record Ident : String (1 .. 8) := (others => ' '); end record; type Database_Connection_Access is access all Database_Connection'Class; -- Get the database driver index. function Get_Driver_Index (Database : in Database_Connection) return Driver_Index; function Create_Statement (Database : in Database_Connection; Table : in ADO.Schemas.Class_Mapping_Access) return Query_Statement_Access is abstract; function Create_Statement (Database : in Database_Connection; Query : in String) return Query_Statement_Access is abstract; -- Create a delete statement. function Create_Statement (Database : in Database_Connection; Table : in ADO.Schemas.Class_Mapping_Access) return Delete_Statement_Access is abstract; -- Create an insert statement. function Create_Statement (Database : in Database_Connection; Table : in ADO.Schemas.Class_Mapping_Access) return Insert_Statement_Access is abstract; -- Create an update statement. function Create_Statement (Database : in Database_Connection; Table : in ADO.Schemas.Class_Mapping_Access) return Update_Statement_Access is abstract; -- Start a transaction. procedure Begin_Transaction (Database : in out Database_Connection) is abstract; -- Commit the current transaction. procedure Commit (Database : in out Database_Connection) is abstract; -- Rollback the current transaction. procedure Rollback (Database : in out Database_Connection) is abstract; -- Load the database schema definition for the current database. procedure Load_Schema (Database : in Database_Connection; Schema : out ADO.Schemas.Schema_Definition) is abstract; -- Get the database driver which manages this connection. function Get_Driver (Database : in Database_Connection) return Driver_Access is abstract; -- Closes the database connection procedure Close (Database : in out Database_Connection) is abstract; package Ref is new Util.Refs.Indefinite_References (Element_Type => Database_Connection'Class, Element_Access => Database_Connection_Access); -- ------------------------------ -- The database configuration properties -- ------------------------------ type Configuration is new Ada.Finalization.Controlled with private; type Configuration_Access is access all Configuration'Class; -- Set the connection URL to connect to the database. -- The driver connection is a string of the form: -- -- driver://[host][:port]/[database][?property1][=value1]... -- -- If the string is invalid or if the driver cannot be found, -- the Connection_Error exception is raised. procedure Set_Connection (Controller : in out Configuration; URI : in String); -- Set a property on the datasource for the driver. -- The driver can retrieve the property to configure and open -- the database connection. procedure Set_Property (Controller : in out Configuration; Name : in String; Value : in String); -- Get a property from the data source configuration. -- If the property does not exist, an empty string is returned. function Get_Property (Controller : in Configuration; Name : in String) return String; -- Set the server hostname. procedure Set_Server (Controller : in out Configuration; Server : in String); -- Get the server hostname. function Get_Server (Controller : in Configuration) return String; -- Set the server port. procedure Set_Port (Controller : in out Configuration; Port : in Natural); -- Get the server port. function Get_Port (Controller : in Configuration) return Natural; -- Set the database name. procedure Set_Database (Controller : in out Configuration; Database : in String); -- Get the database name. function Get_Database (Controller : in Configuration) return String; -- Get the database driver name. function Get_Driver (Controller : in Configuration) return String; -- Get the database driver index. function Get_Driver (Controller : in Configuration) return Driver_Index; -- Create a new connection using the configuration parameters. procedure Create_Connection (Config : in Configuration'Class; Result : in out Ref.Ref'Class); -- ------------------------------ -- Database Driver -- ------------------------------ -- Create a new connection using the configuration parameters. procedure Create_Connection (D : in out Driver; Config : in Configuration'Class; Result : in out Ref.Ref'Class) is abstract; -- Get the driver unique index. function Get_Driver_Index (D : in Driver) return Driver_Index; -- Get the driver name. function Get_Driver_Name (D : in Driver) return String; -- Register a database driver. procedure Register (Driver : in Driver_Access); -- Get a database driver given its name. function Get_Driver (Name : in String) return Driver_Access; private type Driver is abstract new Ada.Finalization.Limited_Controlled with record Name : Util.Strings.Name_Access; Index : Driver_Index; end record; type Configuration is new Ada.Finalization.Controlled with record URI : Unbounded_String; Log_URI : Unbounded_String; Server : Unbounded_String; Port : Natural := 0; Database : Unbounded_String; Properties : Util.Properties.Manager; Driver : Driver_Access; end record; end ADO.Drivers.Connections;
Declare the Get_Driver function
Declare the Get_Driver function
Ada
apache-2.0
stcarrez/ada-ado
5419684f7b5e985a97db5e9385384b69849ac52b
awa/src/awa-permissions.adb
awa/src/awa-permissions.adb
----------------------------------------------------------------------- -- awa-permissions -- Permissions module -- Copyright (C) 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 Util.Log.Loggers; with Util.Beans.Objects; with Util.Serialize.Mappers.Record_Mapper; with ADO.Schemas.Entities; with ADO.Sessions.Entities; with Security.Contexts; with AWA.Services.Contexts; with AWA.Permissions.Controllers; package body AWA.Permissions is use Util.Log; Log : constant Loggers.Logger := Loggers.Create ("AWA.Permissions"); -- ------------------------------ -- Verify that the permission represented by <b>Permission</b> is granted. -- ------------------------------ procedure Check (Permission : in Security.Permissions.Permission_Index) is begin if not (Security.Contexts.Has_Permission (Permission)) then raise NO_PERMISSION; end if; end Check; -- ------------------------------ -- Verify that the permission represented by <b>Permission</b> is granted to access the -- database entity represented by <b>Entity</b>. -- ------------------------------ procedure Check (Permission : in Security.Permissions.Permission_Index; Entity : in ADO.Identifier) is use type Security.Contexts.Security_Context_Access; Context : constant Security.Contexts.Security_Context_Access := Security.Contexts.Current; Perm : Entity_Permission (Permission); begin if Context = null then Log.Debug ("There is no security context, permission denied"); raise NO_PERMISSION; end if; Perm.Entity := Entity; if not (Security.Contexts.Has_Permission (Perm)) then Log.Debug ("Permission is refused"); raise NO_PERMISSION; end if; end Check; type Controller_Config is record Name : Util.Beans.Objects.Object; SQL : Util.Beans.Objects.Object; Entity : ADO.Entity_Type := 0; Count : Natural := 0; Manager : Entity_Policy_Access; Session : ADO.Sessions.Session; end record; type Config_Fields is (FIELD_NAME, FIELD_ENTITY_TYPE, FIELD_ENTITY_PERMISSION, FIELD_SQL); 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>, <entity-type>, <sql> and -- <entity-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 AWA.Permissions.Controllers; use type ADO.Entity_Type; begin case Field is when FIELD_NAME => Into.Name := Value; when FIELD_SQL => Into.SQL := Value; when FIELD_ENTITY_TYPE => declare Name : constant String := Util.Beans.Objects.To_String (Value); begin Into.Entity := ADO.Sessions.Entities.Find_Entity_Type (Into.Session, Name); exception when ADO.Schemas.Entities.No_Entity_Type => raise Util.Serialize.Mappers.Field_Error with "Invalid entity type: " & Name; end; when FIELD_ENTITY_PERMISSION => declare Name : constant String := Util.Beans.Objects.To_String (Into.Name); begin if Into.Entity = 0 then raise Util.Serialize.Mappers.Field_Error with "Permission '" & Name & "' ignored: missing entity type"; end if; declare SQL : constant String := Util.Beans.Objects.To_String (Into.SQL); Perm : constant Entity_Controller_Access := new Entity_Controller '(Len => SQL'Length, SQL => SQL, Entity => Into.Entity); begin Into.Manager.Add_Permission (Name, Perm.all'Access); Into.Count := 0; Into.Entity := 0; end; 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>entity-permission</b> description. For example: -- -- <entity-permission> -- <name>create-workspace</name> -- <entity-type>WORKSPACE</entity-type> -- <sql>select acl.id from acl where ...</sql> -- </entity-permission> -- -- This defines a permission <b>create-workspace</b> that will be granted if the -- SQL statement returns a non empty list. -- ------------------------------ -- Get the policy name. overriding function Get_Name (From : in Entity_Policy) return String is begin return NAME; end Get_Name; -- Setup the XML parser to read the <b>policy</b> description. overriding procedure Prepare_Config (Policy : in out Entity_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.Session := AWA.Services.Contexts.Get_Session (AWA.Services.Contexts.Current); Config_Mapper.Set_Context (Reader, Config); end Prepare_Config; -- Finish reading the XML policy configuration. The security policy implementation can use -- this procedure to perform any configuration setup after the configuration is parsed. overriding procedure Finish_Config (Into : in out Entity_Policy; Reader : in out Util.Serialize.IO.XML.Parser) is begin null; end Finish_Config; begin Mapper.Add_Mapping ("entity-permission", FIELD_ENTITY_PERMISSION); Mapper.Add_Mapping ("entity-permission/name", FIELD_NAME); Mapper.Add_Mapping ("entity-permission/entity-type", FIELD_ENTITY_TYPE); Mapper.Add_Mapping ("entity-permission/sql", FIELD_SQL); end AWA.Permissions;
----------------------------------------------------------------------- -- awa-permissions -- Permissions module -- Copyright (C) 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 Util.Log.Loggers; with Util.Beans.Objects; with Util.Serialize.Mappers.Record_Mapper; with ADO.Schemas.Entities; with ADO.Sessions.Entities; with Security.Contexts; with AWA.Services.Contexts; with AWA.Permissions.Controllers; package body AWA.Permissions is use Util.Log; Log : constant Loggers.Logger := Loggers.Create ("AWA.Permissions"); -- ------------------------------ -- Verify that the permission represented by <b>Permission</b> is granted. -- ------------------------------ procedure Check (Permission : in Security.Permissions.Permission_Index) is begin if not (Security.Contexts.Has_Permission (Permission)) then raise NO_PERMISSION; end if; end Check; -- ------------------------------ -- Verify that the permission represented by <b>Permission</b> is granted to access the -- database entity represented by <b>Entity</b>. -- ------------------------------ procedure Check (Permission : in Security.Permissions.Permission_Index; Entity : in ADO.Identifier) is use type Security.Contexts.Security_Context_Access; Context : constant Security.Contexts.Security_Context_Access := Security.Contexts.Current; Perm : Entity_Permission (Permission); Result : Boolean; begin if Context = null then Log.Debug ("There is no security context, permission denied"); raise NO_PERMISSION; end if; Perm.Entity := Entity; Context.Has_Permission (Perm, Result); if not Result then Log.Debug ("Permission is refused"); raise NO_PERMISSION; end if; end Check; type Controller_Config is record Name : Util.Beans.Objects.Object; SQL : Util.Beans.Objects.Object; Entity : ADO.Entity_Type := 0; Count : Natural := 0; Manager : Entity_Policy_Access; Session : ADO.Sessions.Session; end record; type Config_Fields is (FIELD_NAME, FIELD_ENTITY_TYPE, FIELD_ENTITY_PERMISSION, FIELD_SQL); 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>, <entity-type>, <sql> and -- <entity-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 AWA.Permissions.Controllers; use type ADO.Entity_Type; begin case Field is when FIELD_NAME => Into.Name := Value; when FIELD_SQL => Into.SQL := Value; when FIELD_ENTITY_TYPE => declare Name : constant String := Util.Beans.Objects.To_String (Value); begin Into.Entity := ADO.Sessions.Entities.Find_Entity_Type (Into.Session, Name); exception when ADO.Schemas.Entities.No_Entity_Type => raise Util.Serialize.Mappers.Field_Error with "Invalid entity type: " & Name; end; when FIELD_ENTITY_PERMISSION => declare Name : constant String := Util.Beans.Objects.To_String (Into.Name); begin if Into.Entity = 0 then raise Util.Serialize.Mappers.Field_Error with "Permission '" & Name & "' ignored: missing entity type"; end if; declare SQL : constant String := Util.Beans.Objects.To_String (Into.SQL); Perm : constant Entity_Controller_Access := new Entity_Controller '(Len => SQL'Length, SQL => SQL, Entity => Into.Entity); begin Into.Manager.Add_Permission (Name, Perm.all'Access); Into.Count := 0; Into.Entity := 0; end; 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>entity-permission</b> description. For example: -- -- <entity-permission> -- <name>create-workspace</name> -- <entity-type>WORKSPACE</entity-type> -- <sql>select acl.id from acl where ...</sql> -- </entity-permission> -- -- This defines a permission <b>create-workspace</b> that will be granted if the -- SQL statement returns a non empty list. -- ------------------------------ -- Get the policy name. overriding function Get_Name (From : in Entity_Policy) return String is begin return NAME; end Get_Name; -- Setup the XML parser to read the <b>policy</b> description. overriding procedure Prepare_Config (Policy : in out Entity_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.Session := AWA.Services.Contexts.Get_Session (AWA.Services.Contexts.Current); Config_Mapper.Set_Context (Reader, Config); end Prepare_Config; -- Finish reading the XML policy configuration. The security policy implementation can use -- this procedure to perform any configuration setup after the configuration is parsed. overriding procedure Finish_Config (Into : in out Entity_Policy; Reader : in out Util.Serialize.IO.XML.Parser) is begin null; end Finish_Config; begin Mapper.Add_Mapping ("entity-permission", FIELD_ENTITY_PERMISSION); Mapper.Add_Mapping ("entity-permission/name", FIELD_NAME); Mapper.Add_Mapping ("entity-permission/entity-type", FIELD_ENTITY_TYPE); Mapper.Add_Mapping ("entity-permission/sql", FIELD_SQL); end AWA.Permissions;
Fix Check_Permission
Fix Check_Permission
Ada
apache-2.0
tectronics/ada-awa,tectronics/ada-awa,tectronics/ada-awa,Letractively/ada-awa,Letractively/ada-awa,Letractively/ada-awa
767a461d5d848d9e7112398d5438f0e5099a1422
src/util-texts.ads
src/util-texts.ads
----------------------------------------------------------------------- -- Util-texts -- Various Text Utilities -- Copyright (C) 2001, 2002, 2003, 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. ----------------------------------------------------------------------- package Util.Texts is pragma Pure; end Util.Texts;
----------------------------------------------------------------------- -- util-texts -- Various Text Utilities -- Copyright (C) 2001, 2002, 2003, 2009, 2010, 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. ----------------------------------------------------------------------- package Util.Texts is pragma Pure; end Util.Texts;
Update the header
Update the header
Ada
apache-2.0
stcarrez/ada-util,stcarrez/ada-util
221a9f4be3f3ce6e3c8d1c3ac4f22c0e54b6ce73
awa/plugins/awa-blogs/src/awa-blogs-modules.ads
awa/plugins/awa-blogs/src/awa-blogs-modules.ads
----------------------------------------------------------------------- -- awa-blogs-module -- Blog and post management module -- Copyright (C) 2011, 2012, 2013, 2014, 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 Ada.Strings.Unbounded; with Ada.Calendar; with ASF.Applications; with ADO; with Wiki.Strings; with AWA.Modules; with AWA.Blogs.Models; with AWA.Counters.Definition; with Security.Permissions; -- == Integration == -- The <tt>Blog_Module</tt> manages the creation, update, removal of blog posts in an application. -- It provides operations that are used by the blog beans or other services to create and update -- posts. An instance of the <tt>Blog_Module</tt> must be declared and registered in the -- AWA application. The module instance can be defined as follows: -- -- type Application is new AWA.Applications.Application with record -- Blog_Module : aliased AWA.Blogs.Modules.Blog_Module; -- end record; -- -- And registered in the `Initialize_Modules` procedure by using: -- -- Register (App => App.Self.all'Access, -- Name => AWA.Blogs.Modules.NAME, -- URI => "blogs", -- Module => App.Blog_Module'Access); -- package AWA.Blogs.Modules is NAME : constant String := "blogs"; -- The configuration parameter that defines the image link prefix in rendered HTML content. PARAM_IMAGE_PREFIX : constant String := "image_prefix"; -- Define the permissions. package ACL_Create_Blog is new Security.Permissions.Definition ("blog-create"); package ACL_Delete_Blog is new Security.Permissions.Definition ("blog-delete"); package ACL_Create_Post is new Security.Permissions.Definition ("blog-create-post"); package ACL_Delete_Post is new Security.Permissions.Definition ("blog-delete-post"); package ACL_Update_Post is new Security.Permissions.Definition ("blog-update-post"); -- Define the read post counter. package Read_Counter is new AWA.Counters.Definition (Models.POST_TABLE, "read_count"); Not_Found : exception; type Blog_Module is new AWA.Modules.Module with private; type Blog_Module_Access is access all Blog_Module'Class; -- Initialize the blog module. overriding procedure Initialize (Plugin : in out Blog_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 Blog_Module; Props : in ASF.Applications.Config); -- Get the blog module instance associated with the current application. function Get_Blog_Module return Blog_Module_Access; -- Create a new blog for the user workspace. procedure Create_Blog (Model : in Blog_Module; Title : in String; Result : out ADO.Identifier); -- Create a new post associated with the given blog identifier. procedure Create_Post (Model : in Blog_Module; Blog_Id : in ADO.Identifier; Title : in String; URI : in String; Text : in String; Comment : in Boolean; Status : in AWA.Blogs.Models.Post_Status_Type; Result : out ADO.Identifier); -- Update the post title and text associated with the blog post identified by <b>Post</b>. procedure Update_Post (Model : in Blog_Module; Post_Id : in ADO.Identifier; Title : in String; URI : in String; Text : in String; Comment : in Boolean; Status : in AWA.Blogs.Models.Post_Status_Type); -- Delete the post identified by the given identifier. procedure Delete_Post (Model : in Blog_Module; Post_Id : in ADO.Identifier); -- Load the image data associated with a blog post. The image must be public and the -- post visible for the image to be retrieved by anonymous users. procedure Load_Image (Model : in Blog_Module; Post_Id : in ADO.Identifier; Image_Id : in ADO.Identifier; Width : in out Natural; Height : in out Natural; Mime : out Ada.Strings.Unbounded.Unbounded_String; Date : out Ada.Calendar.Time; Into : out ADO.Blob_Ref); private type Blog_Module is new AWA.Modules.Module with record Image_Prefix : Wiki.Strings.UString; end record; end AWA.Blogs.Modules;
----------------------------------------------------------------------- -- awa-blogs-module -- Blog and post management module -- Copyright (C) 2011, 2012, 2013, 2014, 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 Ada.Strings.Unbounded; with Ada.Calendar; with ASF.Applications; with ADO; with Wiki.Strings; with AWA.Modules; with AWA.Blogs.Models; with AWA.Counters.Definition; with Security.Permissions; -- == Integration == -- The <tt>Blog_Module</tt> manages the creation, update, removal of blog posts in an application. -- It provides operations that are used by the blog beans or other services to create and update -- posts. An instance of the <tt>Blog_Module</tt> must be declared and registered in the -- AWA application. The module instance can be defined as follows: -- -- type Application is new AWA.Applications.Application with record -- Blog_Module : aliased AWA.Blogs.Modules.Blog_Module; -- end record; -- -- And registered in the `Initialize_Modules` procedure by using: -- -- Register (App => App.Self.all'Access, -- Name => AWA.Blogs.Modules.NAME, -- URI => "blogs", -- Module => App.Blog_Module'Access); -- package AWA.Blogs.Modules is NAME : constant String := "blogs"; -- The configuration parameter that defines the image link prefix in rendered HTML content. PARAM_IMAGE_PREFIX : constant String := "image_prefix"; -- Define the permissions. package ACL_Create_Blog is new Security.Permissions.Definition ("blog-create"); package ACL_Delete_Blog is new Security.Permissions.Definition ("blog-delete"); package ACL_Create_Post is new Security.Permissions.Definition ("blog-create-post"); package ACL_Delete_Post is new Security.Permissions.Definition ("blog-delete-post"); package ACL_Update_Post is new Security.Permissions.Definition ("blog-update-post"); -- Define the read post counter. package Read_Counter is new AWA.Counters.Definition (Models.POST_TABLE, "read_count"); Not_Found : exception; type Blog_Module is new AWA.Modules.Module with private; type Blog_Module_Access is access all Blog_Module'Class; -- Initialize the blog module. overriding procedure Initialize (Plugin : in out Blog_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 Blog_Module; Props : in ASF.Applications.Config); -- Get the blog module instance associated with the current application. function Get_Blog_Module return Blog_Module_Access; -- Get the image prefix that was configured for the Blog module. function Get_Image_Prefix (Module : in Blog_Module) return Wiki.Strings.UString; -- Create a new blog for the user workspace. procedure Create_Blog (Model : in Blog_Module; Title : in String; Result : out ADO.Identifier); -- Create a new post associated with the given blog identifier. procedure Create_Post (Model : in Blog_Module; Blog_Id : in ADO.Identifier; Title : in String; URI : in String; Text : in String; Comment : in Boolean; Status : in AWA.Blogs.Models.Post_Status_Type; Result : out ADO.Identifier); -- Update the post title and text associated with the blog post identified by <b>Post</b>. procedure Update_Post (Model : in Blog_Module; Post_Id : in ADO.Identifier; Title : in String; URI : in String; Text : in String; Comment : in Boolean; Status : in AWA.Blogs.Models.Post_Status_Type); -- Delete the post identified by the given identifier. procedure Delete_Post (Model : in Blog_Module; Post_Id : in ADO.Identifier); -- Load the image data associated with a blog post. The image must be public and the -- post visible for the image to be retrieved by anonymous users. procedure Load_Image (Model : in Blog_Module; Post_Id : in ADO.Identifier; Image_Id : in ADO.Identifier; Width : in out Natural; Height : in out Natural; Mime : out Ada.Strings.Unbounded.Unbounded_String; Date : out Ada.Calendar.Time; Into : out ADO.Blob_Ref); private type Blog_Module is new AWA.Modules.Module with record Image_Prefix : Wiki.Strings.UString; end record; end AWA.Blogs.Modules;
Declare the Get_Image_Prefix function
Declare the Get_Image_Prefix function
Ada
apache-2.0
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
31f63ced73ed87adc91e0e7f8d8f167bf61e0073
src/util-files.adb
src/util-files.adb
----------------------------------------------------------------------- -- Util.Files -- Various File Utility Packages -- Copyright (C) 2001, 2002, 2003, 2009, 2010, 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 Ada.Directories; with Ada.Strings.Fixed; with Ada.Streams; with Ada.Streams.Stream_IO; with Ada.Text_IO; with Util.Strings.Tokenizers; package body Util.Files is -- ------------------------------ -- Read a complete file into a string. -- The <b>Max_Size</b> parameter indicates the maximum size that is read. -- ------------------------------ procedure Read_File (Path : in String; Into : out Unbounded_String; Max_Size : in Natural := 0) is use Ada.Streams; use Ada.Streams.Stream_IO; F : File_Type; Buffer : Stream_Element_Array (1 .. 10_000); Pos : Positive_Count := 1; Last : Stream_Element_Offset; Space : Natural; begin if Max_Size = 0 then Space := Natural'Last; else Space := Max_Size; end if; Open (Name => Path, File => F, Mode => In_File); loop Read (File => F, Item => Buffer, From => Pos, Last => Last); if Natural (Last) > Space then Last := Stream_Element_Offset (Space); end if; for I in 1 .. Last loop Append (Into, Character'Val (Buffer (I))); end loop; exit when Last < Buffer'Length; Pos := Pos + Positive_Count (Last); end loop; Close (F); exception when others => if Is_Open (F) then Close (F); end if; raise; end Read_File; -- ------------------------------ -- Read the file with the given path, one line at a time and execute the <b>Process</b> -- procedure with each line as argument. -- ------------------------------ procedure Read_File (Path : in String; Process : not null access procedure (Line : in String)) is File : Ada.Text_IO.File_Type; begin Ada.Text_IO.Open (File => File, Mode => Ada.Text_IO.In_File, Name => Path); while not Ada.Text_IO.End_Of_File (File) loop Process (Ada.Text_IO.Get_Line (File)); end loop; Ada.Text_IO.Close (File); end Read_File; -- ------------------------------ -- Save the string into a file creating the file if necessary -- ------------------------------ procedure Write_File (Path : in String; Content : in String) is use Ada.Streams; use Ada.Streams.Stream_IO; use Ada.Directories; F : File_Type; Buffer : Stream_Element_Array (Stream_Element_Offset (Content'First) .. Stream_Element_Offset (Content'Last)); Dir : constant String := Containing_Directory (Path); begin if not Exists (Dir) then Create_Path (Dir); end if; Create (File => F, Name => Path); for I in Content'Range loop Buffer (Stream_Element_Offset (I)) := Stream_Element (Character'Pos (Content (I))); end loop; Write (F, Buffer); Close (F); exception when others => if Is_Open (F) then Close (F); end if; raise; end Write_File; -- ------------------------------ -- Save the string into a file creating the file if necessary -- ------------------------------ procedure Write_File (Path : in String; Content : in Unbounded_String) is begin Write_File (Path, Ada.Strings.Unbounded.To_String (Content)); end Write_File; -- ------------------------------ -- Iterate over the search directories defined in <b>Paths</b> and execute -- <b>Process</b> with each directory until it returns <b>True</b> in <b>Done</b> -- or the last search directory is found. Each search directory -- is separated by ';' (yes, even on Unix). When <b>Going</b> is set to Backward, the -- directories are searched in reverse order. -- ------------------------------ procedure Iterate_Path (Path : in String; Process : not null access procedure (Dir : in String; Done : out Boolean); Going : in Direction := Ada.Strings.Forward) is begin Util.Strings.Tokenizers.Iterate_Tokens (Content => Path, Pattern => ";", Process => Process, Going => Going); end Iterate_Path; -- ------------------------------ -- Find the file in one of the search directories. Each search directory -- is separated by ';' (yes, even on Unix). -- Returns the path to be used for reading the file. -- ------------------------------ function Find_File_Path (Name : String; Paths : String) return String is use Ada.Directories; use Ada.Strings.Fixed; Sep_Pos : Natural; Pos : Positive := Paths'First; Last : constant Natural := Paths'Last; begin while Pos <= Last loop Sep_Pos := Index (Paths, ";", Pos); if Sep_Pos = 0 then Sep_Pos := Last; else Sep_Pos := Sep_Pos - 1; end if; declare Path : constant String := Util.Files.Compose (Paths (Pos .. Sep_Pos), Name); begin if Exists (Path) and then Kind (Path) = Ordinary_File then return Path; end if; exception when Name_Error => null; end; Pos := Sep_Pos + 2; end loop; return Name; end Find_File_Path; -- ------------------------------ -- Iterate over the search directories defined in <b>Path</b> and search -- for files matching the pattern defined by <b>Pattern</b>. For each file, -- execute <b>Process</b> with the file basename and the full file path. -- Stop iterating when the <b>Process</b> procedure returns True. -- Each search directory is separated by ';'. When <b>Going</b> is set to Backward, the -- directories are searched in reverse order. -- ------------------------------ procedure Iterate_Files_Path (Pattern : in String; Path : in String; Process : not null access procedure (Name : in String; File : in String; Done : out Boolean); Going : in Direction := Ada.Strings.Forward) is procedure Find_Files (Dir : in String; Done : out Boolean); -- ------------------------------ -- Find the files matching the pattern in <b>Dir</b>. -- ------------------------------ procedure Find_Files (Dir : in String; Done : out Boolean) is use Ada.Directories; Filter : constant Filter_Type := (Ordinary_File => True, others => False); Ent : Directory_Entry_Type; Search : Search_Type; begin Done := False; Start_Search (Search, Directory => Dir, Pattern => Pattern, Filter => Filter); while More_Entries (Search) loop Get_Next_Entry (Search, Ent); declare Name : constant String := Simple_Name (Ent); File_Path : constant String := Full_Name (Ent); begin Process (Name, File_Path, Done); exit when Done; end; end loop; end Find_Files; begin Iterate_Path (Path => Path, Process => Find_Files'Access, Going => Going); end Iterate_Files_Path; -- ------------------------------ -- Find the files which match the pattern in the directories specified in the -- search path <b>Path</b>. Each search directory is separated by ';'. -- File names are added to the string set in <b>Into</b>. -- ------------------------------ procedure Find_Files_Path (Pattern : in String; Path : in String; Into : in out Util.Strings.Maps.Map) is procedure Add_File (Name : in String; File_Path : in String; Done : out Boolean); -- ------------------------------ -- Find the files matching the pattern in <b>Dir</b>. -- ------------------------------ procedure Add_File (Name : in String; File_Path : in String; Done : out Boolean) is begin if not Into.Contains (Name) then Into.Insert (Name, File_Path); end if; Done := False; end Add_File; begin Iterate_Files_Path (Pattern => Pattern, Path => Path, Process => Add_File'Access); end Find_Files_Path; -- ------------------------------ -- Compose an existing path by adding the specified name to each path component -- and return a new paths having only existing directories. Each directory is -- separated by ';'. -- If the composed path exists, it is added to the result path. -- Example: -- paths = 'web;regtests' name = 'info' -- result = 'web/info;regtests/info' -- Returns the composed path. -- ------------------------------ function Compose_Path (Paths : in String; Name : in String) return String is procedure Compose (Dir : in String; Done : out Boolean); Result : Unbounded_String; -- ------------------------------ -- Build the new path by checking if <b>Name</b> exists in <b>Dir</b> -- and appending the new path in the <b>Result</b>. -- ------------------------------ procedure Compose (Dir : in String; Done : out Boolean) is use Ada.Directories; use Ada.Strings.Fixed; Path : constant String := Util.Files.Compose (Dir, Name); begin Done := False; if Exists (Path) and then Kind (Path) = Directory then if Length (Result) > 0 then Append (Result, ';'); end if; Append (Result, Path); end if; exception when Name_Error => null; end Compose; begin Iterate_Path (Path => Paths, Process => Compose'Access); return To_String (Result); end Compose_Path; -- ------------------------------ -- Returns the name of the external file with the specified directory -- and the name. Unlike the Ada.Directories.Compose, the name can represent -- a relative path and thus include directory separators. -- ------------------------------ function Compose (Directory : in String; Name : in String) return String is begin if Name'Length = 0 then return Directory; elsif Directory'Length = 0 then return Name; elsif Directory = "." or Directory = "./" then if Name (Name'First) /= '/' then return Name; else return Compose (Directory, Name (Name'First + 1 .. Name'Last)); end if; elsif Directory (Directory'Last) = '/' and Name (Name'First) = '/' then return Directory & Name (Name'First + 1 .. Name'Last); elsif Directory (Directory'Last) = '/' or Name (Name'First) = '/' then return Directory & Name; else return Directory & "/" & Name; end if; end Compose; -- ------------------------------ -- Returns a relative path whose origin is defined by <b>From</b> and which refers -- to the absolute path referenced by <b>To</b>. Both <b>From</b> and <b>To</b> are -- assumed to be absolute pathes. Returns the absolute path <b>To</b> if the relative -- path could not be found. Both paths must have at least one root component in common. -- ------------------------------ function Get_Relative_Path (From : in String; To : in String) return String is Result : Unbounded_String; Last : Natural := 0; begin for I in From'Range loop if I > To'Last or else From (I) /= To (I) then -- Nothing in common, return the absolute path <b>To</b>. if Last <= From'First + 1 then return To; end if; for J in Last .. From'Last - 1 loop if From (J) = '/' or From (J) = '\' then Append (Result, "../"); end if; end loop; if Last <= To'Last and From (I) /= '/' and From (I) /= '\' then Append (Result, "../"); Append (Result, To (Last .. To'Last)); end if; return To_String (Result); elsif I < From'Last and then (From (I) = '/' or From (I) = '\') then Last := I + 1; end if; end loop; if To'Last = From'Last or (To'Last = From'Last + 1 and (To (To'Last) = '/' or To (To'Last) = '\')) then return "."; elsif Last = 0 then return To; elsif To (From'Last + 1) = '/' or To (From'Last + 1) = '\' then return To (From'Last + 2 .. To'Last); else return To (Last .. To'Last); end if; end Get_Relative_Path; end Util.Files;
----------------------------------------------------------------------- -- Util.Files -- Various File Utility Packages -- Copyright (C) 2001, 2002, 2003, 2009, 2010, 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 Ada.Directories; with Ada.Strings.Fixed; with Ada.Streams; with Ada.Streams.Stream_IO; with Ada.Text_IO; with Util.Strings.Tokenizers; package body Util.Files is -- ------------------------------ -- Read a complete file into a string. -- The <b>Max_Size</b> parameter indicates the maximum size that is read. -- ------------------------------ procedure Read_File (Path : in String; Into : out Unbounded_String; Max_Size : in Natural := 0) is use Ada.Streams; use Ada.Streams.Stream_IO; F : File_Type; Buffer : Stream_Element_Array (1 .. 10_000); Pos : Positive_Count := 1; Last : Stream_Element_Offset; Space : Natural; begin if Max_Size = 0 then Space := Natural'Last; else Space := Max_Size; end if; Open (Name => Path, File => F, Mode => In_File); loop Read (File => F, Item => Buffer, From => Pos, Last => Last); if Natural (Last) > Space then Last := Stream_Element_Offset (Space); end if; for I in 1 .. Last loop Append (Into, Character'Val (Buffer (I))); end loop; exit when Last < Buffer'Length; Pos := Pos + Positive_Count (Last); end loop; Close (F); exception when others => if Is_Open (F) then Close (F); end if; raise; end Read_File; -- ------------------------------ -- Read the file with the given path, one line at a time and execute the <b>Process</b> -- procedure with each line as argument. -- ------------------------------ procedure Read_File (Path : in String; Process : not null access procedure (Line : in String)) is File : Ada.Text_IO.File_Type; begin Ada.Text_IO.Open (File => File, Mode => Ada.Text_IO.In_File, Name => Path); while not Ada.Text_IO.End_Of_File (File) loop Process (Ada.Text_IO.Get_Line (File)); end loop; Ada.Text_IO.Close (File); end Read_File; -- ------------------------------ -- Read the file with the given path, one line at a time and append each line to -- the <b>Into</b> vector. -- ------------------------------ procedure Read_File (Path : in String; Into : in out Util.Strings.Vectors.Vector) is procedure Append (Line : in String); procedure Append (Line : in String) is begin Into.Append (Line); end Append; begin Read_File (Path, Append'Access); end Read_File; -- ------------------------------ -- Save the string into a file creating the file if necessary -- ------------------------------ procedure Write_File (Path : in String; Content : in String) is use Ada.Streams; use Ada.Streams.Stream_IO; use Ada.Directories; F : File_Type; Buffer : Stream_Element_Array (Stream_Element_Offset (Content'First) .. Stream_Element_Offset (Content'Last)); Dir : constant String := Containing_Directory (Path); begin if not Exists (Dir) then Create_Path (Dir); end if; Create (File => F, Name => Path); for I in Content'Range loop Buffer (Stream_Element_Offset (I)) := Stream_Element (Character'Pos (Content (I))); end loop; Write (F, Buffer); Close (F); exception when others => if Is_Open (F) then Close (F); end if; raise; end Write_File; -- ------------------------------ -- Save the string into a file creating the file if necessary -- ------------------------------ procedure Write_File (Path : in String; Content : in Unbounded_String) is begin Write_File (Path, Ada.Strings.Unbounded.To_String (Content)); end Write_File; -- ------------------------------ -- Iterate over the search directories defined in <b>Paths</b> and execute -- <b>Process</b> with each directory until it returns <b>True</b> in <b>Done</b> -- or the last search directory is found. Each search directory -- is separated by ';' (yes, even on Unix). When <b>Going</b> is set to Backward, the -- directories are searched in reverse order. -- ------------------------------ procedure Iterate_Path (Path : in String; Process : not null access procedure (Dir : in String; Done : out Boolean); Going : in Direction := Ada.Strings.Forward) is begin Util.Strings.Tokenizers.Iterate_Tokens (Content => Path, Pattern => ";", Process => Process, Going => Going); end Iterate_Path; -- ------------------------------ -- Find the file in one of the search directories. Each search directory -- is separated by ';' (yes, even on Unix). -- Returns the path to be used for reading the file. -- ------------------------------ function Find_File_Path (Name : String; Paths : String) return String is use Ada.Directories; use Ada.Strings.Fixed; Sep_Pos : Natural; Pos : Positive := Paths'First; Last : constant Natural := Paths'Last; begin while Pos <= Last loop Sep_Pos := Index (Paths, ";", Pos); if Sep_Pos = 0 then Sep_Pos := Last; else Sep_Pos := Sep_Pos - 1; end if; declare Path : constant String := Util.Files.Compose (Paths (Pos .. Sep_Pos), Name); begin if Exists (Path) and then Kind (Path) = Ordinary_File then return Path; end if; exception when Name_Error => null; end; Pos := Sep_Pos + 2; end loop; return Name; end Find_File_Path; -- ------------------------------ -- Iterate over the search directories defined in <b>Path</b> and search -- for files matching the pattern defined by <b>Pattern</b>. For each file, -- execute <b>Process</b> with the file basename and the full file path. -- Stop iterating when the <b>Process</b> procedure returns True. -- Each search directory is separated by ';'. When <b>Going</b> is set to Backward, the -- directories are searched in reverse order. -- ------------------------------ procedure Iterate_Files_Path (Pattern : in String; Path : in String; Process : not null access procedure (Name : in String; File : in String; Done : out Boolean); Going : in Direction := Ada.Strings.Forward) is procedure Find_Files (Dir : in String; Done : out Boolean); -- ------------------------------ -- Find the files matching the pattern in <b>Dir</b>. -- ------------------------------ procedure Find_Files (Dir : in String; Done : out Boolean) is use Ada.Directories; Filter : constant Filter_Type := (Ordinary_File => True, others => False); Ent : Directory_Entry_Type; Search : Search_Type; begin Done := False; Start_Search (Search, Directory => Dir, Pattern => Pattern, Filter => Filter); while More_Entries (Search) loop Get_Next_Entry (Search, Ent); declare Name : constant String := Simple_Name (Ent); File_Path : constant String := Full_Name (Ent); begin Process (Name, File_Path, Done); exit when Done; end; end loop; end Find_Files; begin Iterate_Path (Path => Path, Process => Find_Files'Access, Going => Going); end Iterate_Files_Path; -- ------------------------------ -- Find the files which match the pattern in the directories specified in the -- search path <b>Path</b>. Each search directory is separated by ';'. -- File names are added to the string set in <b>Into</b>. -- ------------------------------ procedure Find_Files_Path (Pattern : in String; Path : in String; Into : in out Util.Strings.Maps.Map) is procedure Add_File (Name : in String; File_Path : in String; Done : out Boolean); -- ------------------------------ -- Find the files matching the pattern in <b>Dir</b>. -- ------------------------------ procedure Add_File (Name : in String; File_Path : in String; Done : out Boolean) is begin if not Into.Contains (Name) then Into.Insert (Name, File_Path); end if; Done := False; end Add_File; begin Iterate_Files_Path (Pattern => Pattern, Path => Path, Process => Add_File'Access); end Find_Files_Path; -- ------------------------------ -- Compose an existing path by adding the specified name to each path component -- and return a new paths having only existing directories. Each directory is -- separated by ';'. -- If the composed path exists, it is added to the result path. -- Example: -- paths = 'web;regtests' name = 'info' -- result = 'web/info;regtests/info' -- Returns the composed path. -- ------------------------------ function Compose_Path (Paths : in String; Name : in String) return String is procedure Compose (Dir : in String; Done : out Boolean); Result : Unbounded_String; -- ------------------------------ -- Build the new path by checking if <b>Name</b> exists in <b>Dir</b> -- and appending the new path in the <b>Result</b>. -- ------------------------------ procedure Compose (Dir : in String; Done : out Boolean) is use Ada.Directories; use Ada.Strings.Fixed; Path : constant String := Util.Files.Compose (Dir, Name); begin Done := False; if Exists (Path) and then Kind (Path) = Directory then if Length (Result) > 0 then Append (Result, ';'); end if; Append (Result, Path); end if; exception when Name_Error => null; end Compose; begin Iterate_Path (Path => Paths, Process => Compose'Access); return To_String (Result); end Compose_Path; -- ------------------------------ -- Returns the name of the external file with the specified directory -- and the name. Unlike the Ada.Directories.Compose, the name can represent -- a relative path and thus include directory separators. -- ------------------------------ function Compose (Directory : in String; Name : in String) return String is begin if Name'Length = 0 then return Directory; elsif Directory'Length = 0 then return Name; elsif Directory = "." or Directory = "./" then if Name (Name'First) /= '/' then return Name; else return Compose (Directory, Name (Name'First + 1 .. Name'Last)); end if; elsif Directory (Directory'Last) = '/' and Name (Name'First) = '/' then return Directory & Name (Name'First + 1 .. Name'Last); elsif Directory (Directory'Last) = '/' or Name (Name'First) = '/' then return Directory & Name; else return Directory & "/" & Name; end if; end Compose; -- ------------------------------ -- Returns a relative path whose origin is defined by <b>From</b> and which refers -- to the absolute path referenced by <b>To</b>. Both <b>From</b> and <b>To</b> are -- assumed to be absolute pathes. Returns the absolute path <b>To</b> if the relative -- path could not be found. Both paths must have at least one root component in common. -- ------------------------------ function Get_Relative_Path (From : in String; To : in String) return String is Result : Unbounded_String; Last : Natural := 0; begin for I in From'Range loop if I > To'Last or else From (I) /= To (I) then -- Nothing in common, return the absolute path <b>To</b>. if Last <= From'First + 1 then return To; end if; for J in Last .. From'Last - 1 loop if From (J) = '/' or From (J) = '\' then Append (Result, "../"); end if; end loop; if Last <= To'Last and From (I) /= '/' and From (I) /= '\' then Append (Result, "../"); Append (Result, To (Last .. To'Last)); end if; return To_String (Result); elsif I < From'Last and then (From (I) = '/' or From (I) = '\') then Last := I + 1; end if; end loop; if To'Last = From'Last or (To'Last = From'Last + 1 and (To (To'Last) = '/' or To (To'Last) = '\')) then return "."; elsif Last = 0 then return To; elsif To (From'Last + 1) = '/' or To (From'Last + 1) = '\' then return To (From'Last + 2 .. To'Last); else return To (Last .. To'Last); end if; end Get_Relative_Path; end Util.Files;
Implement Read_File to read a file in a Strings.Vector object
Implement Read_File to read a file in a Strings.Vector object
Ada
apache-2.0
stcarrez/ada-util,stcarrez/ada-util
4371540a27e41bb2a769cf0ade7e8e5619a2c834
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"); -- ------------------------------ -- 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) is Policy : constant Security.Policies.Policy_Access := Context.Get_Policy (NAME); Data : Role_Policy_Context_Access; begin if Policy = null then Log.Error ("There is no security policy: " & NAME); end if; Data := new Role_Policy_Context; Data.Roles := Roles; Context.Set_Policy_Context (Policy, Data.all'Access); end Set_Role_Context; -- ------------------------------ -- Get the policy name. -- ------------------------------ overriding function Get_Name (From : in Role_Policy) return String is pragma Unreferenced (From); begin return NAME; 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; -- ------------------------------ -- Finalize the policy manager. -- ------------------------------ overriding procedure Finalize (Policy : in out Role_Policy) is use type Ada.Strings.Unbounded.String_Access; begin for I in Policy.Names'Range loop exit when Policy.Names (I) = null; Ada.Strings.Unbounded.Free (Policy.Names (I)); end loop; end Finalize; 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 Util.Strings.Tokenizers; 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"); -- ------------------------------ -- 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) is Policy : constant Security.Policies.Policy_Access := Context.Get_Policy (NAME); Data : Role_Policy_Context_Access; begin if Policy = null then Log.Error ("There is no security policy: " & NAME); end if; Data := new Role_Policy_Context; Data.Roles := Roles; Context.Set_Policy_Context (Policy, Data.all'Access); end Set_Role_Context; -- ------------------------------ -- Get the policy name. -- ------------------------------ overriding function Get_Name (From : in Role_Policy) return String is pragma Unreferenced (From); begin return NAME; 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; -- ------------------------------ -- 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) is procedure Process (Role : in String; Done : out Boolean); procedure Process (Role : in String; Done : out Boolean) is begin Into (Manager.Find_Role (Role)) := True; Done := False; end Process; begin Into := (others => False); Util.Strings.Tokenizers.Iterate_Tokens (Content => Roles, Pattern => ",", Process => Process'Access, Going => Ada.Strings.Forward); end Set_Roles; 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; -- ------------------------------ -- Finalize the policy manager. -- ------------------------------ overriding procedure Finalize (Policy : in out Role_Policy) is use type Ada.Strings.Unbounded.String_Access; begin for I in Policy.Names'Range loop exit when Policy.Names (I) = null; Ada.Strings.Unbounded.Free (Policy.Names (I)); end loop; end Finalize; 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;
Implement Set_Roles
Implement Set_Roles
Ada
apache-2.0
Letractively/ada-security
8e00101038cd63fadcf6ae88e9cf7b6a068f76a2
src/security-policies-roles.adb
src/security-policies-roles.adb
----------------------------------------------------------------------- -- security-policies-roles -- Role based policies -- 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 Util.Log.Loggers; with Util.Serialize.Mappers.Record_Mapper; with Util.Strings.Tokenizers; with Security.Controllers; with Security.Controllers.Roles; package body Security.Policies.Roles is -- The logger Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("Security.Policies.Roles"); -- ------------------------------ -- 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) is Policy : constant Security.Policies.Policy_Access := Context.Get_Policy (NAME); Data : Role_Policy_Context_Access; begin if Policy = null then Log.Error ("There is no security policy: " & NAME); end if; Data := new Role_Policy_Context; Data.Roles := Roles; Context.Set_Policy_Context (Policy, Data.all'Access); end Set_Role_Context; -- ------------------------------ -- 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) is Policy : constant Security.Policies.Policy_Access := Context.Get_Policy (NAME); Data : Role_Policy_Context_Access; Map : Role_Map; begin if Policy = null then Log.Error ("There is no security policy: " & NAME); end if; Role_Policy'Class (Policy.all).Set_Roles (Roles, Map); Data := new Role_Policy_Context; Data.Roles := Map; Context.Set_Policy_Context (Policy, Data.all'Access); end Set_Role_Context; -- ------------------------------ -- Get the policy name. -- ------------------------------ overriding function Get_Name (From : in Role_Policy) return String is pragma Unreferenced (From); begin return NAME; 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; -- ------------------------------ -- 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) is procedure Process (Role : in String; Done : out Boolean); procedure Process (Role : in String; Done : out Boolean) is begin Into (Manager.Find_Role (Role)) := True; Done := False; end Process; begin Into := (others => False); Util.Strings.Tokenizers.Iterate_Tokens (Content => Roles, Pattern => ",", Process => Process'Access, Going => Ada.Strings.Forward); end Set_Roles; type Config_Fields is (FIELD_NAME, FIELD_ROLE, FIELD_ROLE_PERMISSION, FIELD_ROLE_NAME); procedure Set_Member (Into : in out Role_Policy'Class; 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 Role_Policy'Class; 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.Find_Role (Role); Into.Count := Into.Count + 1; exception when 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)); Index : Permission_Index; begin Security.Permissions.Add_Permission (Name, Index); for I in 1 .. Into.Count loop Into.Grants (Index) (Into.Roles (I)) := True; end loop; 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.Add_Role_Type (Name, Role); end; end case; end Set_Member; package Config_Mapper is new Util.Serialize.Mappers.Record_Mapper (Element_Type => Role_Policy'Class, Element_Type_Access => Role_Policy_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 begin Reader.Add_Mapping ("policy-rules", Mapper'Access); Reader.Add_Mapping ("module", Mapper'Access); Config_Mapper.Set_Context (Reader, Policy'Unchecked_Access); end Prepare_Config; -- ------------------------------ -- Finalize the policy manager. -- ------------------------------ overriding procedure Finalize (Policy : in out Role_Policy) is use type Ada.Strings.Unbounded.String_Access; begin for I in Policy.Names'Range loop exit when Policy.Names (I) = null; Ada.Strings.Unbounded.Free (Policy.Names (I)); end loop; end Finalize; -- ------------------------------ -- 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 is Policy : constant Security.Policies.Policy_Access := Manager.Get_Policy (NAME); begin if Policy = null or else not (Policy.all in Role_Policy'Class) then return null; else return Role_Policy'Class (Policy.all)'Access; end if; end Get_Role_Policy; 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, 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.Log.Loggers; with Util.Serialize.Mappers.Record_Mapper; with Util.Strings.Tokenizers; with Security.Controllers; with Security.Controllers.Roles; package body Security.Policies.Roles is -- The logger Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("Security.Policies.Roles"); -- ------------------------------ -- 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) is Policy : constant Security.Policies.Policy_Access := Context.Get_Policy (NAME); Data : Role_Policy_Context_Access; begin if Policy = null then Log.Error ("There is no security policy: " & NAME); end if; Data := new Role_Policy_Context; Data.Roles := Roles; Context.Set_Policy_Context (Policy, Data.all'Access); end Set_Role_Context; -- ------------------------------ -- 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) is Policy : constant Security.Policies.Policy_Access := Context.Get_Policy (NAME); Data : Role_Policy_Context_Access; Map : Role_Map; begin if Policy = null then Log.Error ("There is no security policy: " & NAME); end if; Role_Policy'Class (Policy.all).Set_Roles (Roles, Map); Data := new Role_Policy_Context; Data.Roles := Map; Context.Set_Policy_Context (Policy, Data.all'Access); end Set_Role_Context; -- ------------------------------ -- Get the policy name. -- ------------------------------ overriding function Get_Name (From : in Role_Policy) return String is pragma Unreferenced (From); begin return NAME; 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; -- ------------------------------ -- Get the roles that grant the given permission. -- ------------------------------ function Get_Grants (Manager : in Role_Policy; Permission : in Permission_Index) return Role_Map is begin return Manager.Grants (Permission); end Get_Grants; -- ------------------------------ -- 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; -- ------------------------------ -- 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) is procedure Process (Role : in String; Done : out Boolean); procedure Process (Role : in String; Done : out Boolean) is begin Into (Manager.Find_Role (Role)) := True; Done := False; end Process; begin Into := (others => False); Util.Strings.Tokenizers.Iterate_Tokens (Content => Roles, Pattern => ",", Process => Process'Access, Going => Ada.Strings.Forward); end Set_Roles; type Config_Fields is (FIELD_NAME, FIELD_ROLE, FIELD_ROLE_PERMISSION, FIELD_ROLE_NAME); procedure Set_Member (Into : in out Role_Policy'Class; 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 Role_Policy'Class; 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.Find_Role (Role); Into.Count := Into.Count + 1; exception when 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)); Index : Permission_Index; begin Security.Permissions.Add_Permission (Name, Index); for I in 1 .. Into.Count loop Into.Grants (Index) (Into.Roles (I)) := True; end loop; 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.Add_Role_Type (Name, Role); end; end case; end Set_Member; package Config_Mapper is new Util.Serialize.Mappers.Record_Mapper (Element_Type => Role_Policy'Class, Element_Type_Access => Role_Policy_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 begin Reader.Add_Mapping ("policy-rules", Mapper'Access); Reader.Add_Mapping ("module", Mapper'Access); Config_Mapper.Set_Context (Reader, Policy'Unchecked_Access); end Prepare_Config; -- ------------------------------ -- Finalize the policy manager. -- ------------------------------ overriding procedure Finalize (Policy : in out Role_Policy) is use type Ada.Strings.Unbounded.String_Access; begin for I in Policy.Names'Range loop exit when Policy.Names (I) = null; Ada.Strings.Unbounded.Free (Policy.Names (I)); end loop; end Finalize; -- ------------------------------ -- 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 is Policy : constant Security.Policies.Policy_Access := Manager.Get_Policy (NAME); begin if Policy = null or else not (Policy.all in Role_Policy'Class) then return null; else return Role_Policy'Class (Policy.all)'Access; end if; end Get_Role_Policy; 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;
Implement the Get_Grants function to retrieve the list of roles that grant a given permission
Implement the Get_Grants function to retrieve the list of roles that grant a given permission
Ada
apache-2.0
stcarrez/ada-security
1cd10e2a9cf86e30cbf7d1541cc626ec10e3f3e2
src/wiki-nodes.ads
src/wiki-nodes.ads
----------------------------------------------------------------------- -- wiki -- Ada Wiki Engine -- 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 Wiki.Attributes; with Wiki.Documents; package Wiki.Nodes is pragma Preelaborate; subtype Format_Map is Wiki.Documents.Format_Map; subtype WString is Wide_Wide_String; type Node_Kind is (N_LINE_BREAK, N_HORIZONTAL_RULE, N_PARAGRAPH, N_HEADER, N_BLOCKQUOTE, N_QUOTE, N_TAG_START, N_INDENT, N_TEXT, N_LINK, N_IMAGE); -- Node kinds which are simple markers in the document. subtype Simple_Node_Kind is Node_Kind range N_LINE_BREAK .. N_PARAGRAPH; -- The possible HTML tags as described in HTML5 specification. type Html_Tag_Type is ( -- Section 4.1 The root element HTML_TAG, -- Section 4.2 Document metadata HEAD_TAG, TITLE_TAG, BASE_TAG, LINK_TAG, META_TAG, STYLE_TAG, -- Section 4.3 Sections BODY_TAG, ARTICLE_TAG, SECTION_TAG, NAV_TAG, ASIDE_TAG, H1_TAG, H2_TAG, H3_TAG, H4_TAG, H5_TAG, H6_TAG, HEADER_TAG, FOOTER_TAG, ADDRESS_TAG, -- Section 4.4 Grouping content P_TAG, HR_TAG, PRE_TAG, BLOCKQUOTE_TAG, OL_TAG, UL_TAG, LI_TAG, DL_TAG, DT_TAG, DD_TAG, FIGURE_TAG, FIGCAPTION_TAG, DIV_TAG, MAIN_TAG, -- Section 4.5 Text-level semantics A_TAG, EM_TAG, STRONG_TAG, SMALL_TAG, S_TAG, CITE_TAG, Q_TAG, DFN_TAG, ABBR_TAG, DATA_TAG, TIME_TAG, CODE_TAG, VAR_TAG, SAMP_TAG, KBD_TAG, SUB_TAG, SUP_TAG, I_TAG, B_TAG, U_TAG, MARK_TAG, RUBY_TAG, RB_TAG, RT_TAG, RTC_TAG, RP_TAG, BDI_TAG, BDO_TAG, SPAN_TAG, BR_TAG, WBR_TAG, -- Section 4.6 Edits INS_TAG, DEL_TAG, -- Section 4.7 Embedded content IMG_TAG, IFRAME_TAG, EMBED_TAG, OBJECT_TAG, PARAM_TAG, VIDEO_TAG, AUDIO_TAG, SOURCE_TAG, TRACK_TAG, MAP_TAG, AREA_TAG, -- Section 4.9 Tabular data TABLE_TAG, CAPTION_TAG, COLGROUP_TAG, COL_TAG, TBODY_TAG, THEAD_TAG, TFOOT_TAG, TR_TAG, TD_TAG, TH_TAG, -- Section 4.10 Forms FORM_TAG, LABEL_TAG, INPUT_TAG, BUTTON_TAG, SELECT_TAG, DATALIST_TAG, OPTGROUP_TAG, OPTION_TAG, TEXTAREA_TAG, KEYGEN_TAG, OUTPUT_TAG, PROGRESS_TAG, METER_TAG, FIELDSET_TAG, LEGEND_TAG, -- Section 4.11 Scripting SCRIPT_TAG, NOSCRIPT_TAG, TEMPLATE_TAG, CANVAS_TAG, -- Unknown tags UNKNOWN_TAG ); type String_Access is access constant String; -- Get the HTML tag name. function Get_Tag_Name (Tag : in Html_Tag_Type) return String_Access; type Node_List is limited private; type Node_List_Access is access all Node_List; type Node_Type; type Node_Type_Access is access all Node_Type; type Node_Type (Kind : Node_Kind; Len : Natural) is limited record case Kind is when N_HEADER | N_BLOCKQUOTE | N_INDENT => Level : Natural := 0; Header : WString (1 .. Len); when N_TEXT => Format : Format_Map; Text : WString (1 .. Len); when N_LINK | N_IMAGE => Link_Attr : Wiki.Attributes.Attribute_List_Type; Title : WString (1 .. Len); when N_QUOTE => Quote_Attr : Wiki.Attributes.Attribute_List_Type; Quote : WString (1 .. Len); when N_TAG_START => Tag_Start : Html_Tag_Type; Attributes : Wiki.Attributes.Attribute_List_Type; Children : Node_List_Access; Parent : Node_Type_Access; when others => null; end case; end record; -- Create a text node. function Create_Text (Text : in WString) return Node_Type_Access; type Document is limited private; -- Append a node to the document. procedure Append (Into : in out Document; Node : in Node_Type_Access); -- Append a simple node such as N_LINE_BREAK, N_HORIZONTAL_RULE or N_PARAGRAPH. procedure Append (Into : in out Document; Kind : in Simple_Node_Kind); -- Append a HTML tag start node to the document. procedure Add_Tag (Document : in out Wiki.Nodes.Document; Tag : in Html_Tag_Type; Attributes : in Wiki.Attributes.Attribute_List_Type); -- procedure Add_Text (Doc : in out Document; -- Text : in WString); -- type Renderer is limited interface; -- -- procedure Render (Engine : in out Renderer; -- Doc : in Document; -- Node : in Node_Type) is abstract; -- -- procedure Iterate (Doc : in Document; -- Process : access procedure (Doc : in Document; Node : in Node_Type)) is -- Node : Document_Node_Access := Doc.First; -- begin -- while Node /= null loop -- Process (Doc, Node.Data); -- Node := Node.Next; -- end loop; -- end Iterate; private NODE_LIST_BLOCK_SIZE : constant Positive := 20; type Node_Array is array (Positive range <>) of Node_Type_Access; type Node_List_Block; type Node_List_Block_Access is access all Node_List_Block; type Node_List_Block (Max : Positive) is limited record Next : Node_List_Block_Access; Last : Natural := 0; List : Node_Array (1 .. Max); end record; type Node_List is limited record Current : Node_List_Block_Access; Length : Natural := 0; First : Node_List_Block (NODE_LIST_BLOCK_SIZE); end record; -- Append a node to the node list. procedure Append (Into : in out Node_List; Node : in Node_Type_Access); type Document is limited record Nodes : Node_List; Current : Node_Type_Access; end record; end Wiki.Nodes;
----------------------------------------------------------------------- -- wiki -- Ada Wiki Engine -- 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 Wiki.Attributes; with Wiki.Documents; package Wiki.Nodes is pragma Preelaborate; subtype Format_Map is Wiki.Documents.Format_Map; subtype WString is Wide_Wide_String; type Node_Kind is (N_LINE_BREAK, N_HORIZONTAL_RULE, N_PARAGRAPH, N_HEADER, N_BLOCKQUOTE, N_QUOTE, N_TAG_START, N_INDENT, N_TEXT, N_LINK, N_TABLE, N_ROW, N_COLUMN); -- Node kinds which are simple markers in the document. subtype Simple_Node_Kind is Node_Kind range N_LINE_BREAK .. N_PARAGRAPH; -- The possible HTML tags as described in HTML5 specification. type Html_Tag_Type is ( -- Section 4.1 The root element HTML_TAG, -- Section 4.2 Document metadata HEAD_TAG, TITLE_TAG, BASE_TAG, LINK_TAG, META_TAG, STYLE_TAG, -- Section 4.3 Sections BODY_TAG, ARTICLE_TAG, SECTION_TAG, NAV_TAG, ASIDE_TAG, H1_TAG, H2_TAG, H3_TAG, H4_TAG, H5_TAG, H6_TAG, HEADER_TAG, FOOTER_TAG, ADDRESS_TAG, -- Section 4.4 Grouping content P_TAG, HR_TAG, PRE_TAG, BLOCKQUOTE_TAG, OL_TAG, UL_TAG, LI_TAG, DL_TAG, DT_TAG, DD_TAG, FIGURE_TAG, FIGCAPTION_TAG, DIV_TAG, MAIN_TAG, -- Section 4.5 Text-level semantics A_TAG, EM_TAG, STRONG_TAG, SMALL_TAG, S_TAG, CITE_TAG, Q_TAG, DFN_TAG, ABBR_TAG, DATA_TAG, TIME_TAG, CODE_TAG, VAR_TAG, SAMP_TAG, KBD_TAG, SUB_TAG, SUP_TAG, I_TAG, B_TAG, U_TAG, MARK_TAG, RUBY_TAG, RB_TAG, RT_TAG, RTC_TAG, RP_TAG, BDI_TAG, BDO_TAG, SPAN_TAG, BR_TAG, WBR_TAG, -- Section 4.6 Edits INS_TAG, DEL_TAG, -- Section 4.7 Embedded content IMG_TAG, IFRAME_TAG, EMBED_TAG, OBJECT_TAG, PARAM_TAG, VIDEO_TAG, AUDIO_TAG, SOURCE_TAG, TRACK_TAG, MAP_TAG, AREA_TAG, -- Section 4.9 Tabular data TABLE_TAG, CAPTION_TAG, COLGROUP_TAG, COL_TAG, TBODY_TAG, THEAD_TAG, TFOOT_TAG, TR_TAG, TD_TAG, TH_TAG, -- Section 4.10 Forms FORM_TAG, LABEL_TAG, INPUT_TAG, BUTTON_TAG, SELECT_TAG, DATALIST_TAG, OPTGROUP_TAG, OPTION_TAG, TEXTAREA_TAG, KEYGEN_TAG, OUTPUT_TAG, PROGRESS_TAG, METER_TAG, FIELDSET_TAG, LEGEND_TAG, -- Section 4.11 Scripting SCRIPT_TAG, NOSCRIPT_TAG, TEMPLATE_TAG, CANVAS_TAG, -- Unknown tags UNKNOWN_TAG ); -- Find the tag from the tag name. function Find_Tag (Name : in Wide_Wide_String) return Html_Tag_Type; type String_Access is access constant String; -- Get the HTML tag name. function Get_Tag_Name (Tag : in Html_Tag_Type) return String_Access; type Node_List is limited private; type Node_List_Access is access all Node_List; type Node_Type; type Node_Type_Access is access all Node_Type; type Node_Type (Kind : Node_Kind; Len : Natural) is limited record case Kind is when N_HEADER | N_BLOCKQUOTE | N_INDENT => Level : Natural := 0; Header : WString (1 .. Len); when N_TEXT => Format : Format_Map; Text : WString (1 .. Len); when N_LINK => Image : Boolean; Link_Attr : Wiki.Attributes.Attribute_List_Type; Title : WString (1 .. Len); when N_QUOTE => Quote_Attr : Wiki.Attributes.Attribute_List_Type; Quote : WString (1 .. Len); when N_TAG_START => Tag_Start : Html_Tag_Type; Attributes : Wiki.Attributes.Attribute_List_Type; Children : Node_List_Access; Parent : Node_Type_Access; when others => null; end case; end record; -- Create a text node. function Create_Text (Text : in WString) return Node_Type_Access; type Document is limited private; -- Append a node to the document. procedure Append (Into : in out Document; Node : in Node_Type_Access); -- Append a simple node such as N_LINE_BREAK, N_HORIZONTAL_RULE or N_PARAGRAPH. procedure Append (Into : in out Document; Kind : in Simple_Node_Kind); -- Append a HTML tag start node to the document. procedure Add_Tag (Document : in out Wiki.Nodes.Document; Tag : in Html_Tag_Type; Attributes : in Wiki.Attributes.Attribute_List_Type); -- procedure Add_Text (Doc : in out Document; -- Text : in WString); -- type Renderer is limited interface; -- -- procedure Render (Engine : in out Renderer; -- Doc : in Document; -- Node : in Node_Type) is abstract; -- -- procedure Iterate (Doc : in Document; -- Process : access procedure (Doc : in Document; Node : in Node_Type)) is -- Node : Document_Node_Access := Doc.First; -- begin -- while Node /= null loop -- Process (Doc, Node.Data); -- Node := Node.Next; -- end loop; -- end Iterate; private NODE_LIST_BLOCK_SIZE : constant Positive := 20; type Node_Array is array (Positive range <>) of Node_Type_Access; type Node_List_Block; type Node_List_Block_Access is access all Node_List_Block; type Node_List_Block (Max : Positive) is limited record Next : Node_List_Block_Access; Last : Natural := 0; List : Node_Array (1 .. Max); end record; type Node_List is limited record Current : Node_List_Block_Access; Length : Natural := 0; First : Node_List_Block (NODE_LIST_BLOCK_SIZE); end record; -- Append a node to the node list. procedure Append (Into : in out Node_List; Node : in Node_Type_Access); type Document is limited record Nodes : Node_List; Current : Node_Type_Access; end record; end Wiki.Nodes;
Declare Find_Tag function
Declare Find_Tag function
Ada
apache-2.0
stcarrez/ada-wiki,stcarrez/ada-wiki
a2768f272a10d9116052b5924bfcc763a9649b48
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"; 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;
----------------------------------------------------------------------- -- 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 ASF.Security.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 ASF.Security.Servlets.Request_Auth_Servlet; Verify_Auth : aliased ASF.Security.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;
Fix compilation after Ada Security integration
Fix compilation after Ada Security integration
Ada
apache-2.0
stcarrez/ada-asf,stcarrez/ada-asf,stcarrez/ada-asf
0be8cfe25ef5d938460a42007bf13999aa0090ee
regtests/util-streams-buffered-encoders-tests.adb
regtests/util-streams-buffered-encoders-tests.adb
----------------------------------------------------------------------- -- util-streams-buffered-encoders-tests -- Unit tests for encoding buffered streams -- 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 Util.Test_Caller; with Util.Streams.Files; with Util.Streams.Texts; with Util.Files; with Ada.Streams.Stream_IO; package body Util.Streams.Buffered.Encoders.Tests is use Util.Tests; use Util.Streams.Files; use Ada.Streams.Stream_IO; package Caller is new Util.Test_Caller (Test, "Streams.Buffered.Encoders"); procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is begin Caller.Add_Test (Suite, "Test Util.Streams.Buffered.Encoders.Write, Read", Test_Base64_Stream'Access); end Add_Tests; procedure Test_Base64_Stream (T : in out Test) is Stream : aliased File_Stream; Buffer : aliased Util.Streams.Buffered.Encoders.Encoding_Stream; Print : Util.Streams.Texts.Print_Stream; Path : constant String := Util.Tests.Get_Test_Path ("regtests/result/test-stream.b64"); Expect : constant String := Util.Tests.Get_Path ("regtests/expect/test-stream.b64"); begin Print.Initialize (Output => Buffer'Unchecked_Access, Size => 5); Buffer.Initialize (Output => Stream'Unchecked_Access, Size => 1024, Format => Util.Encoders.BASE_64); Stream.Create (Mode => Out_File, Name => Path); for I in 1 .. 32 loop Print.Write ("abcd"); Print.Write (" fghij"); Print.Write (ASCII.LF); end loop; Print.Flush; Stream.Close; Util.Tests.Assert_Equal_Files (T => T, Expect => Expect, Test => Path, Message => "Base64 stream"); end Test_Base64_Stream; end Util.Streams.Buffered.Encoders.Tests;
----------------------------------------------------------------------- -- util-streams-buffered-encoders-tests -- Unit tests for encoding buffered streams -- 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 Util.Test_Caller; with Util.Streams.Files; with Util.Streams.Texts; with Ada.Streams.Stream_IO; package body Util.Streams.Buffered.Encoders.Tests is use Util.Tests; use Util.Streams.Files; use Ada.Streams.Stream_IO; package Caller is new Util.Test_Caller (Test, "Streams.Buffered.Encoders"); procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is begin Caller.Add_Test (Suite, "Test Util.Streams.Buffered.Encoders.Write, Read", Test_Base64_Stream'Access); end Add_Tests; procedure Test_Base64_Stream (T : in out Test) is Stream : aliased File_Stream; Buffer : aliased Util.Streams.Buffered.Encoders.Encoding_Stream; Print : Util.Streams.Texts.Print_Stream; Path : constant String := Util.Tests.Get_Test_Path ("regtests/result/test-stream.b64"); Expect : constant String := Util.Tests.Get_Path ("regtests/expect/test-stream.b64"); begin Print.Initialize (Output => Buffer'Unchecked_Access, Size => 5); Buffer.Initialize (Output => Stream'Unchecked_Access, Size => 1024, Format => Util.Encoders.BASE_64); Stream.Create (Mode => Out_File, Name => Path); for I in 1 .. 32 loop Print.Write ("abcd"); Print.Write (" fghij"); Print.Write (ASCII.LF); end loop; Print.Flush; Stream.Close; Util.Tests.Assert_Equal_Files (T => T, Expect => Expect, Test => Path, Message => "Base64 stream"); end Test_Base64_Stream; end Util.Streams.Buffered.Encoders.Tests;
Fix compilation warning
Fix compilation warning
Ada
apache-2.0
stcarrez/ada-util,stcarrez/ada-util
3251016149235cdaffbc0577507d19f1c627eb9f
src/ado.ads
src/ado.ads
----------------------------------------------------------------------- -- ADO Databases -- Database Objects -- 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.Strings.Unbounded; with Ada.Streams; with Ada.Calendar; with Util.Refs; package ADO is type Int64 is range -2**63 .. 2**63 - 1; for Int64'Size use 64; type Unsigned64 is mod 2**64; for Unsigned64'Size use 64; DEFAULT_TIME : constant Ada.Calendar.Time; -- ------------------------------ -- Database Identifier -- ------------------------------ -- type Identifier is range -2**47 .. 2**47 - 1; NO_IDENTIFIER : constant Identifier := -1; type Entity_Type is range 0 .. 2**16 - 1; NO_ENTITY_TYPE : constant Entity_Type := 0; type Object_Id is record Id : Identifier; Kind : Entity_Type; end record; pragma Pack (Object_Id); -- ------------------------------ -- Nullable Types -- ------------------------------ -- Most database allow to store a NULL instead of an actual integer, date or string value. -- Unlike Java, there is no easy way to distinguish between a NULL and an actual valid value. -- The <b>Nullable_T</b> types provide a way to specify and check whether a value is null -- or not. -- An integer which can be null. type Nullable_Integer is record Value : Integer := 0; Is_Null : Boolean := True; end record; -- A string which can be null. type Nullable_String is record Value : Ada.Strings.Unbounded.Unbounded_String; Is_Null : Boolean := True; end record; -- A date which can be null. type Nullable_Time is record Value : Ada.Calendar.Time; Is_Null : Boolean := True; end record; type Nullable_Entity_Type is record Value : Entity_Type; Is_Null : Boolean := True; end record; -- ------------------------------ -- Blob data type -- ------------------------------ -- The <b>Blob</b> type is used to represent database blobs. The data is stored -- in an <b>Ada.Streams.Stream_Element_Array</b> pointed to by the <b>Data</b> member. -- The query statement and bind parameter will use a <b>Blob_Ref</b> which represents -- a reference to the blob data. This is intended to minimize data copy. type Blob (Len : Ada.Streams.Stream_Element_Offset) is new Util.Refs.Ref_Entity with record Data : Ada.Streams.Stream_Element_Array (1 .. Len); end record; type Blob_Access is access all Blob; package Blob_References is new Util.Refs.Indefinite_References (Blob, Blob_Access); subtype Blob_Ref is Blob_References.Ref; -- Create a blob with an allocated buffer of <b>Size</b> bytes. function Create_Blob (Size : in Natural) return Blob_Ref; -- Create a blob initialized with the given data buffer. function Create_Blob (Data : in Ada.Streams.Stream_Element_Array) return Blob_Ref; -- Create a blob initialized with the content from the file whose path is <b>Path</b>. -- Raises an IO exception if the file does not exist. function Create_Blob (Path : in String) return Blob_Ref; -- Return a null blob. function Null_Blob return Blob_Ref; private DEFAULT_TIME : constant Ada.Calendar.Time := Ada.Calendar.Time_Of (Year => 1901, Month => 1, Day => 2, Seconds => 0.0); end ADO;
----------------------------------------------------------------------- -- ADO Databases -- Database Objects -- 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.Strings.Unbounded; with Ada.Streams; with Ada.Calendar; with Util.Refs; package ADO is type Int64 is range -2**63 .. 2**63 - 1; for Int64'Size use 64; type Unsigned64 is mod 2**64; for Unsigned64'Size use 64; DEFAULT_TIME : constant Ada.Calendar.Time; -- ------------------------------ -- Database Identifier -- ------------------------------ -- type Identifier is range -2**47 .. 2**47 - 1; NO_IDENTIFIER : constant Identifier := -1; type Entity_Type is range 0 .. 2**16 - 1; NO_ENTITY_TYPE : constant Entity_Type := 0; type Object_Id is record Id : Identifier; Kind : Entity_Type; end record; pragma Pack (Object_Id); -- ------------------------------ -- Nullable Types -- ------------------------------ -- Most database allow to store a NULL instead of an actual integer, date or string value. -- Unlike Java, there is no easy way to distinguish between a NULL and an actual valid value. -- The <b>Nullable_T</b> types provide a way to specify and check whether a value is null -- or not. -- An integer which can be null. type Nullable_Integer is record Value : Integer := 0; Is_Null : Boolean := True; end record; -- A string which can be null. type Nullable_String is record Value : Ada.Strings.Unbounded.Unbounded_String; Is_Null : Boolean := True; end record; -- A date which can be null. type Nullable_Time is record Value : Ada.Calendar.Time; Is_Null : Boolean := True; end record; type Nullable_Entity_Type is record Value : Entity_Type := 0; Is_Null : Boolean := True; end record; -- ------------------------------ -- Blob data type -- ------------------------------ -- The <b>Blob</b> type is used to represent database blobs. The data is stored -- in an <b>Ada.Streams.Stream_Element_Array</b> pointed to by the <b>Data</b> member. -- The query statement and bind parameter will use a <b>Blob_Ref</b> which represents -- a reference to the blob data. This is intended to minimize data copy. type Blob (Len : Ada.Streams.Stream_Element_Offset) is new Util.Refs.Ref_Entity with record Data : Ada.Streams.Stream_Element_Array (1 .. Len); end record; type Blob_Access is access all Blob; package Blob_References is new Util.Refs.Indefinite_References (Blob, Blob_Access); subtype Blob_Ref is Blob_References.Ref; -- Create a blob with an allocated buffer of <b>Size</b> bytes. function Create_Blob (Size : in Natural) return Blob_Ref; -- Create a blob initialized with the given data buffer. function Create_Blob (Data : in Ada.Streams.Stream_Element_Array) return Blob_Ref; -- Create a blob initialized with the content from the file whose path is <b>Path</b>. -- Raises an IO exception if the file does not exist. function Create_Blob (Path : in String) return Blob_Ref; -- Return a null blob. function Null_Blob return Blob_Ref; private DEFAULT_TIME : constant Ada.Calendar.Time := Ada.Calendar.Time_Of (Year => 1901, Month => 1, Day => 2, Seconds => 0.0); end ADO;
Fix the Nullable_Entity_Type record to initialize the default value
Fix the Nullable_Entity_Type record to initialize the default value
Ada
apache-2.0
stcarrez/ada-ado
eba74afe5b5ada5a371bfb971e5590c84e0500cf
src/sys/lzma/util-encoders-lzma.adb
src/sys/lzma/util-encoders-lzma.adb
----------------------------------------------------------------------- -- util-encoders-lzma -- LZMA compression and decompression -- 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 Lzma.Check; with Lzma.Container; with Interfaces.C; package body Util.Encoders.Lzma is use type Interfaces.C.size_t; use type Ada.Streams.Stream_Element_Offset; use type Base.lzma_ret; subtype Offset is Ada.Streams.Stream_Element_Offset; -- ------------------------------ -- Compress the binary input stream represented by <b>Data</b> by using -- the LZMA compression into the output stream <b>Into</b>. -- -- If the transformer does not have enough room to write the result, -- it must return in <b>Encoded</b> the index of the last encoded -- position in the <b>Data</b> stream. -- -- The transformer returns in <b>Last</b> the last valid position -- in the output stream <b>Into</b>. -- -- The <b>Encoding_Error</b> exception is raised if the input -- stream cannot be transformed. -- ------------------------------ overriding procedure Transform (E : in out Compress; Data : in Ada.Streams.Stream_Element_Array; Into : out Ada.Streams.Stream_Element_Array; Last : out Ada.Streams.Stream_Element_Offset; Encoded : out Ada.Streams.Stream_Element_Offset) is Result : Base.lzma_ret; begin E.Stream.next_out := Into (Into'First)'Unchecked_Access; E.Stream.avail_out := Into'Length; E.Stream.next_in := Data (Data'First)'Unrestricted_Access; E.Stream.avail_in := Interfaces.C.size_t (Data'Length); loop Result := Base.lzma_code (E.Stream'Unchecked_Access, Base.LZMA_RUN); -- Write the output data when the buffer is full or we reached the end of stream. if E.Stream.avail_out = 0 or E.Stream.avail_in = 0 or Result = Base.LZMA_STREAM_END then Last := Into'First + Into'Length - Offset (E.Stream.avail_out) - 1; Encoded := Data'First + Data'Length - Offset (E.Stream.avail_in); return; end if; exit when Result /= Base.LZMA_OK; end loop; Encoded := Into'First; end Transform; -- ------------------------------ -- Finish compression of the input array. -- ------------------------------ overriding procedure Finish (E : in out Compress; Into : in out Ada.Streams.Stream_Element_Array; Last : in out Ada.Streams.Stream_Element_Offset) is Result : Base.lzma_ret; pragma Unreferenced (Result); begin E.Stream.next_out := Into (Into'First)'Unchecked_Access; E.Stream.avail_out := Into'Length; E.Stream.next_in := null; E.Stream.avail_in := 0; Result := Base.lzma_code (E.Stream'Unchecked_Access, Base.LZMA_FINISH); Last := Into'First + Into'Length - Offset (E.Stream.avail_out) - 1; end Finish; overriding procedure Initialize (E : in out Compress) is Result : Base.lzma_ret; pragma Unreferenced (Result); begin Result := Container.lzma_easy_encoder (E.Stream'Unchecked_Access, 6, Check.LZMA_CHECK_CRC64); end Initialize; overriding procedure Finalize (E : in out Compress) is begin Base.lzma_end (E.Stream'Unchecked_Access); end Finalize; end Util.Encoders.Lzma;
----------------------------------------------------------------------- -- util-encoders-lzma -- LZMA compression and decompression -- Copyright (C) 2018, 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 Lzma.Check; with Lzma.Container; with Interfaces.C; package body Util.Encoders.Lzma is use type Interfaces.C.size_t; -- use type Ada.Streams.Stream_Element_Offset; use type Base.lzma_ret; subtype Offset is Ada.Streams.Stream_Element_Offset; -- ------------------------------ -- Compress the binary input stream represented by <b>Data</b> by using -- the LZMA compression into the output stream <b>Into</b>. -- -- If the transformer does not have enough room to write the result, -- it must return in <b>Encoded</b> the index of the last encoded -- position in the <b>Data</b> stream. -- -- The transformer returns in <b>Last</b> the last valid position -- in the output stream <b>Into</b>. -- -- The <b>Encoding_Error</b> exception is raised if the input -- stream cannot be transformed. -- ------------------------------ overriding procedure Transform (E : in out Compress; Data : in Ada.Streams.Stream_Element_Array; Into : out Ada.Streams.Stream_Element_Array; Last : out Ada.Streams.Stream_Element_Offset; Encoded : out Ada.Streams.Stream_Element_Offset) is Result : Base.lzma_ret; begin E.Stream.next_out := Into (Into'First)'Unchecked_Access; E.Stream.avail_out := Into'Length; E.Stream.next_in := Data (Data'First)'Unrestricted_Access; E.Stream.avail_in := Interfaces.C.size_t (Data'Length); loop Result := Base.lzma_code (E.Stream'Unchecked_Access, Base.LZMA_RUN); -- Write the output data when the buffer is full or we reached the end of stream. if E.Stream.avail_out = 0 or E.Stream.avail_in = 0 or Result = Base.LZMA_STREAM_END then Last := Into'First + Into'Length - Offset (E.Stream.avail_out) - 1; Encoded := Data'First + Data'Length - Offset (E.Stream.avail_in); return; end if; exit when Result /= Base.LZMA_OK; end loop; Encoded := Into'First; end Transform; -- ------------------------------ -- Finish compression of the input array. -- ------------------------------ overriding procedure Finish (E : in out Compress; Into : in out Ada.Streams.Stream_Element_Array; Last : in out Ada.Streams.Stream_Element_Offset) is Result : Base.lzma_ret; pragma Unreferenced (Result); begin E.Stream.next_out := Into (Into'First)'Unchecked_Access; E.Stream.avail_out := Into'Length; E.Stream.next_in := null; E.Stream.avail_in := 0; Result := Base.lzma_code (E.Stream'Unchecked_Access, Base.LZMA_FINISH); Last := Into'First + Into'Length - Offset (E.Stream.avail_out) - 1; end Finish; overriding procedure Initialize (E : in out Compress) is Result : Base.lzma_ret; pragma Unreferenced (Result); begin Result := Container.lzma_easy_encoder (E.Stream'Unchecked_Access, 6, Check.LZMA_CHECK_CRC64); end Initialize; overriding procedure Finalize (E : in out Compress) is begin Base.lzma_end (E.Stream'Unchecked_Access); end Finalize; end Util.Encoders.Lzma;
Fix compilation warning
Fix compilation warning
Ada
apache-2.0
stcarrez/ada-util,stcarrez/ada-util
f4765520123069239ed68c4e77ebd844761255f2
mat/src/mat-readers-streams-files.adb
mat/src/mat-readers-streams-files.adb
----------------------------------------------------------------------- -- mat-readers-files -- Reader for files -- 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.Streams.Stream_IO; with Util.Log.Loggers; with MAT.Readers.Marshaller; package body MAT.Readers.Files is -- The logger Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("MAT.Readers.Files"); -- Open the file. procedure Open (Reader : in out File_Reader_Type; Path : in String) is begin Log.Info ("Reading data stream {0}", Path); Reader.Stream.Initialize (Size => BUFFER_SIZE, Input => Reader.File'Unchecked_Access, Output => null); Reader.File.Open (Mode => Ada.Streams.Stream_IO.In_File, Name => Path); end Open; end MAT.Readers.Files;
----------------------------------------------------------------------- -- mat-readers-files -- Reader for files -- 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.Streams.Stream_IO; with Util.Log.Loggers; with MAT.Readers.Marshaller; package body MAT.Readers.Streams.Files is -- The logger Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("MAT.Readers.Files"); BUFFER_SIZE : constant Natural := 100 * 1024; -- Open the file. procedure Open (Reader : in out File_Reader_Type; Path : in String) is begin Log.Info ("Reading data stream {0}", Path); Reader.Stream.Initialize (Size => BUFFER_SIZE, Input => Reader.File'Unchecked_Access, Output => null); Reader.File.Open (Mode => Ada.Streams.Stream_IO.In_File, Name => Path); end Open; end MAT.Readers.Streams.Files;
Rename package to MAT.Readers.Streams.Files
Rename package to MAT.Readers.Streams.Files
Ada
apache-2.0
stcarrez/mat,stcarrez/mat,stcarrez/mat
3f19ed9f315118ba3e8d53ea55a95f54ccfd19d6
testcases/ds_fetch/ds_fetch.adb
testcases/ds_fetch/ds_fetch.adb
with AdaBase; with Connect; with CommonText; with Ada.Text_IO; with AdaBase.Results.Sets; procedure DS_Fetch is package CON renames Connect; package TIO renames Ada.Text_IO; package ARS renames AdaBase.Results.Sets; package CT renames CommonText; row : ARS.DataRow_Access; sql : constant String := "SELECT * FROM fruits WHERE color = 'orange'"; begin declare begin CON.connect_database; exception when others => TIO.Put_Line ("database connect failed."); return; end; CON.STMT := CON.DR.query (sql); TIO.Put_Line (" Query successful: " & CON.STMT.successful'Img); TIO.Put_Line (" Data Discarded: " & CON.STMT.data_discard'Img); TIO.Put_Line ("Number of columns:" & CON.STMT.column_count'Img); TIO.Put_Line (" Number of rows:" & CON.STMT.rows_returned'Img); TIO.Put_Line (""); for c in Natural range 1 .. CON.STMT.column_count loop TIO.Put_Line ("Column" & c'Img & ":"); TIO.Put_Line (" TABLE: " & CON.STMT.column_table (c)); TIO.Put_Line (" NAME: " & CON.STMT.column_name (c)); TIO.Put_Line (" TYPE: " & CON.STMT.column_native_type (c)'Img); end loop; TIO.Put_Line (""); loop row := CON.STMT.fetch_next; exit when ARS.complete (row); TIO.Put (CT.zeropad (Natural (row.column (1).as_byte2), 2) & " "); declare fruit : String := row.column ("fruit").as_string; frlen : Natural := fruit'Length; rest : String (1 .. 12 - frlen) := (others => ' '); begin TIO.Put (rest & fruit); end; TIO.Put (" (" & row.column ("color").as_string & ") calories ="); TIO.Put_Line (row.column (4).as_byte2'Img); end loop; CON.DR.disconnect; end DS_Fetch;
with AdaBase; with Connect; with CommonText; with Ada.Text_IO; with AdaBase.Results.Sets; procedure DS_Fetch is package CON renames Connect; package TIO renames Ada.Text_IO; package ARS renames AdaBase.Results.Sets; package CT renames CommonText; row : ARS.DataRow_Access; sql : constant String := "SELECT * FROM fruits WHERE color = 'orange'"; begin declare begin CON.connect_database; exception when others => TIO.Put_Line ("database connect failed."); return; end; CON.STMT := CON.DR.query (sql); TIO.Put_Line (" Query successful: " & CON.STMT.successful'Img); TIO.Put_Line (" Data Discarded: " & CON.STMT.data_discarded'Img); TIO.Put_Line ("Number of columns:" & CON.STMT.column_count'Img); TIO.Put_Line (" Number of rows:" & CON.STMT.rows_returned'Img); TIO.Put_Line (""); for c in Natural range 1 .. CON.STMT.column_count loop TIO.Put_Line ("Column" & c'Img & ":"); TIO.Put_Line (" TABLE: " & CON.STMT.column_table (c)); TIO.Put_Line (" NAME: " & CON.STMT.column_name (c)); TIO.Put_Line (" TYPE: " & CON.STMT.column_native_type (c)'Img); end loop; TIO.Put_Line (""); loop row := CON.STMT.fetch_next; exit when ARS.complete (row); TIO.Put (CT.zeropad (Natural (row.column (1).as_byte2), 2) & " "); declare fruit : String := row.column ("fruit").as_string; frlen : Natural := fruit'Length; rest : String (1 .. 12 - frlen) := (others => ' '); begin TIO.Put (rest & fruit); end; TIO.Put (" (" & row.column ("color").as_string & ") calories ="); TIO.Put_Line (row.column (4).as_byte2'Img); end loop; CON.DR.disconnect; end DS_Fetch;
Fix new typo on ds_fetch testcase
Fix new typo on ds_fetch testcase
Ada
isc
jrmarino/AdaBase
9fce103f4251b1ddbef7a044f15a5c3ed765471a
src/wiki-nodes.ads
src/wiki-nodes.ads
----------------------------------------------------------------------- -- wiki -- Ada Wiki Engine -- 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 Wiki.Attributes; with Wiki.Documents; with Wiki.Strings; package Wiki.Nodes is pragma Preelaborate; subtype Format_Map is Wiki.Documents.Format_Map; subtype WString is Wide_Wide_String; type Node_Kind is (N_LINE_BREAK, N_HORIZONTAL_RULE, N_PARAGRAPH, N_HEADER, N_BLOCKQUOTE, N_QUOTE, N_TAG_START, N_INDENT, N_TEXT, N_LINK, N_IMAGE); -- Node kinds which are simple markers in the document. subtype Simple_Node_Kind is Node_Kind range N_LINE_BREAK .. N_PARAGRAPH; -- The possible HTML tags as described in HTML5 specification. type Html_Tag_Type is ( -- Section 4.1 The root element HTML_TAG, -- Section 4.2 Document metadata HEAD_TAG, TITLE_TAG, BASE_TAG, LINK_TAG, META_TAG, STYLE_TAG, -- Section 4.3 Sections BODY_TAG, ARTICLE_TAG, SECTION_TAG, NAV_TAG, ASIDE_TAG, H1_TAG, H2_TAG, H3_TAG, H4_TAG, H5_TAG, H6_TAG, HEADER_TAG, FOOTER_TAG, ADDRESS_TAG, -- Section 4.4 Grouping content P_TAG, HR_TAG, PRE_TAG, BLOCKQUOTE_TAG, OL_TAG, UL_TAG, LI_TAG, DL_TAG, DT_TAG, DD_TAG, FIGURE_TAG, FIGCAPTION_TAG, DIV_TAG, MAIN_TAG, -- Section 4.5 Text-level semantics A_TAG, EM_TAG, STRONG_TAG, SMALL_TAG, S_TAG, CITE_TAG, Q_TAG, DFN_TAG, ABBR_TAG, DATA_TAG, TIME_TAG, CODE_TAG, VAR_TAG, SAMP_TAG, KBD_TAG, SUB_TAG, SUP_TAG, I_TAG, B_TAG, U_TAG, MARK_TAG, RUBY_TAG, RB_TAG, RT_TAG, RTC_TAG, RP_TAG, BDI_TAG, BDO_TAG, SPAN_TAG, BR_TAG, WBR_TAG, -- Section 4.6 Edits INS_TAG, DEL_TAG, -- Section 4.7 Embedded content IMG_TAG, IFRAME_TAG, EMBED_TAG, OBJECT_TAG, PARAM_TAG, VIDEO_TAG, AUDIO_TAG, SOURCE_TAG, TRACK_TAG, MAP_TAG, AREA_TAG, -- Section 4.9 Tabular data TABLE_TAG, CAPTION_TAG, COLGROUP_TAG, COL_TAG, TBODY_TAG, THEAD_TAG, TFOOT_TAG, TR_TAG, TD_TAG, TH_TAG, -- Section 4.10 Forms FORM_TAG, LABEL_TAG, INPUT_TAG, BUTTON_TAG, SELECT_TAG, DATALIST_TAG, OPTGROUP_TAG, OPTION_TAG, TEXTAREA_TAG, KEYGEN_TAG, OUTPUT_TAG, PROGRESS_TAG, METER_TAG, FIELDSET_TAG, LEGEND_TAG, -- Section 4.11 Scripting SCRIPT_TAG, NOSCRIPT_TAG, TEMPLATE_TAG, CANVAS_TAG, -- Unknown tags UNKNOWN_TAG ); -- Find the tag from the tag name. function Find_Tag (Name : in Wide_Wide_String) return Html_Tag_Type; type String_Access is access constant String; -- Get the HTML tag name. function Get_Tag_Name (Tag : in Html_Tag_Type) return String_Access; type Node_List is limited private; type Node_List_Access is access all Node_List; type Node_Type; type Node_Type_Access is access all Node_Type; type Node_Type (Kind : Node_Kind; Len : Natural) is limited record case Kind is when N_HEADER | N_BLOCKQUOTE | N_INDENT => Level : Natural := 0; Header : WString (1 .. Len); when N_TEXT => Format : Format_Map; Text : WString (1 .. Len); when N_LINK | N_IMAGE | N_QUOTE => Link_Attr : Wiki.Attributes.Attribute_List_Type; Title : WString (1 .. Len); when N_TAG_START => Tag_Start : Html_Tag_Type; Attributes : Wiki.Attributes.Attribute_List_Type; Children : Node_List_Access; Parent : Node_Type_Access; when others => null; end case; end record; -- Create a text node. function Create_Text (Text : in WString) return Node_Type_Access; type Document is limited private; -- Append a node to the document. procedure Append (Into : in out Document; Node : in Node_Type_Access); -- Append a simple node such as N_LINE_BREAK, N_HORIZONTAL_RULE or N_PARAGRAPH. procedure Append (Into : in out Document; Kind : in Simple_Node_Kind); -- Append a HTML tag start node to the document. procedure Push_Node (Document : in out Wiki.Nodes.Document; Tag : in Html_Tag_Type; Attributes : in Wiki.Attributes.Attribute_List_Type); -- Pop the HTML tag. procedure Pop_Node (Document : in out Wiki.Nodes.Document; Tag : in Html_Tag_Type); -- Append the text with the given format at end of the document. procedure Append (Into : in out Document; Text : in Wiki.Strings.WString; Format : in Format_Map); -- Append a section header at end of the document. procedure Append (Into : in out Document; Header : in Wiki.Strings.WString; Level : in Positive); -- Add a link. procedure Add_Link (Into : in out Document; Name : in Wiki.Strings.WString; Attributes : in out Wiki.Attributes.Attribute_List_Type); -- Add an image. procedure Add_Image (Into : in out Document; Name : in Wiki.Strings.WString; Attributes : in out Wiki.Attributes.Attribute_List_Type); -- Add a quote. procedure Add_Quote (Into : in out Document; Name : in Wiki.Strings.WString; Attributes : in out Wiki.Attributes.Attribute_List_Type); -- Add a list item (<li>). Close the previous paragraph and list item if any. -- The list item will be closed at the next list item, next paragraph or next header. procedure Add_List_Item (Into : in out Document; Level : in Positive; Ordered : in Boolean); -- Add a blockquote (<blockquote>). The level indicates the blockquote nested level. -- The blockquote must be closed at the next header. procedure Add_Blockquote (Into : in out Document; Level : in Natural); -- Add a text block that is pre-formatted. procedure Add_Preformatted (Into : in out Document; Text : in Wiki.Strings.WString; Format : in Wiki.Strings.WString); -- Iterate over the nodes of the list and call the <tt>Process</tt> procedure with -- each node instance. procedure Iterate (List : in Node_List_Access; Process : not null access procedure (Node : in Node_Type)); private NODE_LIST_BLOCK_SIZE : constant Positive := 20; type Node_Array is array (Positive range <>) of Node_Type_Access; type Node_List_Block; type Node_List_Block_Access is access all Node_List_Block; type Node_List_Block (Max : Positive) is limited record Next : Node_List_Block_Access; Last : Natural := 0; List : Node_Array (1 .. Max); end record; type Node_List is limited record Current : Node_List_Block_Access; Length : Natural := 0; First : aliased Node_List_Block (NODE_LIST_BLOCK_SIZE); end record; -- Append a node to the node list. procedure Append (Into : in out Node_List; Node : in Node_Type_Access); type Document is limited record Nodes : Node_List; Current : Node_Type_Access; end record; end Wiki.Nodes;
----------------------------------------------------------------------- -- wiki -- Ada Wiki Engine -- 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 Wiki.Attributes; with Wiki.Strings; package Wiki.Nodes is pragma Preelaborate; subtype WString is Wide_Wide_String; type Node_Kind is (N_LINE_BREAK, N_HORIZONTAL_RULE, N_PARAGRAPH, N_HEADER, N_BLOCKQUOTE, N_QUOTE, N_TAG_START, N_INDENT, N_TEXT, N_LINK, N_IMAGE); -- Node kinds which are simple markers in the document. subtype Simple_Node_Kind is Node_Kind range N_LINE_BREAK .. N_PARAGRAPH; -- The possible HTML tags as described in HTML5 specification. type Html_Tag_Type is ( -- Section 4.1 The root element HTML_TAG, -- Section 4.2 Document metadata HEAD_TAG, TITLE_TAG, BASE_TAG, LINK_TAG, META_TAG, STYLE_TAG, -- Section 4.3 Sections BODY_TAG, ARTICLE_TAG, SECTION_TAG, NAV_TAG, ASIDE_TAG, H1_TAG, H2_TAG, H3_TAG, H4_TAG, H5_TAG, H6_TAG, HEADER_TAG, FOOTER_TAG, ADDRESS_TAG, -- Section 4.4 Grouping content P_TAG, HR_TAG, PRE_TAG, BLOCKQUOTE_TAG, OL_TAG, UL_TAG, LI_TAG, DL_TAG, DT_TAG, DD_TAG, FIGURE_TAG, FIGCAPTION_TAG, DIV_TAG, MAIN_TAG, -- Section 4.5 Text-level semantics A_TAG, EM_TAG, STRONG_TAG, SMALL_TAG, S_TAG, CITE_TAG, Q_TAG, DFN_TAG, ABBR_TAG, DATA_TAG, TIME_TAG, CODE_TAG, VAR_TAG, SAMP_TAG, KBD_TAG, SUB_TAG, SUP_TAG, I_TAG, B_TAG, U_TAG, MARK_TAG, RUBY_TAG, RB_TAG, RT_TAG, RTC_TAG, RP_TAG, BDI_TAG, BDO_TAG, SPAN_TAG, BR_TAG, WBR_TAG, -- Section 4.6 Edits INS_TAG, DEL_TAG, -- Section 4.7 Embedded content IMG_TAG, IFRAME_TAG, EMBED_TAG, OBJECT_TAG, PARAM_TAG, VIDEO_TAG, AUDIO_TAG, SOURCE_TAG, TRACK_TAG, MAP_TAG, AREA_TAG, -- Section 4.9 Tabular data TABLE_TAG, CAPTION_TAG, COLGROUP_TAG, COL_TAG, TBODY_TAG, THEAD_TAG, TFOOT_TAG, TR_TAG, TD_TAG, TH_TAG, -- Section 4.10 Forms FORM_TAG, LABEL_TAG, INPUT_TAG, BUTTON_TAG, SELECT_TAG, DATALIST_TAG, OPTGROUP_TAG, OPTION_TAG, TEXTAREA_TAG, KEYGEN_TAG, OUTPUT_TAG, PROGRESS_TAG, METER_TAG, FIELDSET_TAG, LEGEND_TAG, -- Section 4.11 Scripting SCRIPT_TAG, NOSCRIPT_TAG, TEMPLATE_TAG, CANVAS_TAG, -- Unknown tags UNKNOWN_TAG ); -- Find the tag from the tag name. function Find_Tag (Name : in Wide_Wide_String) return Html_Tag_Type; type String_Access is access constant String; -- Get the HTML tag name. function Get_Tag_Name (Tag : in Html_Tag_Type) return String_Access; type Node_List is limited private; type Node_List_Access is access all Node_List; type Node_Type; type Node_Type_Access is access all Node_Type; type Node_Type (Kind : Node_Kind; Len : Natural) is limited record case Kind is when N_HEADER | N_BLOCKQUOTE | N_INDENT => Level : Natural := 0; Header : WString (1 .. Len); when N_TEXT => Format : Format_Map; Text : WString (1 .. Len); when N_LINK | N_IMAGE | N_QUOTE => Link_Attr : Wiki.Attributes.Attribute_List_Type; Title : WString (1 .. Len); when N_TAG_START => Tag_Start : Html_Tag_Type; Attributes : Wiki.Attributes.Attribute_List_Type; Children : Node_List_Access; Parent : Node_Type_Access; when others => null; end case; end record; -- Create a text node. function Create_Text (Text : in WString) return Node_Type_Access; type Document is limited private; -- Append a node to the document. procedure Append (Into : in out Document; Node : in Node_Type_Access); -- Append a simple node such as N_LINE_BREAK, N_HORIZONTAL_RULE or N_PARAGRAPH. procedure Append (Into : in out Document; Kind : in Simple_Node_Kind); -- Append a HTML tag start node to the document. procedure Push_Node (Document : in out Wiki.Nodes.Document; Tag : in Html_Tag_Type; Attributes : in Wiki.Attributes.Attribute_List_Type); -- Pop the HTML tag. procedure Pop_Node (Document : in out Wiki.Nodes.Document; Tag : in Html_Tag_Type); -- Append the text with the given format at end of the document. procedure Append (Into : in out Document; Text : in Wiki.Strings.WString; Format : in Format_Map); -- Append a section header at end of the document. procedure Append (Into : in out Document; Header : in Wiki.Strings.WString; Level : in Positive); -- Add a link. procedure Add_Link (Into : in out Document; Name : in Wiki.Strings.WString; Attributes : in out Wiki.Attributes.Attribute_List_Type); -- Add an image. procedure Add_Image (Into : in out Document; Name : in Wiki.Strings.WString; Attributes : in out Wiki.Attributes.Attribute_List_Type); -- Add a quote. procedure Add_Quote (Into : in out Document; Name : in Wiki.Strings.WString; Attributes : in out Wiki.Attributes.Attribute_List_Type); -- Add a list item (<li>). Close the previous paragraph and list item if any. -- The list item will be closed at the next list item, next paragraph or next header. procedure Add_List_Item (Into : in out Document; Level : in Positive; Ordered : in Boolean); -- Add a blockquote (<blockquote>). The level indicates the blockquote nested level. -- The blockquote must be closed at the next header. procedure Add_Blockquote (Into : in out Document; Level : in Natural); -- Add a text block that is pre-formatted. procedure Add_Preformatted (Into : in out Document; Text : in Wiki.Strings.WString; Format : in Wiki.Strings.WString); -- Iterate over the nodes of the list and call the <tt>Process</tt> procedure with -- each node instance. procedure Iterate (List : in Node_List_Access; Process : not null access procedure (Node : in Node_Type)); private NODE_LIST_BLOCK_SIZE : constant Positive := 20; type Node_Array is array (Positive range <>) of Node_Type_Access; type Node_List_Block; type Node_List_Block_Access is access all Node_List_Block; type Node_List_Block (Max : Positive) is limited record Next : Node_List_Block_Access; Last : Natural := 0; List : Node_Array (1 .. Max); end record; type Node_List is limited record Current : Node_List_Block_Access; Length : Natural := 0; First : aliased Node_List_Block (NODE_LIST_BLOCK_SIZE); end record; -- Append a node to the node list. procedure Append (Into : in out Node_List; Node : in Node_Type_Access); type Document is limited record Nodes : Node_List; Current : Node_Type_Access; end record; end Wiki.Nodes;
Remove dependency with Wiki.Documents
Remove dependency with Wiki.Documents
Ada
apache-2.0
stcarrez/ada-wiki,stcarrez/ada-wiki
d0c1a2f378949a2f9bb5a29e019e408069cf82c6
awa/plugins/awa-sysadmin/src/awa-sysadmin.ads
awa/plugins/awa-sysadmin/src/awa-sysadmin.ads
----------------------------------------------------------------------- -- awa-sysadmin -- -- Copyright (C) 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. ----------------------------------------------------------------------- package AWA.Sysadmin is pragma Pure; end AWA.Sysadmin;
----------------------------------------------------------------------- -- awa-sysadmin -- sysadmin module -- Copyright (C) 2019, 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. ----------------------------------------------------------------------- package AWA.Sysadmin is pragma Pure; end AWA.Sysadmin;
Fix style warnings: add missing overriding and update and then/or else conditions
Fix style warnings: add missing overriding and update and then/or else conditions
Ada
apache-2.0
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
192cf3c02cd19a630afcc2400656417cdce433b2
src/wiki-render.ads
src/wiki-render.ads
----------------------------------------------------------------------- -- wiki-render -- Wiki renderer -- Copyright (C) 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.Nodes; with Wiki.Strings; with Wiki.Documents; -- == Wiki Renderer == -- The <tt>Wiki.Render</tt> package represents the renderer that takes a wiki document -- and render the result either in text, HTML or another format. -- -- @include wiki-render-html.ads -- @include wiki-render-links.ads -- @include wiki-render-text.ads -- @include wiki-render-wiki.ads package Wiki.Render is pragma Preelaborate; -- ------------------------------ -- Document renderer -- ------------------------------ type Renderer is limited interface; type Renderer_Access is access all Renderer'Class; -- Render the node instance from the document. procedure Render (Engine : in out Renderer; Doc : in Wiki.Documents.Document; Node : in Wiki.Nodes.Node_Type) is abstract; -- Finish the rendering pass after all the wiki document nodes are rendered. procedure Finish (Engine : in out Renderer; Doc : in Wiki.Documents.Document) is null; -- Render the list of nodes from the document. procedure Render (Engine : in out Renderer'Class; Doc : in Wiki.Documents.Document; List : in Wiki.Nodes.Node_List_Access); -- Render the document. procedure Render (Engine : in out Renderer'Class; Doc : in Wiki.Documents.Document); end Wiki.Render;
----------------------------------------------------------------------- -- wiki-render -- Wiki renderer -- Copyright (C) 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.Nodes; with Wiki.Documents; -- == Wiki Renderer == -- The <tt>Wiki.Render</tt> package represents the renderer that takes a wiki document -- and render the result either in text, HTML or another format. -- -- @include wiki-render-html.ads -- @include wiki-render-links.ads -- @include wiki-render-text.ads -- @include wiki-render-wiki.ads package Wiki.Render is pragma Preelaborate; -- ------------------------------ -- Document renderer -- ------------------------------ type Renderer is limited interface; type Renderer_Access is access all Renderer'Class; -- Render the node instance from the document. procedure Render (Engine : in out Renderer; Doc : in Wiki.Documents.Document; Node : in Wiki.Nodes.Node_Type) is abstract; -- Finish the rendering pass after all the wiki document nodes are rendered. procedure Finish (Engine : in out Renderer; Doc : in Wiki.Documents.Document) is null; -- Render the list of nodes from the document. procedure Render (Engine : in out Renderer'Class; Doc : in Wiki.Documents.Document; List : in Wiki.Nodes.Node_List_Access); -- Render the document. procedure Render (Engine : in out Renderer'Class; Doc : in Wiki.Documents.Document); end Wiki.Render;
Fix compilation warnings
Fix compilation warnings
Ada
apache-2.0
stcarrez/ada-wiki,stcarrez/ada-wiki
3d4157d9959e902e7477076b7b08a493e2bc8347
regtests/util-events-timers-tests.adb
regtests/util-events-timers-tests.adb
----------------------------------------------------------------------- -- util-events-timers-tests -- Unit tests for timers -- 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 Util.Test_Caller; package body Util.Events.Timers.Tests is use Util.Tests; use type Ada.Real_Time.Time; package Caller is new Util.Test_Caller (Test, "Events.Timers"); procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is begin Caller.Add_Test (Suite, "Test Util.Events.Timers.Is_Scheduled", Test_Empty_Timer'Access); Caller.Add_Test (Suite, "Test Util.Events.Timers.Process", Test_Timer_Event'Access); end Add_Tests; overriding procedure Time_Handler (Sub : in out Test; Event : in out Timer_Ref'Class) is begin Sub.Count := Sub.Count + 1; end Time_Handler; -- ----------------------- -- Test empty timers. -- ----------------------- procedure Test_Empty_Timer (T : in out Test) is M : Timer_List; R : Timer_Ref; Deadline : Ada.Real_Time.Time; begin T.Assert (not R.Is_Scheduled, "Empty timer should not be scheduled"); T.Assert (R.Time_Of_Event = Ada.Real_Time.Time_Last, "Time_Of_Event returned invalid value"); R.Cancel; M.Process (Deadline); T.Assert (Deadline = Ada.Real_Time.Time_Last, "The Process operation returned invalid deadline"); end Test_Empty_Timer; procedure Test_Timer_Event (T : in out Test) is M : Timer_List; R : Timer_Ref; Start : constant Ada.Real_Time.Time := Ada.Real_Time.Clock; Deadline : Ada.Real_Time.Time; Now : Ada.Real_Time.Time; begin for Retry in 1 .. 10 loop M.Set_Timer (T'Unchecked_Access, R, Start + Ada.Real_Time.Milliseconds (10)); M.Process (Deadline); Now := Ada.Real_Time.Clock; exit when Now < Deadline; end loop; T.Assert (Now < Deadline, "The timer deadline is not correct"); delay until Deadline; M.Process (Deadline); Assert_Equals (T, 1, T.Count, "The timer handler was not called"); end Test_Timer_Event; end Util.Events.Timers.Tests;
----------------------------------------------------------------------- -- util-events-timers-tests -- Unit tests for timers -- 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 Util.Test_Caller; package body Util.Events.Timers.Tests is use Util.Tests; use type Ada.Real_Time.Time; package Caller is new Util.Test_Caller (Test, "Events.Timers"); procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is begin Caller.Add_Test (Suite, "Test Util.Events.Timers.Is_Scheduled", Test_Empty_Timer'Access); Caller.Add_Test (Suite, "Test Util.Events.Timers.Process", Test_Timer_Event'Access); Caller.Add_Test (Suite, "Test Util.Events.Timers.Repeat", Test_Repeat_Timer'Access); end Add_Tests; overriding procedure Time_Handler (Sub : in out Test; Event : in out Timer_Ref'Class) is begin Sub.Count := Sub.Count + 1; if Sub.Repeat > 1 then Sub.Repeat := Sub.Repeat - 1; Event.Repeat (Ada.Real_Time.Milliseconds (1)); end if; end Time_Handler; -- ----------------------- -- Test empty timers. -- ----------------------- procedure Test_Empty_Timer (T : in out Test) is M : Timer_List; R : Timer_Ref; Deadline : Ada.Real_Time.Time; begin T.Assert (not R.Is_Scheduled, "Empty timer should not be scheduled"); T.Assert (R.Time_Of_Event = Ada.Real_Time.Time_Last, "Time_Of_Event returned invalid value"); R.Cancel; M.Process (Deadline); T.Assert (Deadline = Ada.Real_Time.Time_Last, "The Process operation returned invalid deadline"); end Test_Empty_Timer; procedure Test_Timer_Event (T : in out Test) is M : Timer_List; R : Timer_Ref; Start : constant Ada.Real_Time.Time := Ada.Real_Time.Clock; Deadline : Ada.Real_Time.Time; Now : Ada.Real_Time.Time; begin for Retry in 1 .. 10 loop M.Set_Timer (T'Unchecked_Access, R, Start + Ada.Real_Time.Milliseconds (10)); M.Process (Deadline); Now := Ada.Real_Time.Clock; exit when Now < Deadline; end loop; T.Assert (Now < Deadline, "The timer deadline is not correct"); delay until Deadline; M.Process (Deadline); Assert_Equals (T, 1, T.Count, "The timer handler was not called"); end Test_Timer_Event; -- ----------------------- -- Test repeating timers. -- ----------------------- procedure Test_Repeat_Timer (T : in out Test) is M : Timer_List; R : Timer_Ref; Start : constant Ada.Real_Time.Time := Ada.Real_Time.Clock; Deadline : Ada.Real_Time.Time; Now : Ada.Real_Time.Time; begin T.Count := 0; T.Repeat := 5; for Retry in 1 .. 10 loop M.Set_Timer (T'Unchecked_Access, R, Start + Ada.Real_Time.Milliseconds (10)); M.Process (Deadline); Now := Ada.Real_Time.Clock; exit when Now < Deadline; end loop; T.Assert (Now < Deadline, "The timer deadline is not correct"); loop delay until Deadline; M.Process (Deadline); exit when Deadline >= Now + Ada.Real_Time.Seconds (1); end loop; Assert_Equals (T, 5, T.Count, "The timer handler was not repeated"); end Test_Repeat_Timer; end Util.Events.Timers.Tests;
Implement the Test_Repeat_Timer procedure and register the new test
Implement the Test_Repeat_Timer procedure and register the new test
Ada
apache-2.0
stcarrez/ada-util,stcarrez/ada-util
0b24471091238045ff5c061a370dee63e4cfb6cd
orka_tools/src/orka_ktx.adb
orka_tools/src/orka_ktx.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.Command_Line; with Ada.Directories; with Ada.Exceptions; with Ada.Real_Time; with Ada.Text_IO; with GL.Objects.Samplers; with GL.Objects.Textures; with GL.Toggles; with GL.Types; with GL.Viewports; with Orka.Behaviors; with Orka.Cameras.Rotate_Around_Cameras; with Orka.Contexts.AWT; with Orka.Debug; with Orka.Loggers.Terminal; with Orka.Logging; with Orka.Loops; with Orka.Rendering.Drawing; with Orka.Rendering.Framebuffers; with Orka.Rendering.Programs.Modules; with Orka.Rendering.Programs.Uniforms; with Orka.Rendering.Textures; with Orka.Resources.Locations.Directories; with Orka.Resources.Textures.KTX; with Orka.Types; with Orka.Windows; with AWT.Inputs; with Orka_Package_KTX; procedure Orka_KTX is Width : constant := 1280; Height : constant := 720; type Zoom_Mode is (Best_Fit, Actual_Size); type View_Mode is (External, Internal); package Job_System renames Orka_Package_KTX.Job_System; package Loader renames Orka_Package_KTX.Loader; use all type Orka.Logging.Source; use all type Orka.Logging.Severity; package Messages is new Orka.Logging.Messages (Application); begin if Ada.Command_Line.Argument_Count /= 1 then Ada.Text_IO.Put_Line ("Usage: <path to .ktx file>"); Job_System.Shutdown; Loader.Shutdown; return; end if; Orka.Logging.Set_Logger (Orka.Loggers.Terminal.Create_Logger (Level => Orka.Loggers.Info)); declare Context : constant Orka.Contexts.Context'Class := Orka.Contexts.AWT.Create_Context (Version => (4, 2), Flags => (Debug => True, others => False)); Window : constant Orka.Windows.Window'Class := Orka.Contexts.AWT.Create_Window (Context, Width, Height, Resizable => False); begin Orka.Debug.Set_Log_Messages (Enable => True); declare Full_Path : constant String := Ada.Command_Line.Argument (1); Location_Path : constant String := Ada.Directories.Containing_Directory (Full_Path); Texture_Path : constant String := Ada.Directories.Simple_Name (Full_Path); use Orka.Rendering.Programs; use Orka.Rendering.Framebuffers; use Orka.Resources; use GL.Types; ---------------------------------------------------------------------- FB_D : Framebuffer := Get_Default_Framebuffer (Window); use Orka.Cameras; Lens : constant Lens_Ptr := new Camera_Lens'Class'(Create_Lens (Width, Height, Transforms.FOV (36.0, 50.0), Context)); Current_Camera : constant Camera_Ptr := new Camera'Class'(Camera'Class (Rotate_Around_Cameras.Create_Camera (Window.Pointer_Input, Lens, FB_D))); ---------------------------------------------------------------------- use GL.Objects.Textures; use GL.Objects.Samplers; Sampler_1 : Sampler; Location_Textures : constant Locations.Location_Ptr := Locations.Directories.Create_Location (Location_Path); T_1 : constant Texture := Orka.Resources.Textures.KTX.Read_Texture (Location_Textures, Texture_Path); Maximum_Level : constant Mipmap_Level := T_1.Mipmap_Levels - 1; ---------------------------------------------------------------------- Location_Shaders : constant Locations.Location_Ptr := Locations.Directories.Create_Location ("data/shaders"); function Get_Module (Kind : LE.Texture_Kind) return Modules.Module is use all type LE.Texture_Kind; begin case Kind is when Texture_1D => return Modules.Create_Module (Location_Shaders, VS => "oversized-triangle.vert", FS => "tools/ktx-1D.frag"); when Texture_2D => return Modules.Create_Module (Location_Shaders, VS => "oversized-triangle.vert", FS => "tools/ktx-2D.frag"); when Texture_3D => return Modules.Create_Module (Location_Shaders, VS => "tools/volume.vert", FS => "tools/ktx-3D.frag"); when Texture_Cube_Map => return Modules.Create_Module (Location_Shaders, VS => "tools/cube.vert", FS => "tools/ktx-cube.frag"); when Texture_2D_Array => return Modules.Create_Module (Location_Shaders, VS => "oversized-triangle.vert", FS => "tools/ktx-2D-array.frag"); when others => raise Constraint_Error with "Unsupported texture kind"; end case; end Get_Module; procedure Draw (Kind : LE.Texture_Kind) is use all type LE.Texture_Kind; begin case Kind is when Texture_1D | Texture_2D | Texture_2D_Array => Orka.Rendering.Drawing.Draw (GL.Types.Triangles, 0, 3); when Texture_3D | Texture_Cube_Map => Orka.Rendering.Drawing.Draw (GL.Types.Triangles, 0, 6 * 6); when others => raise Constraint_Error; end case; end Draw; procedure Update_Title (Kind : LE.Texture_Kind; Mode : Zoom_Mode; View : View_Mode; Colors : Boolean; Level, Levels : Mipmap_Level) is use all type LE.Texture_Kind; use type Zoom_Mode; use type View_Mode; Text : SU.Unbounded_String := SU.To_Unbounded_String ("KTX viewer - " & Texture_Path); begin if Levels > 1 then SU.Append (Text, " (level " & Orka.Logging.Trim (Mipmap_Level'Image (Level + 1)) & "/" & Orka.Logging.Trim (Levels'Image) & ")"); end if; case Kind is when Texture_1D | Texture_2D | Texture_2D_Array => SU.Append (Text, " (zoom: " & Mode'Image & ")"); when Texture_3D | Texture_Cube_Map => SU.Append (Text, " (view: " & View'Image & ")"); SU.Append (Text, " (colors: " & Colors'Image & ")"); when others => null; end case; Window.Set_Title (SU.To_String (Text)); end Update_Title; P_1 : Program := Create_Program (Get_Module (T_1.Kind)); Uni_Texture : constant Uniforms.Uniform_Sampler := P_1.Uniform_Sampler ("colorTexture"); begin -- Clear color to black and depth to 0.0 (if using reversed Z) FB_D.Set_Default_Values ((Color => (0.0, 0.0, 0.0, 1.0), Depth => (if Context.Enabled (Orka.Contexts.Reversed_Z) then 0.0 else 1.0), others => <>)); FB_D.Use_Framebuffer; P_1.Use_Program; Uni_Texture.Verify_Compatibility (T_1); Orka.Rendering.Textures.Bind (T_1, Orka.Rendering.Textures.Texture, 0); Sampler_1.Set_X_Wrapping (Clamp_To_Edge); Sampler_1.Set_Y_Wrapping (Clamp_To_Edge); Sampler_1.Set_Minifying_Filter (Linear); Sampler_1.Set_Magnifying_Filter (Linear); Sampler_1.Bind (0); GL.Toggles.Enable (GL.Toggles.Depth_Test); GL.Toggles.Enable (GL.Toggles.Texture_Cube_Map_Seamless); declare Level : Mipmap_Level := 0 with Atomic; Render_Zoom : Zoom_Mode := Best_Fit with Atomic; Render_View : View_Mode := External with Atomic; Render_Colors : Boolean := False with Atomic; procedure Render (Scene : not null Orka.Behaviors.Behavior_Array_Access; Camera : Orka.Cameras.Camera_Ptr) is use all type LE.Texture_Kind; begin Camera.FB.Clear; T_1.Set_Lowest_Mipmap_Level (Level); Update_Title (T_1.Kind, Render_Zoom, Render_View, Render_Colors, Level, Maximum_Level + 1); case T_1.Kind is when Texture_1D | Texture_2D | Texture_2D_Array => declare Uni_Screen : constant Uniforms.Uniform := P_1.Uniform ("screenSize"); Uni_Best_Fit : constant Uniforms.Uniform := P_1.Uniform ("useBestFit"); begin Uni_Screen.Set_Vector (Orka.Types.Singles.Vector4' (Single (Window.Width), Single (Window.Height), 0.0, 0.0) ); Uni_Best_Fit.Set_Boolean (Render_Zoom = Best_Fit); end; when Texture_3D | Texture_Cube_Map => declare Uni_View : constant Uniforms.Uniform := P_1.Uniform ("view"); Uni_Proj : constant Uniforms.Uniform := P_1.Uniform ("proj"); Uni_External : constant Uniforms.Uniform := P_1.Uniform ("showExternal"); Uni_Colors : constant Uniforms.Uniform := P_1.Uniform ("showColors"); begin Uni_View.Set_Matrix (Camera.View_Matrix); Uni_Proj.Set_Matrix (Camera.Projection_Matrix); Uni_External.Set_Boolean (Render_View = External); Uni_Colors.Set_Boolean (Render_Colors); end; when others => null; end case; -- TODO When the window gets resized, it should automatically update -- the default framebuffer GL.Viewports.Set_Viewports ((0 => (X => 0.0, Y => 0.0, Width => Single (Window.Width), Height => Single (Window.Height)) )); Draw (T_1.Kind); end Render; package Loops is new Orka.Loops (Time_Step => Ada.Real_Time.Microseconds (2_083), Frame_Limit => Ada.Real_Time.Microseconds (16_667), Window => Window'Unchecked_Access, Camera => Current_Camera, Job_Manager => Job_System); begin Loops.Scene.Add (Orka.Behaviors.Null_Behavior); declare task Render_Task is entry Start_Rendering; end Render_Task; task body Render_Task is begin accept Start_Rendering; Context.Make_Current (Window); Loops.Run_Loop (Render'Access, Loops.Stop_Loop'Access); Context.Make_Not_Current; exception when Error : others => Ada.Text_IO.Put_Line ("Error: " & Ada.Exceptions.Exception_Information (Error)); Context.Make_Not_Current; raise; end Render_Task; begin Context.Make_Not_Current; Render_Task.Start_Rendering; while not Window.Should_Close and then AWT.Process_Events (0.016667) loop declare Keyboard : constant AWT.Inputs.Keyboard_State := Window.State; use all type AWT.Inputs.Keyboard_Button; begin if Keyboard.Pressed (Key_Escape) then Window.Close; end if; if Keyboard.Pressed (Key_Arrow_Down) then Level := Mipmap_Level'Max (0, Level - 1); end if; if Keyboard.Pressed (Key_Arrow_Up) then Level := Mipmap_Level'Min (Maximum_Level, Level + 1); end if; if Keyboard.Pressed (Key_Z) then if Render_Zoom = Zoom_Mode'Last then Render_Zoom := Zoom_Mode'First; else Render_Zoom := Zoom_Mode'Succ (Render_Zoom); end if; end if; if Keyboard.Pressed (Key_V) then if Render_View = View_Mode'Last then Render_View := View_Mode'First; else Render_View := View_Mode'Succ (Render_View); end if; end if; if Keyboard.Pressed (Key_C) then Render_Colors := not Render_Colors; end if; end; end loop; end; end; end; end; Job_System.Shutdown; Loader.Shutdown; exception when Error : others => Ada.Text_IO.Put_Line ("Error: " & Ada.Exceptions.Exception_Information (Error)); Job_System.Shutdown; Loader.Shutdown; end Orka_KTX;
-- 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.Command_Line; with Ada.Containers.Indefinite_Holders; with Ada.Directories; with Ada.Exceptions; with Ada.Real_Time; with Ada.Strings.Unbounded; with Ada.Text_IO; with Ada.Containers.Vectors; with GL.Objects.Samplers; with GL.Objects.Textures; with GL.Toggles; with GL.Types; with GL.Viewports; with Orka.Behaviors; with Orka.Cameras.Rotate_Around_Cameras; with Orka.Contexts.AWT; with Orka.Debug; with Orka.Loggers.Terminal; with Orka.Logging; with Orka.Loops; with Orka.Rendering.Drawing; with Orka.Rendering.Framebuffers; with Orka.Rendering.Programs.Modules; with Orka.Rendering.Programs.Uniforms; with Orka.Rendering.Textures; with Orka.Resources.Locations.Directories; with Orka.Resources.Textures.KTX; with Orka.Types; with Orka.Windows; with AWT.Inputs; with Orka_Package_KTX; procedure Orka_KTX is Width : constant := 1280; Height : constant := 720; type Zoom_Mode is (Best_Fit, Actual_Size); type View_Mode is (External, Internal); package Job_System renames Orka_Package_KTX.Job_System; package Loader renames Orka_Package_KTX.Loader; use all type Orka.Logging.Source; use all type Orka.Logging.Severity; package Messages is new Orka.Logging.Messages (Application); package SU renames Ada.Strings.Unbounded; use type SU.Unbounded_String; begin if Ada.Command_Line.Argument_Count /= 1 then Ada.Text_IO.Put_Line ("Usage: <path to .ktx file>"); Job_System.Shutdown; Loader.Shutdown; return; end if; Orka.Logging.Set_Logger (Orka.Loggers.Terminal.Create_Logger (Level => Orka.Loggers.Info)); declare Context : constant Orka.Contexts.Context'Class := Orka.Contexts.AWT.Create_Context (Version => (4, 2), Flags => (Debug => True, others => False)); Window : constant Orka.Windows.Window'Class := Orka.Contexts.AWT.Create_Window (Context, Width, Height, Resizable => False); begin Orka.Debug.Set_Log_Messages (Enable => True); declare Full_Path : constant String := Ada.Command_Line.Argument (1); Location_Path : constant String := Ada.Directories.Containing_Directory (Full_Path); Texture_Path : SU.Unbounded_String := SU.To_Unbounded_String (Ada.Directories.Simple_Name (Full_Path)); Load_Texture_Path : SU.Unbounded_String := Texture_Path; type Load_Action_Kind is (Previous_File, Next_File); procedure Load_File (Action : Load_Action_Kind) is package String_Vectors is new Ada.Containers.Vectors (Positive, SU.Unbounded_String); Files : String_Vectors.Vector; procedure Process_File (File : Ada.Directories.Directory_Entry_Type) is Name : constant String := Ada.Directories.Simple_Name (File); begin Files.Append (SU.To_Unbounded_String (Name)); end Process_File; use all type Ada.Directories.File_Kind; begin Ada.Directories.Search (Directory => Location_Path, Pattern => "*.ktx", Filter => (Ordinary_File => True, others => False), Process => Process_File'Access); declare Cursor : String_Vectors.Cursor := Files.Find (Texture_Path); use type String_Vectors.Cursor; begin case Action is when Previous_File => Cursor := String_Vectors.Previous (Cursor); when Next_File => Cursor := String_Vectors.Next (Cursor); end case; if Cursor /= String_Vectors.No_Element then Load_Texture_Path := Files (Cursor); end if; end; end Load_File; use Orka.Rendering.Programs; use Orka.Rendering.Framebuffers; use Orka.Resources; use GL.Types; ---------------------------------------------------------------------- FB_D : Framebuffer := Get_Default_Framebuffer (Window); use Orka.Cameras; Lens : constant Lens_Ptr := new Camera_Lens'Class'(Create_Lens (Width, Height, Transforms.FOV (36.0, 50.0), Context)); Current_Camera : constant Camera_Ptr := new Camera'Class'(Camera'Class (Rotate_Around_Cameras.Create_Camera (Window.Pointer_Input, Lens, FB_D))); ---------------------------------------------------------------------- use GL.Objects.Textures; use GL.Objects.Samplers; Sampler_1 : Sampler; Location_Textures : constant Locations.Location_Ptr := Locations.Directories.Create_Location (Location_Path); package Texture_Holders is new Ada.Containers.Indefinite_Holders (Element_Type => GL.Objects.Textures.Texture); T_1 : Texture_Holders.Holder; Maximum_Level : Mipmap_Level; ---------------------------------------------------------------------- Location_Shaders : constant Locations.Location_Ptr := Locations.Directories.Create_Location ("data/shaders"); function Get_Module (Kind : LE.Texture_Kind) return Modules.Module is use all type LE.Texture_Kind; begin case Kind is when Texture_1D => return Modules.Create_Module (Location_Shaders, VS => "oversized-triangle.vert", FS => "tools/ktx-1D.frag"); when Texture_2D => return Modules.Create_Module (Location_Shaders, VS => "oversized-triangle.vert", FS => "tools/ktx-2D.frag"); when Texture_3D => return Modules.Create_Module (Location_Shaders, VS => "tools/volume.vert", FS => "tools/ktx-3D.frag"); when Texture_Cube_Map => return Modules.Create_Module (Location_Shaders, VS => "tools/cube.vert", FS => "tools/ktx-cube.frag"); when Texture_2D_Array => return Modules.Create_Module (Location_Shaders, VS => "oversized-triangle.vert", FS => "tools/ktx-2D-array.frag"); when others => raise Constraint_Error with "Unsupported texture kind"; end case; end Get_Module; procedure Draw (Kind : LE.Texture_Kind) is use all type LE.Texture_Kind; begin case Kind is when Texture_1D | Texture_2D | Texture_2D_Array => Orka.Rendering.Drawing.Draw (GL.Types.Triangles, 0, 3); when Texture_3D | Texture_Cube_Map => Orka.Rendering.Drawing.Draw (GL.Types.Triangles, 0, 6 * 6); when others => raise Constraint_Error; end case; end Draw; procedure Update_Title (Kind : LE.Texture_Kind; Mode : Zoom_Mode; View : View_Mode; Colors : Boolean; Level, Levels : Mipmap_Level) is use all type LE.Texture_Kind; use type Zoom_Mode; use type View_Mode; Text : SU.Unbounded_String := "KTX viewer - " & Texture_Path; begin if Levels > 1 then SU.Append (Text, " (level " & Orka.Logging.Trim (Mipmap_Level'Image (Level + 1)) & "/" & Orka.Logging.Trim (Levels'Image) & ")"); end if; case Kind is when Texture_1D | Texture_2D | Texture_2D_Array => SU.Append (Text, " (zoom: " & Mode'Image & ")"); when Texture_3D | Texture_Cube_Map => SU.Append (Text, " (view: " & View'Image & ")"); SU.Append (Text, " (colors: " & Colors'Image & ")"); when others => null; end case; Window.Set_Title (SU.To_String (Text)); end Update_Title; P_1 : Program; begin -- Clear color to black and depth to 0.0 (if using reversed Z) FB_D.Set_Default_Values ((Color => (0.0, 0.0, 0.0, 1.0), Depth => (if Context.Enabled (Orka.Contexts.Reversed_Z) then 0.0 else 1.0), others => <>)); FB_D.Use_Framebuffer; Sampler_1.Set_X_Wrapping (Clamp_To_Edge); Sampler_1.Set_Y_Wrapping (Clamp_To_Edge); Sampler_1.Set_Minifying_Filter (Linear); Sampler_1.Set_Magnifying_Filter (Linear); Sampler_1.Bind (0); GL.Toggles.Enable (GL.Toggles.Depth_Test); GL.Toggles.Enable (GL.Toggles.Texture_Cube_Map_Seamless); declare Level : Mipmap_Level := 0 with Atomic; Render_Zoom : Zoom_Mode := Best_Fit with Atomic; Render_View : View_Mode := External with Atomic; Render_Colors : Boolean := False with Atomic; procedure Render (Scene : not null Orka.Behaviors.Behavior_Array_Access; Camera : Orka.Cameras.Camera_Ptr) is use all type LE.Texture_Kind; begin Camera.FB.Clear; if Load_Texture_Path /= SU.Null_Unbounded_String then T_1 := Texture_Holders.To_Holder (Orka.Resources.Textures.KTX.Read_Texture (Location_Textures, SU.To_String (Load_Texture_Path))); P_1 := Create_Program (Get_Module (T_1.Constant_Reference.Kind)); P_1.Use_Program; declare Uni_Texture : constant Uniforms.Uniform_Sampler := P_1.Uniform_Sampler ("colorTexture"); begin Uni_Texture.Verify_Compatibility (T_1.Constant_Reference); Orka.Rendering.Textures.Bind (T_1.Constant_Reference, Orka.Rendering.Textures.Texture, 0); end; Maximum_Level := T_1.Constant_Reference.Mipmap_Levels - 1; Level := Mipmap_Level'Min (Level, Maximum_Level); Texture_Path := Load_Texture_Path; Load_Texture_Path := SU.Null_Unbounded_String; end if; T_1.Constant_Reference.Set_Lowest_Mipmap_Level (Level); Update_Title (T_1.Constant_Reference.Kind, Render_Zoom, Render_View, Render_Colors, Level, Maximum_Level + 1); case T_1.Constant_Reference.Kind is when Texture_1D | Texture_2D | Texture_2D_Array => declare Uni_Screen : constant Uniforms.Uniform := P_1.Uniform ("screenSize"); Uni_Best_Fit : constant Uniforms.Uniform := P_1.Uniform ("useBestFit"); begin Uni_Screen.Set_Vector (Orka.Types.Singles.Vector4' (Single (Window.Width), Single (Window.Height), 0.0, 0.0) ); Uni_Best_Fit.Set_Boolean (Render_Zoom = Best_Fit); end; when Texture_3D | Texture_Cube_Map => declare Uni_View : constant Uniforms.Uniform := P_1.Uniform ("view"); Uni_Proj : constant Uniforms.Uniform := P_1.Uniform ("proj"); Uni_External : constant Uniforms.Uniform := P_1.Uniform ("showExternal"); Uni_Colors : constant Uniforms.Uniform := P_1.Uniform ("showColors"); begin Uni_View.Set_Matrix (Camera.View_Matrix); Uni_Proj.Set_Matrix (Camera.Projection_Matrix); Uni_External.Set_Boolean (Render_View = External); Uni_Colors.Set_Boolean (Render_Colors); end; when others => null; end case; -- TODO When the window gets resized, it should automatically update -- the default framebuffer GL.Viewports.Set_Viewports ((0 => (X => 0.0, Y => 0.0, Width => Single (Window.Width), Height => Single (Window.Height)) )); Draw (T_1.Constant_Reference.Kind); end Render; package Loops is new Orka.Loops (Time_Step => Ada.Real_Time.Microseconds (2_083), Frame_Limit => Ada.Real_Time.Microseconds (16_667), Window => Window'Unchecked_Access, Camera => Current_Camera, Job_Manager => Job_System); begin Loops.Scene.Add (Orka.Behaviors.Null_Behavior); declare task Render_Task is entry Start_Rendering; end Render_Task; task body Render_Task is begin accept Start_Rendering; Context.Make_Current (Window); Loops.Run_Loop (Render'Access, Loops.Stop_Loop'Access); Context.Make_Not_Current; exception when Error : others => Ada.Text_IO.Put_Line ("Error: " & Ada.Exceptions.Exception_Information (Error)); Context.Make_Not_Current; raise; end Render_Task; begin Context.Make_Not_Current; Render_Task.Start_Rendering; while not Window.Should_Close and then AWT.Process_Events (0.016667) loop declare Keyboard : constant AWT.Inputs.Keyboard_State := Window.State; use all type AWT.Inputs.Keyboard_Button; begin if Keyboard.Pressed (Key_Escape) then Window.Close; end if; if Keyboard.Pressed (Key_Arrow_Down) then Level := Mipmap_Level'Max (0, Level - 1); end if; if Keyboard.Pressed (Key_Arrow_Up) then Level := Mipmap_Level'Min (Maximum_Level, Level + 1); end if; if Keyboard.Pressed (Key_Arrow_Left) then Load_File (Previous_File); end if; if Keyboard.Pressed (Key_Arrow_Right) then Load_File (Next_File); end if; if Keyboard.Pressed (Key_Z) then if Render_Zoom = Zoom_Mode'Last then Render_Zoom := Zoom_Mode'First; else Render_Zoom := Zoom_Mode'Succ (Render_Zoom); end if; end if; if Keyboard.Pressed (Key_V) then if Render_View = View_Mode'Last then Render_View := View_Mode'First; else Render_View := View_Mode'Succ (Render_View); end if; end if; if Keyboard.Pressed (Key_C) then Render_Colors := not Render_Colors; end if; end; end loop; end; end; end; end; Job_System.Shutdown; Loader.Shutdown; exception when Error : others => Ada.Text_IO.Put_Line ("Error: " & Ada.Exceptions.Exception_Information (Error)); Job_System.Shutdown; Loader.Shutdown; end Orka_KTX;
Support loading previous/next file in folder of current KTX file
tools: Support loading previous/next file in folder of current KTX file Signed-off-by: onox <[email protected]> Fixes: #53
Ada
apache-2.0
onox/orka
ea56ce13ebd6d49189757f142189a6fa3dfd89a2
regtests/asf-applications-tests.ads
regtests/asf-applications-tests.ads
----------------------------------------------------------------------- -- asf-applications-tests - ASF Application tests using ASFUnit -- Copyright (C) 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 Util.Tests; with Util.Beans.Basic; with Util.Beans.Objects; with Util.Beans.Methods; with Util.Beans.Basic.Lists; with Ada.Strings.Unbounded; package ASF.Applications.Tests is use Ada.Strings.Unbounded; Test_Exception : exception; procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite); type Test is new Util.Tests.Test with null record; -- Initialize the test application overriding procedure Set_Up (T : in out Test); -- Test a GET request on a static file served by the File_Servlet. procedure Test_Get_File (T : in out Test); -- Test a GET 404 error on missing static file served by the File_Servlet. procedure Test_Get_404 (T : in out Test); -- Test a GET request on the measure servlet procedure Test_Get_Measures (T : in out Test); -- Test an invalid HTTP request. procedure Test_Invalid_Request (T : in out Test); -- Test a GET+POST request with submitted values and an action method called on the bean. procedure Test_Form_Post (T : in out Test); -- Test a POST request with an invalid submitted value procedure Test_Form_Post_Validation_Error (T : in out Test); -- Test a GET+POST request with form having <h:selectOneMenu> element. procedure Test_Form_Post_Select (T : in out Test); -- Test a POST request to invoke a bean method. procedure Test_Ajax_Action (T : in out Test); -- Test a POST request to invoke a bean method. -- Verify that invalid requests raise an error. procedure Test_Ajax_Action_Error (T : in out Test); -- Test a POST/REDIRECT/GET request with a flash information passed in between. procedure Test_Flash_Object (T : in out Test); -- Test a GET+POST request with the default navigation rule based on the outcome. procedure Test_Default_Navigation_Rule (T : in out Test); -- Test a GET request with meta data and view parameters. procedure Test_View_Params (T : in out Test); -- Test a GET request with meta data and view action. procedure Test_View_Action (T : in out Test); type Form_Bean is new Util.Beans.Basic.Bean and Util.Beans.Methods.Method_Bean with record Name : Unbounded_String; Password : Unbounded_String; Email : Unbounded_String; Called : Natural := 0; Gender : Unbounded_String; Use_Flash : Boolean := False; Def_Nav : Boolean := False; Perm_Error : Boolean := False; end record; type Form_Bean_Access is access all Form_Bean'Class; -- Get the value identified by the name. overriding function Get_Value (From : in Form_Bean; Name : in String) return Util.Beans.Objects.Object; -- Set the value identified by the name. overriding procedure Set_Value (From : in out Form_Bean; Name : in String; Value : in Util.Beans.Objects.Object); -- This bean provides some methods that can be used in a Method_Expression overriding function Get_Method_Bindings (From : in Form_Bean) return Util.Beans.Methods.Method_Binding_Array_Access; -- Action to save the form procedure Save (Data : in out Form_Bean; Outcome : in out Unbounded_String); -- Create a list of forms. package Form_Lists is new Util.Beans.Basic.Lists (Form_Bean); -- Create a list of forms. function Create_Form_List return Util.Beans.Basic.Readonly_Bean_Access; -- Initialize the ASF application for the unit test. procedure Initialize_Test_Application; end ASF.Applications.Tests;
----------------------------------------------------------------------- -- asf-applications-tests - ASF Application tests using ASFUnit -- Copyright (C) 2011, 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.Tests; with Util.Beans.Basic; with Util.Beans.Objects; with Util.Beans.Methods; with Util.Beans.Basic.Lists; with Ada.Strings.Unbounded; package ASF.Applications.Tests is use Ada.Strings.Unbounded; Test_Exception : exception; procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite); type Test is new Util.Tests.Test with null record; -- Initialize the test application overriding procedure Set_Up (T : in out Test); -- Test a GET request on a static file served by the File_Servlet. procedure Test_Get_File (T : in out Test); -- Test a GET 404 error on missing static file served by the File_Servlet. procedure Test_Get_404 (T : in out Test); -- Test a GET request on the measure servlet procedure Test_Get_Measures (T : in out Test); -- Test an invalid HTTP request. procedure Test_Invalid_Request (T : in out Test); -- Test a GET+POST request with submitted values and an action method called on the bean. procedure Test_Form_Post (T : in out Test); -- Test a POST request with an invalid submitted value procedure Test_Form_Post_Validation_Error (T : in out Test); -- Test a GET+POST request with form having <h:selectOneMenu> element. procedure Test_Form_Post_Select (T : in out Test); -- Test a POST request to invoke a bean method. procedure Test_Ajax_Action (T : in out Test); -- Test a POST request to invoke a bean method. -- Verify that invalid requests raise an error. procedure Test_Ajax_Action_Error (T : in out Test); -- Test a POST/REDIRECT/GET request with a flash information passed in between. procedure Test_Flash_Object (T : in out Test); -- Test a GET+POST request with the default navigation rule based on the outcome. procedure Test_Default_Navigation_Rule (T : in out Test); -- Test a GET request with meta data and view parameters. procedure Test_View_Params (T : in out Test); -- Test a GET request with meta data and view action. procedure Test_View_Action (T : in out Test); type Form_Bean is new Util.Beans.Basic.Bean and Util.Beans.Methods.Method_Bean with record Name : Unbounded_String; Password : Unbounded_String; Email : Unbounded_String; Called : Natural := 0; Gender : Unbounded_String; Use_Flash : Boolean := False; Def_Nav : Boolean := False; Perm_Error : Boolean := False; end record; type Form_Bean_Access is access all Form_Bean'Class; -- Get the value identified by the name. overriding function Get_Value (From : in Form_Bean; Name : in String) return Util.Beans.Objects.Object; -- Set the value identified by the name. overriding procedure Set_Value (From : in out Form_Bean; Name : in String; Value : in Util.Beans.Objects.Object); -- This bean provides some methods that can be used in a Method_Expression overriding function Get_Method_Bindings (From : in Form_Bean) return Util.Beans.Methods.Method_Binding_Array_Access; -- Action to save the form procedure Save (Data : in out Form_Bean; Outcome : in out Unbounded_String); -- Create a form bean. function Create_Form_Bean return Util.Beans.Basic.Readonly_Bean_Access; -- Create a list of forms. package Form_Lists is new Util.Beans.Basic.Lists (Form_Bean); -- Create a list of forms. function Create_Form_List return Util.Beans.Basic.Readonly_Bean_Access; -- Initialize the ASF application for the unit test. procedure Initialize_Test_Application; end ASF.Applications.Tests;
Declare the Create_Form_Bean function to create a form bean
Declare the Create_Form_Bean function to create a form bean
Ada
apache-2.0
stcarrez/ada-asf,stcarrez/ada-asf,stcarrez/ada-asf
bcdca3f21ea8808e5aa24cd22887e06eb38ef8ae
src/natools-s_expressions-parsers.adb
src/natools-s_expressions-parsers.adb
------------------------------------------------------------------------------ -- Copyright (c) 2013-2014, 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. -- ------------------------------------------------------------------------------ with Natools.S_Expressions.Encodings; package body Natools.S_Expressions.Parsers is ---------------------- -- Parser Interface -- ---------------------- function Current_Event (P : in Parser) return Events.Event is begin return P.Latest; end Current_Event; function Current_Atom (P : in Parser) return Atom is begin if P.Latest /= Events.Add_Atom then raise Program_Error; end if; return P.Buffer.Data; end Current_Atom; function Current_Level (P : in Parser) return Natural is begin return P.Level; end Current_Level; procedure Query_Atom (P : in Parser; Process : not null access procedure (Data : in Atom)) is begin if P.Latest /= Events.Add_Atom then raise Program_Error; end if; P.Buffer.Query (Process); end Query_Atom; procedure Read_Atom (P : in Parser; Data : out Atom; Length : out Count) is begin if P.Latest /= Events.Add_Atom then raise Program_Error; end if; P.Buffer.Read (Data, Length); end Read_Atom; procedure Next_Event (P : in out Parser; Input : not null access Ada.Streams.Root_Stream_Type'Class) is O : Octet; Item : Ada.Streams.Stream_Element_Array (1 .. 1); Last : Ada.Streams.Stream_Element_Offset; begin P.Latest := Events.Error; loop -- Process pending events if P.Pending /= Events.End_Of_Input then P.Latest := P.Pending; P.Pending := Events.End_Of_Input; case P.Latest is when Events.Open_List => P.Level := P.Level + 1; when Events.Close_List => if P.Level > 0 then P.Level := P.Level - 1; end if; when others => null; end case; exit; end if; -- Read a single octet from source if P.Override_Pos < P.Override.Length then P.Override_Pos := P.Override_Pos + 1; O := P.Override.Element (P.Override_Pos); if P.Override_Pos >= P.Override.Length then P.Override.Hard_Reset; P.Override_Pos := 0; end if; else Input.Read (Item, Last); if Last not in Item'Range then P.Latest := Events.End_Of_Input; exit; end if; O := Item (Last); end if; -- Process octet case P.Internal.State is when Waiting => P.Buffer.Soft_Reset; case O is when 0 | Encodings.Space | Encodings.HT | Encodings.CR | Encodings.LF | Encodings.VT | Encodings.FF => null; when Encodings.List_Begin => P.Latest := Events.Open_List; P.Level := P.Level + 1; when Encodings.List_End => P.Latest := Events.Close_List; if P.Level > 0 then P.Level := P.Level - 1; end if; when Encodings.Base64_Atom_Begin => P.Internal := (State => Base64_Atom, Chunk => (Data => <>, Length => 0)); when Encodings.Base64_Expr_Begin => P.Internal := (State => Base64_Expr, Chunk => (Data => <>, Length => 0)); when Encodings.Hex_Atom_Begin => P.Internal := (State => Hex_Atom, Nibble_Buffer => 0); when Encodings.Quoted_Atom_Begin => P.Internal := (State => Quoted_Atom, Escape => (Data => <>, Length => 0)); when Encodings.Digit_0 .. Encodings.Digit_9 => P.Internal := (State => Number); Atom_Buffers.Append (P.Buffer, O); when others => P.Internal := (State => Token); Atom_Buffers.Append (P.Buffer, O); end case; when Base64_Atom | Base64_Expr => if Encodings.Is_Base64_Digit (O) then P.Internal.Chunk.Data (P.Internal.Chunk.Length) := O; P.Internal.Chunk.Length := P.Internal.Chunk.Length + 1; if P.Internal.Chunk.Length = 4 then P.Buffer.Append (Encodings.Decode_Base64 (P.Internal.Chunk.Data)); P.Internal.Chunk.Length := 0; end if; elsif (O = Encodings.Base64_Atom_End and P.Internal.State = Base64_Atom) or (O = Encodings.Base64_Expr_End and P.Internal.State = Base64_Expr) then P.Buffer.Append (Encodings.Decode_Base64 (P.Internal.Chunk.Data (0 .. P.Internal.Chunk.Length - 1))); if P.Internal.State = Base64_Atom then P.Latest := Events.Add_Atom; else P.Override.Append (P.Buffer.Data); P.Buffer.Soft_Reset; end if; P.Internal := (State => Waiting); end if; when Hex_Atom => if Encodings.Is_Hex_Digit (O) then if Encodings.Is_Hex_Digit (P.Internal.Nibble_Buffer) then P.Buffer.Append (Encodings.Decode_Hex (P.Internal.Nibble_Buffer, O)); P.Internal.Nibble_Buffer := 0; else P.Internal.Nibble_Buffer := O; end if; elsif O = Encodings.Hex_Atom_End then P.Latest := Events.Add_Atom; P.Internal := (State => Waiting); end if; when Number => case O is when Encodings.Digit_0 .. Encodings.Digit_9 => P.Buffer.Append (O); when Encodings.Verbatim_Begin => P.Internal := (State => Verbatim_Atom, Size => 0); for I in 1 .. P.Buffer.Length loop P.Internal.Size := P.Internal.Size * 10 + Count (P.Buffer.Element (I) - Encodings.Digit_0); end loop; P.Buffer.Soft_Reset; if P.Internal.Size = 0 then P.Latest := Events.Add_Atom; P.Internal := (State => Waiting); else P.Buffer.Preallocate (P.Internal.Size); end if; when 0 | Encodings.Space | Encodings.HT | Encodings.CR | Encodings.LF | Encodings.VT | Encodings.FF => P.Latest := Events.Add_Atom; P.Internal := (State => Waiting); when Encodings.List_Begin => P.Internal := (State => Waiting); P.Pending := Events.Open_List; P.Latest := Events.Add_Atom; when Encodings.List_End => P.Internal := (State => Waiting); P.Pending := Events.Close_List; P.Latest := Events.Add_Atom; when Encodings.Base64_Atom_Begin => P.Internal := (State => Base64_Atom, Chunk => (Data => <>, Length => 0)); P.Buffer.Soft_Reset; when Encodings.Base64_Expr_Begin => P.Internal := (State => Base64_Expr, Chunk => (Data => <>, Length => 0)); P.Buffer.Soft_Reset; when Encodings.Hex_Atom_Begin => P.Internal := (State => Hex_Atom, Nibble_Buffer => 0); P.Buffer.Soft_Reset; when Encodings.Quoted_Atom_Begin => P.Internal := (State => Quoted_Atom, Escape => (Data => <>, Length => 0)); P.Buffer.Soft_Reset; when others => P.Buffer.Append (O); P.Internal := (State => Token); end case; when Quoted_Atom => case P.Internal.Escape.Length is when 0 => case O is when Encodings.Escape => P.Internal.Escape.Data (0) := O; P.Internal.Escape.Length := 1; when Encodings.Quoted_Atom_End => P.Internal := (State => Waiting); P.Latest := Events.Add_Atom; when others => P.Buffer.Append (O); end case; when 1 => case O is when Character'Pos ('b') => P.Buffer.Append (8); P.Internal.Escape.Length := 0; when Character'Pos ('t') => P.Buffer.Append (9); P.Internal.Escape.Length := 0; when Character'Pos ('n') => P.Buffer.Append (10); P.Internal.Escape.Length := 0; when Character'Pos ('v') => P.Buffer.Append (11); P.Internal.Escape.Length := 0; when Character'Pos ('f') => P.Buffer.Append (12); P.Internal.Escape.Length := 0; when Character'Pos ('r') => P.Buffer.Append (13); P.Internal.Escape.Length := 0; when Character'Pos (''') | Encodings.Escape | Encodings.Quoted_Atom_End => P.Buffer.Append (O); P.Internal.Escape.Length := 0; when Encodings.Digit_0 .. Encodings.Digit_0 + 3 | Character'Pos ('x') | Encodings.CR | Encodings.LF => P.Internal.Escape.Data (1) := O; P.Internal.Escape.Length := 2; when others => P.Buffer.Append ((1 => P.Internal.Escape.Data (0), 2 => O)); P.Internal.Escape.Length := 0; end case; when 2 => if (P.Internal.Escape.Data (1) in Encodings.Digit_0 .. Encodings.Digit_0 + 3 and O in Encodings.Digit_0 .. Encodings.Digit_0 + 7) or (P.Internal.Escape.Data (1) = Character'Pos ('x') and then Encodings.Is_Hex_Digit (O)) then P.Internal.Escape.Data (2) := O; P.Internal.Escape.Length := 3; elsif P.Internal.Escape.Data (1) = Encodings.CR or P.Internal.Escape.Data (1) = Encodings.LF then P.Internal.Escape.Length := 0; if not ((O = Encodings.CR or O = Encodings.LF) and O /= P.Internal.Escape.Data (1)) then P.Buffer.Append (O); end if; else P.Buffer.Append ((P.Internal.Escape.Data (0), P.Internal.Escape.Data (1), O)); P.Internal.Escape.Length := 0; end if; when 3 => if P.Internal.Escape.Data (1) = Character'Pos ('x') then if Encodings.Is_Hex_Digit (O) then P.Buffer.Append (Encodings.Decode_Hex (P.Internal.Escape.Data (2), O)); else P.Buffer.Append ((P.Internal.Escape.Data (0), P.Internal.Escape.Data (1), P.Internal.Escape.Data (2), O)); end if; else pragma Assert (P.Internal.Escape.Data (1) in Encodings.Digit_0 .. Encodings.Digit_0 + 3); if O in Encodings.Digit_0 .. Encodings.Digit_0 + 7 then Atom_Buffers.Append (P.Buffer, (P.Internal.Escape.Data (1) - Encodings.Digit_0) * 2**6 + (P.Internal.Escape.Data (2) - Encodings.Digit_0) * 2**3 + (O - Encodings.Digit_0)); else P.Buffer.Append ((P.Internal.Escape.Data (0), P.Internal.Escape.Data (1), P.Internal.Escape.Data (2), O)); end if; end if; P.Internal.Escape.Length := 0; when 4 => raise Program_Error; end case; when Token => case O is when 0 | Encodings.Space | Encodings.HT | Encodings.CR | Encodings.LF | Encodings.VT | Encodings.FF => P.Internal := (State => Waiting); P.Latest := Events.Add_Atom; when Encodings.List_Begin => P.Internal := (State => Waiting); P.Pending := Events.Open_List; P.Latest := Events.Add_Atom; when Encodings.List_End => P.Internal := (State => Waiting); P.Pending := Events.Close_List; P.Latest := Events.Add_Atom; when others => P.Buffer.Append (O); end case; when Verbatim_Atom => P.Buffer.Append (O); pragma Assert (P.Buffer.Length <= P.Internal.Size); if P.Buffer.Length = P.Internal.Size then P.Internal := (State => Waiting); P.Latest := Events.Add_Atom; end if; end case; exit when P.Latest /= Events.Error; end loop; end Next_Event; ------------------------- -- Subparser functions -- ------------------------- function Current_Event (P : in Subparser) return Events.Event is begin if P.Terminated then return Events.End_Of_Input; else return Current_Event (P.Backend.all); end if; end Current_Event; function Current_Atom (P : in Subparser) return Atom is begin if P.Terminated then raise Constraint_Error; else return Current_Atom (P.Backend.all); end if; end Current_Atom; function Current_Level (P : in Subparser) return Natural is begin if P.Terminated then return P.Base_Level; else return Current_Level (P.Backend.all); end if; end Current_Level; procedure Query_Atom (P : in Subparser; Process : not null access procedure (Data : in Atom)) is begin if P.Terminated then raise Constraint_Error; else Query_Atom (P.Backend.all, Process); end if; end Query_Atom; procedure Read_Atom (P : in Subparser; Data : out Atom; Length : out Count) is begin if P.Terminated then raise Constraint_Error; else Read_Atom (P.Backend.all, Data, Length); end if; end Read_Atom; procedure Next (P : in out Subparser; Event : out Events.Event) is begin if P.Terminated then raise Constraint_Error; end if; if not P.Initialized then P.Base_Level := Current_Level (P.Backend.all); P.Initialized := True; end if; Next_Event (P.Backend.all, P.Input); Event := Current_Event (P.Backend.all); if Event = Events.Close_List and then Current_Level (P.Backend.all) < P.Base_Level then P.Terminated := True; Event := Events.End_Of_Input; end if; end Next; procedure Finish (P : in out Subparser) is Event : Events.Event := Current_Event (P); begin while Event /= Events.Error and Event /= Events.End_Of_Input loop Next (P, Event); end loop; end Finish; end Natools.S_Expressions.Parsers;
------------------------------------------------------------------------------ -- Copyright (c) 2013-2014, 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. -- ------------------------------------------------------------------------------ with Natools.S_Expressions.Encodings; package body Natools.S_Expressions.Parsers is ---------------------- -- Parser Interface -- ---------------------- function Current_Event (P : in Parser) return Events.Event is begin return P.Latest; end Current_Event; function Current_Atom (P : in Parser) return Atom is begin if P.Latest /= Events.Add_Atom then raise Program_Error; end if; return P.Buffer.Data; end Current_Atom; function Current_Level (P : in Parser) return Natural is begin return P.Level; end Current_Level; procedure Query_Atom (P : in Parser; Process : not null access procedure (Data : in Atom)) is begin if P.Latest /= Events.Add_Atom then raise Program_Error; end if; P.Buffer.Query (Process); end Query_Atom; procedure Read_Atom (P : in Parser; Data : out Atom; Length : out Count) is begin if P.Latest /= Events.Add_Atom then raise Program_Error; end if; P.Buffer.Read (Data, Length); end Read_Atom; procedure Next_Event (P : in out Parser; Input : not null access Ada.Streams.Root_Stream_Type'Class) is O : Octet; Item : Ada.Streams.Stream_Element_Array (1 .. 1); Last : Ada.Streams.Stream_Element_Offset; begin P.Latest := Events.Error; loop -- Process pending events if P.Pending /= Events.End_Of_Input then P.Latest := P.Pending; P.Pending := Events.End_Of_Input; case P.Latest is when Events.Open_List => P.Level := P.Level + 1; when Events.Close_List => if P.Level > 0 then P.Level := P.Level - 1; end if; when others => null; end case; exit; end if; -- Read a single octet from source if P.Override_Pos < P.Override.Length then P.Override_Pos := P.Override_Pos + 1; O := P.Override.Element (P.Override_Pos); if P.Override_Pos >= P.Override.Length then P.Override.Hard_Reset; P.Override_Pos := 0; end if; else Input.Read (Item, Last); if Last not in Item'Range then P.Latest := Events.End_Of_Input; exit; end if; O := Item (Last); end if; -- Process octet case P.Internal.State is when Waiting => P.Buffer.Soft_Reset; case O is when 0 | Encodings.Space | Encodings.HT | Encodings.CR | Encodings.LF | Encodings.VT | Encodings.FF => null; when Encodings.List_Begin => P.Latest := Events.Open_List; P.Level := P.Level + 1; when Encodings.List_End => P.Latest := Events.Close_List; if P.Level > 0 then P.Level := P.Level - 1; end if; when Encodings.Base64_Atom_Begin => P.Internal := (State => Base64_Atom, Chunk => (Data => <>, Length => 0)); when Encodings.Base64_Expr_Begin => P.Internal := (State => Base64_Expr, Chunk => (Data => <>, Length => 0)); when Encodings.Hex_Atom_Begin => P.Internal := (State => Hex_Atom, Nibble_Buffer => 0); when Encodings.Quoted_Atom_Begin => P.Internal := (State => Quoted_Atom, Escape => (Data => <>, Length => 0)); when Encodings.Digit_0 .. Encodings.Digit_9 => P.Internal := (State => Number); Atom_Buffers.Append (P.Buffer, O); when others => P.Internal := (State => Token); Atom_Buffers.Append (P.Buffer, O); end case; when Base64_Atom | Base64_Expr => if Encodings.Is_Base64_Digit (O) then P.Internal.Chunk.Data (P.Internal.Chunk.Length) := O; P.Internal.Chunk.Length := P.Internal.Chunk.Length + 1; if P.Internal.Chunk.Length = 4 then P.Buffer.Append (Encodings.Decode_Base64 (P.Internal.Chunk.Data)); P.Internal.Chunk.Length := 0; end if; elsif (O = Encodings.Base64_Atom_End and P.Internal.State = Base64_Atom) or (O = Encodings.Base64_Expr_End and P.Internal.State = Base64_Expr) then P.Buffer.Append (Encodings.Decode_Base64 (P.Internal.Chunk.Data (0 .. P.Internal.Chunk.Length - 1))); if P.Internal.State = Base64_Atom then P.Latest := Events.Add_Atom; else P.Override.Append (P.Buffer.Data); P.Buffer.Soft_Reset; end if; P.Internal := (State => Waiting); end if; when Hex_Atom => if Encodings.Is_Hex_Digit (O) then if Encodings.Is_Hex_Digit (P.Internal.Nibble_Buffer) then P.Buffer.Append (Encodings.Decode_Hex (P.Internal.Nibble_Buffer, O)); P.Internal.Nibble_Buffer := 0; else P.Internal.Nibble_Buffer := O; end if; elsif O = Encodings.Hex_Atom_End then P.Latest := Events.Add_Atom; P.Internal := (State => Waiting); end if; when Number => case O is when Encodings.Digit_0 .. Encodings.Digit_9 => P.Buffer.Append (O); when Encodings.Verbatim_Begin => P.Internal := (State => Verbatim_Atom, Size => 0); for I in 1 .. P.Buffer.Length loop P.Internal.Size := P.Internal.Size * 10 + Count (P.Buffer.Element (I) - Encodings.Digit_0); end loop; P.Buffer.Soft_Reset; if P.Internal.Size = 0 then P.Latest := Events.Add_Atom; P.Internal := (State => Waiting); else P.Buffer.Preallocate (P.Internal.Size); end if; when 0 | Encodings.Space | Encodings.HT | Encodings.CR | Encodings.LF | Encodings.VT | Encodings.FF => P.Latest := Events.Add_Atom; P.Internal := (State => Waiting); when Encodings.List_Begin => P.Internal := (State => Waiting); P.Pending := Events.Open_List; P.Latest := Events.Add_Atom; when Encodings.List_End => P.Internal := (State => Waiting); P.Pending := Events.Close_List; P.Latest := Events.Add_Atom; when Encodings.Base64_Atom_Begin => P.Internal := (State => Base64_Atom, Chunk => (Data => <>, Length => 0)); P.Buffer.Soft_Reset; when Encodings.Base64_Expr_Begin => P.Internal := (State => Base64_Expr, Chunk => (Data => <>, Length => 0)); P.Buffer.Soft_Reset; when Encodings.Hex_Atom_Begin => P.Internal := (State => Hex_Atom, Nibble_Buffer => 0); P.Buffer.Soft_Reset; when Encodings.Quoted_Atom_Begin => P.Internal := (State => Quoted_Atom, Escape => (Data => <>, Length => 0)); P.Buffer.Soft_Reset; when others => P.Buffer.Append (O); P.Internal := (State => Token); end case; when Quoted_Atom => case P.Internal.Escape.Length is when 0 => case O is when Encodings.Escape => P.Internal.Escape.Data (0) := O; P.Internal.Escape.Length := 1; when Encodings.Quoted_Atom_End => P.Internal := (State => Waiting); P.Latest := Events.Add_Atom; when others => P.Buffer.Append (O); end case; when 1 => case O is when Character'Pos ('b') => P.Buffer.Append (8); P.Internal.Escape.Length := 0; when Character'Pos ('t') => P.Buffer.Append (9); P.Internal.Escape.Length := 0; when Character'Pos ('n') => P.Buffer.Append (10); P.Internal.Escape.Length := 0; when Character'Pos ('v') => P.Buffer.Append (11); P.Internal.Escape.Length := 0; when Character'Pos ('f') => P.Buffer.Append (12); P.Internal.Escape.Length := 0; when Character'Pos ('r') => P.Buffer.Append (13); P.Internal.Escape.Length := 0; when Character'Pos (''') | Encodings.Escape | Encodings.Quoted_Atom_End => P.Buffer.Append (O); P.Internal.Escape.Length := 0; when Encodings.Digit_0 .. Encodings.Digit_0 + 3 | Character'Pos ('x') | Encodings.CR | Encodings.LF => P.Internal.Escape.Data (1) := O; P.Internal.Escape.Length := 2; when others => P.Buffer.Append (P.Internal.Escape.Data (0)); P.Override.Append (O); P.Internal.Escape.Length := 0; end case; when 2 => if (P.Internal.Escape.Data (1) in Encodings.Digit_0 .. Encodings.Digit_0 + 3 and O in Encodings.Digit_0 .. Encodings.Digit_0 + 7) or (P.Internal.Escape.Data (1) = Character'Pos ('x') and then Encodings.Is_Hex_Digit (O)) then P.Internal.Escape.Data (2) := O; P.Internal.Escape.Length := 3; elsif P.Internal.Escape.Data (1) = Encodings.CR or P.Internal.Escape.Data (1) = Encodings.LF then P.Internal.Escape.Length := 0; if not ((O = Encodings.CR or O = Encodings.LF) and O /= P.Internal.Escape.Data (1)) then P.Override.Append (O); end if; else P.Buffer.Append ((P.Internal.Escape.Data (0), P.Internal.Escape.Data (1))); P.Override.Append (O); P.Internal.Escape.Length := 0; end if; when 3 => if P.Internal.Escape.Data (1) = Character'Pos ('x') then if Encodings.Is_Hex_Digit (O) then P.Buffer.Append (Encodings.Decode_Hex (P.Internal.Escape.Data (2), O)); else P.Buffer.Append ((P.Internal.Escape.Data (0), P.Internal.Escape.Data (1), P.Internal.Escape.Data (2))); P.Override.Append (O); end if; else pragma Assert (P.Internal.Escape.Data (1) in Encodings.Digit_0 .. Encodings.Digit_0 + 3); if O in Encodings.Digit_0 .. Encodings.Digit_0 + 7 then Atom_Buffers.Append (P.Buffer, (P.Internal.Escape.Data (1) - Encodings.Digit_0) * 2**6 + (P.Internal.Escape.Data (2) - Encodings.Digit_0) * 2**3 + (O - Encodings.Digit_0)); else P.Buffer.Append ((P.Internal.Escape.Data (0), P.Internal.Escape.Data (1), P.Internal.Escape.Data (2))); P.Override.Append (O); end if; end if; P.Internal.Escape.Length := 0; when 4 => raise Program_Error; end case; when Token => case O is when 0 | Encodings.Space | Encodings.HT | Encodings.CR | Encodings.LF | Encodings.VT | Encodings.FF => P.Internal := (State => Waiting); P.Latest := Events.Add_Atom; when Encodings.List_Begin => P.Internal := (State => Waiting); P.Pending := Events.Open_List; P.Latest := Events.Add_Atom; when Encodings.List_End => P.Internal := (State => Waiting); P.Pending := Events.Close_List; P.Latest := Events.Add_Atom; when others => P.Buffer.Append (O); end case; when Verbatim_Atom => P.Buffer.Append (O); pragma Assert (P.Buffer.Length <= P.Internal.Size); if P.Buffer.Length = P.Internal.Size then P.Internal := (State => Waiting); P.Latest := Events.Add_Atom; end if; end case; exit when P.Latest /= Events.Error; end loop; end Next_Event; ------------------------- -- Subparser functions -- ------------------------- function Current_Event (P : in Subparser) return Events.Event is begin if P.Terminated then return Events.End_Of_Input; else return Current_Event (P.Backend.all); end if; end Current_Event; function Current_Atom (P : in Subparser) return Atom is begin if P.Terminated then raise Constraint_Error; else return Current_Atom (P.Backend.all); end if; end Current_Atom; function Current_Level (P : in Subparser) return Natural is begin if P.Terminated then return P.Base_Level; else return Current_Level (P.Backend.all); end if; end Current_Level; procedure Query_Atom (P : in Subparser; Process : not null access procedure (Data : in Atom)) is begin if P.Terminated then raise Constraint_Error; else Query_Atom (P.Backend.all, Process); end if; end Query_Atom; procedure Read_Atom (P : in Subparser; Data : out Atom; Length : out Count) is begin if P.Terminated then raise Constraint_Error; else Read_Atom (P.Backend.all, Data, Length); end if; end Read_Atom; procedure Next (P : in out Subparser; Event : out Events.Event) is begin if P.Terminated then raise Constraint_Error; end if; if not P.Initialized then P.Base_Level := Current_Level (P.Backend.all); P.Initialized := True; end if; Next_Event (P.Backend.all, P.Input); Event := Current_Event (P.Backend.all); if Event = Events.Close_List and then Current_Level (P.Backend.all) < P.Base_Level then P.Terminated := True; Event := Events.End_Of_Input; end if; end Next; procedure Finish (P : in out Subparser) is Event : Events.Event := Current_Event (P); begin while Event /= Events.Error and Event /= Events.End_Of_Input loop Next (P, Event); end loop; end Finish; end Natools.S_Expressions.Parsers;
fix a bug where the first character after an invalid escape sequence was not processed
s_expressions-parsers: fix a bug where the first character after an invalid escape sequence was not processed
Ada
isc
faelys/natools
03e70e662f7fc5537f9acb2293e00428807ee832
regtests/util-events-timers-tests.adb
regtests/util-events-timers-tests.adb
----------------------------------------------------------------------- -- util-events-timers-tests -- Unit tests for timers -- 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 Util.Tests; with Util.Test_Caller; package body Util.Events.Timers.Tests is use Util.Tests; use type Ada.Real_Time.Time; package Caller is new Util.Test_Caller (Test, "Events.Timers"); procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is begin Caller.Add_Test (Suite, "Test Util.Events.Channels.Post_Event", Test_Timer_Event'Access); end Add_Tests; overriding procedure Time_Handler (Sub : in out Test; Event : in out Timer_Ref'Class) is begin Sub.Count := Sub.Count + 1; end Time_Handler; procedure Test_Timer_Event (T : in out Test) is M : Timer_List; R : Timer_Ref; Start : Ada.Real_Time.Time := Ada.Real_Time.Clock; Deadline : Ada.Real_Time.Time; Now : Ada.Real_Time.Time; begin T.Assert (not R.Is_Scheduled, "Empty timer should not be scheduled"); for Retry in 1 .. 10 loop M.Set_Timer (T'Unchecked_Access, R, Start + Ada.Real_Time.Milliseconds (10)); M.Process (Deadline); Now := Ada.Real_Time.Clock; exit when Now < Deadline; end loop; T.Assert (Now < Deadline, "The timer deadline is not correct"); delay until Deadline; M.Process (Deadline); Assert_Equals (T, 1, T.Count, "The timer handler was not called"); end Test_Timer_Event; end Util.Events.Timers.Tests;
----------------------------------------------------------------------- -- util-events-timers-tests -- Unit tests for timers -- 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 Util.Tests; with Util.Test_Caller; package body Util.Events.Timers.Tests is use Util.Tests; use type Ada.Real_Time.Time; package Caller is new Util.Test_Caller (Test, "Events.Timers"); procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is begin Caller.Add_Test (Suite, "Test Util.Events.Timers.Is_Scheduled", Test_Empty_Timer'Access); Caller.Add_Test (Suite, "Test Util.Events.Timers.Process", Test_Timer_Event'Access); end Add_Tests; overriding procedure Time_Handler (Sub : in out Test; Event : in out Timer_Ref'Class) is begin Sub.Count := Sub.Count + 1; end Time_Handler; -- ----------------------- -- Test empty timers. -- ----------------------- procedure Test_Empty_Timer (T : in out Test) is M : Timer_List; R : Timer_Ref; Deadline : Ada.Real_Time.Time; begin T.Assert (not R.Is_Scheduled, "Empty timer should not be scheduled"); R.Cancel; M.Process (Deadline); T.Assert (Deadline = Ada.Real_Time.Time_Last, "The Process operation returned invalid deadline"); end Test_Empty_Timer; procedure Test_Timer_Event (T : in out Test) is M : Timer_List; R : Timer_Ref; Start : Ada.Real_Time.Time := Ada.Real_Time.Clock; Deadline : Ada.Real_Time.Time; Now : Ada.Real_Time.Time; begin for Retry in 1 .. 10 loop M.Set_Timer (T'Unchecked_Access, R, Start + Ada.Real_Time.Milliseconds (10)); M.Process (Deadline); Now := Ada.Real_Time.Clock; exit when Now < Deadline; end loop; T.Assert (Now < Deadline, "The timer deadline is not correct"); delay until Deadline; M.Process (Deadline); Assert_Equals (T, 1, T.Count, "The timer handler was not called"); end Test_Timer_Event; end Util.Events.Timers.Tests;
Implement the Test_Empty_Timer procedure and register it for execution
Implement the Test_Empty_Timer procedure and register it for execution
Ada
apache-2.0
stcarrez/ada-util,stcarrez/ada-util
41ab79484141f348c0a3f780618540c84a7e27e7
src/ado-sessions.adb
src/ado-sessions.adb
----------------------------------------------------------------------- -- ADO Sessions -- Sessions Management -- Copyright (C) 2009, 2010, 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 Util.Log; with Util.Log.Loggers; with Ada.Unchecked_Deallocation; with ADO.Drivers; with ADO.Sequences; package body ADO.Sessions is Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("ADO.Sessions"); procedure Check_Session (Database : in Session'Class; Message : in String := "") is begin if Database.Impl = null then Log.Error ("Session is closed or not initialized"); raise NOT_OPEN; end if; if Message'Length > 0 then Log.Info (Message, Database.Impl.Database.Get_Ident); end if; end Check_Session; -- --------- -- Session -- --------- -- ------------------------------ -- Get the session status. -- ------------------------------ function Get_Status (Database : in Session) return ADO.Databases.Connection_Status is begin if Database.Impl = null then return ADO.Databases.CLOSED; end if; return Database.Impl.Database.Get_Status; end Get_Status; -- ------------------------------ -- Close the session. -- ------------------------------ procedure Close (Database : in out Session) is procedure Free is new Ada.Unchecked_Deallocation (Object => Session_Record, Name => Session_Record_Access); Is_Zero : Boolean; begin Log.Info ("Closing session"); if Database.Impl /= null then ADO.Objects.Release_Proxy (Database.Impl.Proxy); Database.Impl.Database.Close; Util.Concurrent.Counters.Decrement (Database.Impl.Counter, Is_Zero); if Is_Zero then Free (Database.Impl); end if; Database.Impl := null; end if; end Close; -- ------------------------------ -- Get the database connection. -- ------------------------------ function Get_Connection (Database : in Session) return ADO.Databases.Connection'Class is begin Check_Session (Database); return Database.Impl.Database; end Get_Connection; -- ------------------------------ -- Attach the object to the session. -- ------------------------------ procedure Attach (Database : in out Session; Object : in ADO.Objects.Object_Ref'Class) is pragma Unreferenced (Object); begin Check_Session (Database); end Attach; -- ------------------------------ -- Check if the session contains the object identified by the given key. -- ------------------------------ function Contains (Database : in Session; Item : in ADO.Objects.Object_Key) return Boolean is begin Check_Session (Database); return ADO.Objects.Cache.Contains (Database.Impl.Cache, Item); end Contains; -- ------------------------------ -- Remove the object from the session cache. -- ------------------------------ procedure Evict (Database : in out Session; Item : in ADO.Objects.Object_Key) is begin Check_Session (Database); ADO.Objects.Cache.Remove (Database.Impl.Cache, Item); end Evict; -- ------------------------------ -- Create a query statement. The statement is not prepared -- ------------------------------ function Create_Statement (Database : in Session; Table : in ADO.Schemas.Class_Mapping_Access) return Query_Statement is begin Check_Session (Database); return Database.Impl.Database.Create_Statement (Table); end Create_Statement; -- ------------------------------ -- Create a query statement. The statement is not prepared -- ------------------------------ function Create_Statement (Database : in Session; Query : in String) return Query_Statement is begin Check_Session (Database); return Database.Impl.Database.Create_Statement (Query); end Create_Statement; -- ------------------------------ -- Create a query statement. The statement is not prepared -- ------------------------------ function Create_Statement (Database : in Session; Query : in ADO.Queries.Context'Class) return Query_Statement is begin Check_Session (Database); declare SQL : constant String := Query.Get_SQL (Database.Impl.Database.Get_Driver_Index); Stmt : Query_Statement := Database.Impl.Database.Create_Statement (SQL); begin Stmt.Set_Parameters (Query); return Stmt; end; end Create_Statement; -- ------------------------------ -- Create a query statement and initialize the SQL statement with the query definition. -- ------------------------------ function Create_Statement (Database : in Session; Query : in ADO.Queries.Query_Definition_Access) return Query_Statement is begin Check_Session (Database); declare Index : constant ADO.Drivers.Driver_Index := Database.Impl.Database.Get_Driver_Index; SQL : constant String := ADO.Queries.Get_SQL (Query, Index, False); begin return Database.Impl.Database.Create_Statement (SQL); end; end Create_Statement; -- ------------------------------ -- Create a query statement. The statement is not prepared -- ------------------------------ function Create_Statement (Database : in Session; Query : in ADO.SQL.Query'Class; Table : in ADO.Schemas.Class_Mapping_Access) return Query_Statement is begin Check_Session (Database); declare Stmt : Query_Statement := Database.Impl.Database.Create_Statement (Table); begin if Query in ADO.Queries.Context'Class then declare Pos : constant ADO.Drivers.Driver_Index := Database.Impl.Database.Get_Driver_Index; SQL : constant String := ADO.Queries.Context'Class (Query).Get_SQL (Pos); begin ADO.SQL.Append (Stmt.Get_Query.SQL, SQL); end; end if; Stmt.Set_Parameters (Query); return Stmt; end; end Create_Statement; -- --------- -- Master Session -- --------- -- ------------------------------ -- Start a transaction. -- ------------------------------ procedure Begin_Transaction (Database : in out Master_Session) is begin Check_Session (Database, "Begin transaction {0}"); Database.Impl.Database.Begin_Transaction; end Begin_Transaction; -- ------------------------------ -- Commit the current transaction. -- ------------------------------ procedure Commit (Database : in out Master_Session) is begin Check_Session (Database, "Commit transaction {0}"); Database.Impl.Database.Commit; end Commit; -- ------------------------------ -- Rollback the current transaction. -- ------------------------------ procedure Rollback (Database : in out Master_Session) is begin Check_Session (Database, "Rollback transaction {0}"); Database.Impl.Database.Rollback; end Rollback; -- ------------------------------ -- Allocate an identifier for the table. -- ------------------------------ procedure Allocate (Database : in out Master_Session; Id : in out ADO.Objects.Object_Record'Class) is begin Check_Session (Database); ADO.Sequences.Allocate (Database.Sequences.all, Id); end Allocate; -- ------------------------------ -- Flush the objects that were modified. -- ------------------------------ procedure Flush (Database : in out Master_Session) is begin Check_Session (Database); end Flush; overriding procedure Adjust (Object : in out Session) is begin if Object.Impl /= null then Util.Concurrent.Counters.Increment (Object.Impl.Counter); end if; end Adjust; overriding procedure Finalize (Object : in out Session) is procedure Free is new Ada.Unchecked_Deallocation (Object => Session_Record, Name => Session_Record_Access); Is_Zero : Boolean; begin if Object.Impl /= null then Util.Concurrent.Counters.Decrement (Object.Impl.Counter, Is_Zero); if Is_Zero then ADO.Objects.Release_Proxy (Object.Impl.Proxy); Object.Impl.Database.Close; Free (Object.Impl); end if; Object.Impl := null; end if; end Finalize; -- ------------------------------ -- Create a delete statement -- ------------------------------ function Create_Statement (Database : in Master_Session; Table : in ADO.Schemas.Class_Mapping_Access) return Delete_Statement is begin Check_Session (Database); return Database.Impl.Database.Create_Statement (Table); end Create_Statement; -- ------------------------------ -- Create an update statement -- ------------------------------ function Create_Statement (Database : in Master_Session; Table : in ADO.Schemas.Class_Mapping_Access) return Update_Statement is begin Check_Session (Database); return Database.Impl.Database.Create_Statement (Table); end Create_Statement; -- ------------------------------ -- Create an insert statement -- ------------------------------ function Create_Statement (Database : in Master_Session; Table : in ADO.Schemas.Class_Mapping_Access) return Insert_Statement is begin Check_Session (Database); return Database.Impl.Database.Create_Statement (Table); end Create_Statement; -- ------------------------------ -- Internal method to get the session proxy associated with the given database session. -- The session proxy is associated with some ADO objects to be able to retrieve the database -- session for the implementation of lazy loading. The session proxy is kept until the -- session exist and at least one ADO object is refering to it. -- ------------------------------ function Get_Session_Proxy (Database : in Session) return ADO.Objects.Session_Proxy_Access is use type ADO.Objects.Session_Proxy_Access; begin Check_Session (Database); if Database.Impl.Proxy = null then Database.Impl.Proxy := ADO.Objects.Create_Session_Proxy (Database.Impl); end if; return Database.Impl.Proxy; end Get_Session_Proxy; end ADO.Sessions;
----------------------------------------------------------------------- -- ADO Sessions -- Sessions Management -- Copyright (C) 2009, 2010, 2011, 2012, 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.Log; with Util.Log.Loggers; with Ada.Unchecked_Deallocation; with ADO.Drivers; with ADO.Sequences; package body ADO.Sessions is Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("ADO.Sessions"); procedure Check_Session (Database : in Session'Class; Message : in String := "") is begin if Database.Impl = null then Log.Error ("Session is closed or not initialized"); raise NOT_OPEN; end if; if Message'Length > 0 then Log.Info (Message, Database.Impl.Database.Get_Ident); end if; end Check_Session; -- --------- -- Session -- --------- -- ------------------------------ -- Get the session status. -- ------------------------------ function Get_Status (Database : in Session) return ADO.Databases.Connection_Status is begin if Database.Impl = null then return ADO.Databases.CLOSED; end if; return Database.Impl.Database.Get_Status; end Get_Status; -- ------------------------------ -- Close the session. -- ------------------------------ procedure Close (Database : in out Session) is procedure Free is new Ada.Unchecked_Deallocation (Object => Session_Record, Name => Session_Record_Access); Is_Zero : Boolean; begin Log.Info ("Closing session"); if Database.Impl /= null then ADO.Objects.Release_Proxy (Database.Impl.Proxy); Database.Impl.Database.Close; Util.Concurrent.Counters.Decrement (Database.Impl.Counter, Is_Zero); if Is_Zero then Free (Database.Impl); end if; Database.Impl := null; end if; end Close; -- ------------------------------ -- Get the database connection. -- ------------------------------ function Get_Connection (Database : in Session) return ADO.Databases.Connection'Class is begin Check_Session (Database); return Database.Impl.Database; end Get_Connection; -- ------------------------------ -- Attach the object to the session. -- ------------------------------ procedure Attach (Database : in out Session; Object : in ADO.Objects.Object_Ref'Class) is pragma Unreferenced (Object); begin Check_Session (Database); end Attach; -- ------------------------------ -- Check if the session contains the object identified by the given key. -- ------------------------------ function Contains (Database : in Session; Item : in ADO.Objects.Object_Key) return Boolean is begin Check_Session (Database); return ADO.Objects.Cache.Contains (Database.Impl.Cache, Item); end Contains; -- ------------------------------ -- Remove the object from the session cache. -- ------------------------------ procedure Evict (Database : in out Session; Item : in ADO.Objects.Object_Key) is begin Check_Session (Database); ADO.Objects.Cache.Remove (Database.Impl.Cache, Item); end Evict; -- ------------------------------ -- Create a query statement. The statement is not prepared -- ------------------------------ function Create_Statement (Database : in Session; Table : in ADO.Schemas.Class_Mapping_Access) return Query_Statement is begin Check_Session (Database); return Database.Impl.Database.Create_Statement (Table); end Create_Statement; -- ------------------------------ -- Create a query statement. The statement is not prepared -- ------------------------------ function Create_Statement (Database : in Session; Query : in String) return Query_Statement is begin Check_Session (Database); return Database.Impl.Database.Create_Statement (Query); end Create_Statement; -- ------------------------------ -- Create a query statement. The statement is not prepared -- ------------------------------ function Create_Statement (Database : in Session; Query : in ADO.Queries.Context'Class) return Query_Statement is begin Check_Session (Database); declare SQL : constant String := Query.Get_SQL (Database.Impl.Database.Get_Driver_Index); Stmt : Query_Statement := Database.Impl.Database.Create_Statement (SQL); begin Stmt.Set_Parameters (Query); return Stmt; end; end Create_Statement; -- ------------------------------ -- Create a query statement and initialize the SQL statement with the query definition. -- ------------------------------ function Create_Statement (Database : in Session; Query : in ADO.Queries.Query_Definition_Access) return Query_Statement is begin Check_Session (Database); declare Index : constant ADO.Drivers.Driver_Index := Database.Impl.Database.Get_Driver_Index; SQL : constant String := ADO.Queries.Get_SQL (Query, Index, False); begin return Database.Impl.Database.Create_Statement (SQL); end; end Create_Statement; -- ------------------------------ -- Create a query statement. The statement is not prepared -- ------------------------------ function Create_Statement (Database : in Session; Query : in ADO.SQL.Query'Class; Table : in ADO.Schemas.Class_Mapping_Access) return Query_Statement is begin Check_Session (Database); declare Stmt : Query_Statement := Database.Impl.Database.Create_Statement (Table); begin if Query in ADO.Queries.Context'Class then declare Pos : constant ADO.Drivers.Driver_Index := Database.Impl.Database.Get_Driver_Index; SQL : constant String := ADO.Queries.Context'Class (Query).Get_SQL (Pos); begin ADO.SQL.Append (Stmt.Get_Query.SQL, SQL); end; end if; Stmt.Set_Parameters (Query); return Stmt; end; end Create_Statement; -- ------------------------------ -- Load the database schema definition for the current database. -- ------------------------------ procedure Load_Schema (Database : in Session; Schema : out ADO.Schemas.Schema_Definition) is begin Check_Session (Database, "Loading schema {0}"); Database.Impl.Database.Load_Schema (Schema); end Load_Schema; -- --------- -- Master Session -- --------- -- ------------------------------ -- Start a transaction. -- ------------------------------ procedure Begin_Transaction (Database : in out Master_Session) is begin Check_Session (Database, "Begin transaction {0}"); Database.Impl.Database.Begin_Transaction; end Begin_Transaction; -- ------------------------------ -- Commit the current transaction. -- ------------------------------ procedure Commit (Database : in out Master_Session) is begin Check_Session (Database, "Commit transaction {0}"); Database.Impl.Database.Commit; end Commit; -- ------------------------------ -- Rollback the current transaction. -- ------------------------------ procedure Rollback (Database : in out Master_Session) is begin Check_Session (Database, "Rollback transaction {0}"); Database.Impl.Database.Rollback; end Rollback; -- ------------------------------ -- Allocate an identifier for the table. -- ------------------------------ procedure Allocate (Database : in out Master_Session; Id : in out ADO.Objects.Object_Record'Class) is begin Check_Session (Database); ADO.Sequences.Allocate (Database.Sequences.all, Id); end Allocate; -- ------------------------------ -- Flush the objects that were modified. -- ------------------------------ procedure Flush (Database : in out Master_Session) is begin Check_Session (Database); end Flush; overriding procedure Adjust (Object : in out Session) is begin if Object.Impl /= null then Util.Concurrent.Counters.Increment (Object.Impl.Counter); end if; end Adjust; overriding procedure Finalize (Object : in out Session) is procedure Free is new Ada.Unchecked_Deallocation (Object => Session_Record, Name => Session_Record_Access); Is_Zero : Boolean; begin if Object.Impl /= null then Util.Concurrent.Counters.Decrement (Object.Impl.Counter, Is_Zero); if Is_Zero then ADO.Objects.Release_Proxy (Object.Impl.Proxy); Object.Impl.Database.Close; Free (Object.Impl); end if; Object.Impl := null; end if; end Finalize; -- ------------------------------ -- Create a delete statement -- ------------------------------ function Create_Statement (Database : in Master_Session; Table : in ADO.Schemas.Class_Mapping_Access) return Delete_Statement is begin Check_Session (Database); return Database.Impl.Database.Create_Statement (Table); end Create_Statement; -- ------------------------------ -- Create an update statement -- ------------------------------ function Create_Statement (Database : in Master_Session; Table : in ADO.Schemas.Class_Mapping_Access) return Update_Statement is begin Check_Session (Database); return Database.Impl.Database.Create_Statement (Table); end Create_Statement; -- ------------------------------ -- Create an insert statement -- ------------------------------ function Create_Statement (Database : in Master_Session; Table : in ADO.Schemas.Class_Mapping_Access) return Insert_Statement is begin Check_Session (Database); return Database.Impl.Database.Create_Statement (Table); end Create_Statement; -- ------------------------------ -- Internal method to get the session proxy associated with the given database session. -- The session proxy is associated with some ADO objects to be able to retrieve the database -- session for the implementation of lazy loading. The session proxy is kept until the -- session exist and at least one ADO object is refering to it. -- ------------------------------ function Get_Session_Proxy (Database : in Session) return ADO.Objects.Session_Proxy_Access is use type ADO.Objects.Session_Proxy_Access; begin Check_Session (Database); if Database.Impl.Proxy = null then Database.Impl.Proxy := ADO.Objects.Create_Session_Proxy (Database.Impl); end if; return Database.Impl.Proxy; end Get_Session_Proxy; end ADO.Sessions;
Implement the Load_Schema procedure
Implement the Load_Schema procedure
Ada
apache-2.0
stcarrez/ada-ado
46d97633160cabdf3759fee5626e437533ebe92f
src/base/dates/util-dates-formats.ads
src/base/dates/util-dates-formats.ads
----------------------------------------------------------------------- -- util-dates-formats -- Date Format ala strftime -- Copyright (C) 2011, 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.Properties; -- == Localized date formatting == -- The `Util.Dates.Formats` provides a date formatting and parsing operation similar to the -- Unix `strftime`, `strptime` or the `GNAT.Calendar.Time_IO`. The localization of month -- and day labels is however handled through `Util.Properties.Bundle` (similar to -- the Java world). Unlike `strftime` and `strptime`, this allows to have a multi-threaded -- application that reports dates in several languages. The `GNAT.Calendar.Time_IO` only -- supports English and this is the reason why it is not used here. -- -- The date pattern recognizes the following formats: -- -- | Format | Description | -- | --- | ---------- | -- | %a | The abbreviated weekday name according to the current locale. -- | %A | The full weekday name according to the current locale. -- | %b | The abbreviated month name according to the current locale. -- | %h | Equivalent to %b. (SU) -- | %B | The full month name according to the current locale. -- | %c | The preferred date and time representation for the current locale. -- | %C | The century number (year/100) as a 2-digit integer. (SU) -- | %d | The day of the month as a decimal number (range 01 to 31). -- | %D | Equivalent to %m/%d/%y -- | %e | Like %d, the day of the month as a decimal number, -- | | but a leading zero is replaced by a space. (SU) -- | %F | Equivalent to %Y\-%m\-%d (the ISO 8601 date format). (C99) -- | %G | The ISO 8601 week-based year -- | %H | The hour as a decimal number using a 24-hour clock (range 00 to 23). -- | %I | The hour as a decimal number using a 12-hour clock (range 01 to 12). -- | %j | The day of the year as a decimal number (range 001 to 366). -- | %k | The hour (24 hour clock) as a decimal number (range 0 to 23); -- | %l | The hour (12 hour clock) as a decimal number (range 1 to 12); -- | %m | The month as a decimal number (range 01 to 12). -- | %M | The minute as a decimal number (range 00 to 59). -- | %n | A newline character. (SU) -- | %p | Either "AM" or "PM" -- | %P | Like %p but in lowercase: "am" or "pm" -- | %r | The time in a.m. or p.m. notation. -- | | In the POSIX locale this is equivalent to %I:%M:%S %p. (SU) -- | %R | The time in 24 hour notation (%H:%M). -- | %s | The number of seconds since the Epoch, that is, -- | | since 1970\-01\-01 00:00:00 UTC. (TZ) -- | %S | The second as a decimal number (range 00 to 60). -- | %t | A tab character. (SU) -- | %T | The time in 24 hour notation (%H:%M:%S). (SU) -- | %u | The day of the week as a decimal, range 1 to 7, -- | | Monday being 1. See also %w. (SU) -- | %U | The week number of the current year as a decimal -- | | number, range 00 to 53 -- | %V | The ISO 8601 week number -- | %w | The day of the week as a decimal, range 0 to 6, -- | | Sunday being 0. See also %u. -- | %W | The week number of the current year as a decimal number, -- | | range 00 to 53 -- | %x | The preferred date representation for the current locale -- | | without the time. -- | %X | The preferred time representation for the current locale -- | | without the date. -- | %y | The year as a decimal number without a century (range 00 to 99). -- | %Y | The year as a decimal number including the century. -- | %z | The timezone as hour offset from GMT. -- | %Z | The timezone or name or abbreviation. -- -- The following strftime flags are ignored: -- -- | Format | Description | -- | --- | ---------- | -- | %E | Modifier: use alternative format, see below. (SU) -- | %O | Modifier: use alternative format, see below. (SU) -- -- SU: Single Unix Specification -- C99: C99 standard, POSIX.1-2001 -- -- See strftime (3) and strptime (3) manual page -- -- To format and use the localize date, it is first necessary to get a bundle -- for the `dates` so that date elements are translated into the given locale. -- -- Factory : Util.Properties.Bundles.Loader; -- Bundle : Util.Properties.Bundles.Manager; -- ... -- Load_Bundle (Factory, "dates", "fr", Bundle); -- -- The date is formatted according to the pattern string described above. -- The bundle is used by the formatter to use the day and month names in the -- expected locale. -- -- Date : String := Util.Dates.Formats.Format (Pattern => Pattern, -- Date => Ada.Calendar.Clock, -- Bundle => Bundle); -- -- To parse a date according to a pattern and a localization, the same pattern string -- and bundle can be used and the `Parse` function will return the date in split format. -- -- Result : Date_Record := Util.Dates.Formats.Parse (Date => Date, -- Pattern => Pattern, -- Bundle => Bundle); -- package Util.Dates.Formats is -- Month labels. MONTH_NAME_PREFIX : constant String := "util.month"; -- Day labels. DAY_NAME_PREFIX : constant String := "util.day"; -- Short month/day suffix. SHORT_SUFFIX : constant String := ".short"; -- Long month/day suffix. LONG_SUFFIX : constant String := ".long"; -- The date time pattern name to be used for the %x representation. -- This property name is searched in the bundle to find the localized date time pattern. DATE_TIME_LOCALE_NAME : constant String := "util.datetime.pattern"; -- The default date pattern for %c (English). DATE_TIME_DEFAULT_PATTERN : constant String := "%a %b %_d %T %Y"; -- The date pattern to be used for the %x representation. -- This property name is searched in the bundle to find the localized date pattern. DATE_LOCALE_NAME : constant String := "util.date.pattern"; -- The default date pattern for %x (English). DATE_DEFAULT_PATTERN : constant String := "%m/%d/%y"; -- The time pattern to be used for the %X representation. -- This property name is searched in the bundle to find the localized time pattern. TIME_LOCALE_NAME : constant String := "util.time.pattern"; -- The default time pattern for %X (English). TIME_DEFAULT_PATTERN : constant String := "%T %Y"; AM_NAME : constant String := "util.date.am"; PM_NAME : constant String := "util.date.pm"; AM_DEFAULT : constant String := "AM"; PM_DEFAULT : constant String := "PM"; -- Format the date passed in <b>Date</b> using the date pattern specified in <b>Pattern</b>. -- The date pattern is similar to the Unix <b>strftime</b> operation. -- -- For month and day of week strings, use the resource bundle passed in <b>Bundle</b>. -- Append the formatted date in the <b>Into</b> string. procedure Format (Into : in out Ada.Strings.Unbounded.Unbounded_String; Pattern : in String; Date : in Date_Record; Bundle : in Util.Properties.Manager'Class); -- Format the date passed in <b>Date</b> using the date pattern specified in <b>Pattern</b>. -- For month and day of week strings, use the resource bundle passed in <b>Bundle</b>. -- Append the formatted date in the <b>Into</b> string. procedure Format (Into : in out Ada.Strings.Unbounded.Unbounded_String; Pattern : in String; Date : in Ada.Calendar.Time; Bundle : in Util.Properties.Manager'Class); function Format (Pattern : in String; Date : in Ada.Calendar.Time; Bundle : in Util.Properties.Manager'Class) return String; -- Append the localized month string in the <b>Into</b> string. -- The month string is found in the resource bundle under the name: -- util.month<month number>.short -- util.month<month number>.long -- If the month string is not found, the month is displayed as a number. procedure Append_Month (Into : in out Ada.Strings.Unbounded.Unbounded_String; Month : in Ada.Calendar.Month_Number; Bundle : in Util.Properties.Manager'Class; Short : in Boolean := True); -- Append the localized month string in the <b>Into</b> string. -- The month string is found in the resource bundle under the name: -- util.month<month number>.short -- util.month<month number>.long -- If the month string is not found, the month is displayed as a number. procedure Append_Day (Into : in out Ada.Strings.Unbounded.Unbounded_String; Day : in Ada.Calendar.Formatting.Day_Name; Bundle : in Util.Properties.Manager'Class; Short : in Boolean := True); -- Append a number with padding if necessary procedure Append_Number (Into : in out Ada.Strings.Unbounded.Unbounded_String; Value : in Natural; Padding : in Character; Length : in Natural := 2); -- Append the timezone offset procedure Append_Time_Offset (Into : in out Ada.Strings.Unbounded.Unbounded_String; Offset : in Ada.Calendar.Time_Zones.Time_Offset); -- Parse the date according to the pattern and the given locale bundle and -- return the data split record. -- A `Constraint_Error` exception is raised if the date string is not in the correct format. function Parse (Date : in String; Pattern : in String; Bundle : in Util.Properties.Manager'Class) return Date_Record; end Util.Dates.Formats;
----------------------------------------------------------------------- -- util-dates-formats -- Date Format ala strftime -- Copyright (C) 2011, 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.Properties; -- == Localized date formatting == -- The `Util.Dates.Formats` provides a date formatting and parsing operation similar to the -- Unix `strftime`, `strptime` or the `GNAT.Calendar.Time_IO`. The localization of month -- and day labels is however handled through `Util.Properties.Bundle` (similar to -- the Java world). Unlike `strftime` and `strptime`, this allows to have a multi-threaded -- application that reports dates in several languages. The `GNAT.Calendar.Time_IO` only -- supports English and this is the reason why it is not used here. -- -- The date pattern recognizes the following formats: -- -- | Format | Description | -- | --- | ---------- | -- | %a | The abbreviated weekday name according to the current locale. -- | %A | The full weekday name according to the current locale. -- | %b | The abbreviated month name according to the current locale. -- | %h | Equivalent to %b. (SU) -- | %B | The full month name according to the current locale. -- | %c | The preferred date and time representation for the current locale. -- | %C | The century number (year/100) as a 2-digit integer. (SU) -- | %d | The day of the month as a decimal number (range 01 to 31). -- | %D | Equivalent to %m/%d/%y -- | %e | Like %d, the day of the month as a decimal number, -- | | but a leading zero is replaced by a space. (SU) -- | %F | Equivalent to %Y\-%m\-%d (the ISO 8601 date format). (C99) -- | %G | The ISO 8601 week-based year -- | %H | The hour as a decimal number using a 24-hour clock (range 00 to 23). -- | %I | The hour as a decimal number using a 12-hour clock (range 01 to 12). -- | %j | The day of the year as a decimal number (range 001 to 366). -- | %k | The hour (24 hour clock) as a decimal number (range 0 to 23); -- | %l | The hour (12 hour clock) as a decimal number (range 1 to 12); -- | %m | The month as a decimal number (range 01 to 12). -- | %M | The minute as a decimal number (range 00 to 59). -- | %n | A newline character. (SU) -- | %p | Either "AM" or "PM" -- | %P | Like %p but in lowercase: "am" or "pm" -- | %r | The time in a.m. or p.m. notation. -- | | In the POSIX locale this is equivalent to %I:%M:%S %p. (SU) -- | %R | The time in 24 hour notation (%H:%M). -- | %s | The number of seconds since the Epoch, that is, -- | | since 1970\-01\-01 00:00:00 UTC. (TZ) -- | %S | The second as a decimal number (range 00 to 60). -- | %t | A tab character. (SU) -- | %T | The time in 24 hour notation (%H:%M:%S). (SU) -- | %u | The day of the week as a decimal, range 1 to 7, -- | | Monday being 1. See also %w. (SU) -- | %U | The week number of the current year as a decimal -- | | number, range 00 to 53 -- | %V | The ISO 8601 week number -- | %w | The day of the week as a decimal, range 0 to 6, -- | | Sunday being 0. See also %u. -- | %W | The week number of the current year as a decimal number, -- | | range 00 to 53 -- | %x | The preferred date representation for the current locale -- | | without the time. -- | %X | The preferred time representation for the current locale -- | | without the date. -- | %y | The year as a decimal number without a century (range 00 to 99). -- | %Y | The year as a decimal number including the century. -- | %z | The timezone as hour offset from GMT. -- | %Z | The timezone or name or abbreviation. -- -- The following strftime flags are ignored: -- -- | Format | Description | -- | --- | ---------- | -- | %E | Modifier: use alternative format, see below. (SU) -- | %O | Modifier: use alternative format, see below. (SU) -- -- SU: Single Unix Specification -- C99: C99 standard, POSIX.1-2001 -- -- See strftime (3) and strptime (3) manual page -- -- To format and use the localize date, it is first necessary to get a bundle -- for the `dates` so that date elements are translated into the given locale. -- -- Factory : Util.Properties.Bundles.Loader; -- Bundle : Util.Properties.Bundles.Manager; -- ... -- Load_Bundle (Factory, "dates", "fr", Bundle); -- -- The date is formatted according to the pattern string described above. -- The bundle is used by the formatter to use the day and month names in the -- expected locale. -- -- Date : String := Util.Dates.Formats.Format (Pattern => Pattern, -- Date => Ada.Calendar.Clock, -- Bundle => Bundle); -- -- To parse a date according to a pattern and a localization, the same pattern string -- and bundle can be used and the `Parse` function will return the date in split format. -- -- Result : Date_Record := Util.Dates.Formats.Parse (Date => Date, -- Pattern => Pattern, -- Bundle => Bundle); -- package Util.Dates.Formats is -- Month labels. MONTH_NAME_PREFIX : constant String := "util.month"; -- Day labels. DAY_NAME_PREFIX : constant String := "util.day"; -- Short month/day suffix. SHORT_SUFFIX : constant String := ".short"; -- Long month/day suffix. LONG_SUFFIX : constant String := ".long"; -- The date time pattern name to be used for the %x representation. -- This property name is searched in the bundle to find the localized date time pattern. DATE_TIME_LOCALE_NAME : constant String := "util.datetime.pattern"; -- The default date pattern for %c (English). DATE_TIME_DEFAULT_PATTERN : constant String := "%a %b %_d %T %Y"; -- The date pattern to be used for the %x representation. -- This property name is searched in the bundle to find the localized date pattern. DATE_LOCALE_NAME : constant String := "util.date.pattern"; -- The default date pattern for %x (English). DATE_DEFAULT_PATTERN : constant String := "%m/%d/%y"; -- The time pattern to be used for the %X representation. -- This property name is searched in the bundle to find the localized time pattern. TIME_LOCALE_NAME : constant String := "util.time.pattern"; -- The default time pattern for %X (English). TIME_DEFAULT_PATTERN : constant String := "%T %Y"; AM_NAME : constant String := "util.date.am"; PM_NAME : constant String := "util.date.pm"; AM_DEFAULT : constant String := "AM"; PM_DEFAULT : constant String := "PM"; -- Format the date passed in <b>Date</b> using the date pattern specified in <b>Pattern</b>. -- The date pattern is similar to the Unix <b>strftime</b> operation. -- -- For month and day of week strings, use the resource bundle passed in <b>Bundle</b>. -- Append the formatted date in the <b>Into</b> string. procedure Format (Into : in out Ada.Strings.Unbounded.Unbounded_String; Pattern : in String; Date : in Date_Record; Bundle : in Util.Properties.Manager'Class); -- Format the date passed in <b>Date</b> using the date pattern specified in <b>Pattern</b>. -- For month and day of week strings, use the resource bundle passed in <b>Bundle</b>. -- Append the formatted date in the <b>Into</b> string. procedure Format (Into : in out Ada.Strings.Unbounded.Unbounded_String; Pattern : in String; Date : in Ada.Calendar.Time; Bundle : in Util.Properties.Manager'Class); function Format (Pattern : in String; Date : in Ada.Calendar.Time; Bundle : in Util.Properties.Manager'Class) return String; -- Format the date passed in `Date` with a simple format pattern. -- The pattern is composed of minimalist sequences that are replaced by -- values, unrecognized characters are passed as is: -- YYYY : year MM : month dd: day HH: hour mm: minute ss: second function Simple_Format (Pattern : in String; Date : in Ada.Calendar.Time) return String; -- Append the localized month string in the <b>Into</b> string. -- The month string is found in the resource bundle under the name: -- util.month<month number>.short -- util.month<month number>.long -- If the month string is not found, the month is displayed as a number. procedure Append_Month (Into : in out Ada.Strings.Unbounded.Unbounded_String; Month : in Ada.Calendar.Month_Number; Bundle : in Util.Properties.Manager'Class; Short : in Boolean := True); -- Append the localized month string in the <b>Into</b> string. -- The month string is found in the resource bundle under the name: -- util.month<month number>.short -- util.month<month number>.long -- If the month string is not found, the month is displayed as a number. procedure Append_Day (Into : in out Ada.Strings.Unbounded.Unbounded_String; Day : in Ada.Calendar.Formatting.Day_Name; Bundle : in Util.Properties.Manager'Class; Short : in Boolean := True); -- Append a number with padding if necessary procedure Append_Number (Into : in out Ada.Strings.Unbounded.Unbounded_String; Value : in Natural; Padding : in Character; Length : in Natural := 2); -- Append the timezone offset procedure Append_Time_Offset (Into : in out Ada.Strings.Unbounded.Unbounded_String; Offset : in Ada.Calendar.Time_Zones.Time_Offset); -- Parse the date according to the pattern and the given locale bundle and -- return the data split record. -- A `Constraint_Error` exception is raised if the date string is not in the correct format. function Parse (Date : in String; Pattern : in String; Bundle : in Util.Properties.Manager'Class) return Date_Record; end Util.Dates.Formats;
Declare the Simple_Format function to provide a simple date format à la SimpleDateFormat in Java
Declare the Simple_Format function to provide a simple date format à la SimpleDateFormat in Java
Ada
apache-2.0
stcarrez/ada-util,stcarrez/ada-util
e97875e7dd5e8918b5d4be447f438dea7817c6a1
src/gen.ads
src/gen.ads
----------------------------------------------------------------------- -- Gen -- Code Generator -- Copyright (C) 2009, 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. ----------------------------------------------------------------------- package Gen is -- Library SVN identification SVN_URL : constant String := "https://ada-gen.googlecode.com/svn/trunk"; -- Revision used (must run 'make version' to update) SVN_REV : constant Positive := 313; end Gen;
----------------------------------------------------------------------- -- Gen -- Code Generator -- Copyright (C) 2009, 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. ----------------------------------------------------------------------- package Gen is -- Library SVN identification SVN_URL : constant String := "https://ada-gen.googlecode.com/svn/trunk"; -- Revision used (must run 'make version' to update) SVN_REV : constant Positive := 339; end Gen;
Update the revision
Update the revision
Ada
apache-2.0
stcarrez/dynamo,stcarrez/dynamo,stcarrez/dynamo
67c08ee6bd2131fd4b362ebca3ecf7373db886fb
src/ado-drivers-dialects.ads
src/ado-drivers-dialects.ads
----------------------------------------------------------------------- -- ADO Dialects -- Driver support for basic SQL Generation -- Copyright (C) 2010, 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. ----------------------------------------------------------------------- -- The <b>ADO.Drivers.Dialects</b> package controls the database specific SQL dialects. package ADO.Drivers.Dialects is -- -------------------- -- SQL Dialect -- -------------------- -- The <b>Dialect</b> defines the specific characteristics that must be -- taken into account when building the SQL statement. This includes: -- <ul> -- <li>The definition of reserved keywords that must be escaped</li> -- <li>How to escape those keywords</li> -- <li>How to escape special characters</li> -- </ul> type Dialect is abstract tagged private; type Dialect_Access is access all Dialect'Class; -- Check if the string is a reserved keyword. function Is_Reserved (D : Dialect; Name : String) return Boolean is abstract; -- Get the quote character to escape an identifier. function Get_Identifier_Quote (D : in Dialect) return Character; -- 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); -- 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); -- Append the boolean item in the buffer. procedure Escape_Sql (D : in Dialect; Buffer : in out Unbounded_String; Item : in Boolean); private type Dialect is abstract tagged null record; end ADO.Drivers.Dialects;
----------------------------------------------------------------------- -- ADO Dialects -- Driver support for basic SQL Generation -- Copyright (C) 2010, 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. ----------------------------------------------------------------------- -- The <b>ADO.Drivers.Dialects</b> package controls the database specific SQL dialects. package ADO.Drivers.Dialects is -- -------------------- -- SQL Dialect -- -------------------- -- The <b>Dialect</b> defines the specific characteristics that must be -- taken into account when building the SQL statement. This includes: -- <ul> -- <li>The definition of reserved keywords that must be escaped</li> -- <li>How to escape those keywords</li> -- <li>How to escape special characters</li> -- </ul> type Dialect is abstract tagged private; type Dialect_Access is access all Dialect'Class; -- Check if the string is a reserved keyword. function Is_Reserved (D : Dialect; Name : String) return Boolean is abstract; -- Get the quote character to escape an identifier. function Get_Identifier_Quote (D : in Dialect) return Character is abstract; -- 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); -- 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); -- Append the boolean item in the buffer. procedure Escape_Sql (D : in Dialect; Buffer : in out Unbounded_String; Item : in Boolean); private type Dialect is abstract tagged null record; end ADO.Drivers.Dialects;
Change Get_Identifier_Quote to be an abstract function
Change Get_Identifier_Quote to be an abstract function
Ada
apache-2.0
stcarrez/ada-ado
928c36bcb13de8c5ecc1e9249b679822bcaa4ec0
src/gen-commands-distrib.adb
src/gen-commands-distrib.adb
----------------------------------------------------------------------- -- gen-commands-distrib -- Distrib command for dynamo -- Copyright (C) 2012, 2013, 2014, 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.Text_IO; package body Gen.Commands.Distrib is -- ------------------------------ -- Execute the command with the arguments. -- ------------------------------ overriding procedure Execute (Cmd : in out Command; Name : in String; Args : in Argument_List'Class; Generator : in out Gen.Generator.Handler) is pragma Unreferenced (Cmd, Name); begin if Args.Get_Count = 0 or Args.Get_Count > 2 then Generator.Error ("Missing target directory"); return; end if; Generator.Read_Project ("dynamo.xml", True); -- Setup the target directory where the distribution is created. Generator.Set_Result_Directory (Args.Get_Argument (1)); -- Read the package description. if Args.Get_Count = 2 then Gen.Generator.Read_Package (Generator, Args.Get_Argument (2)); else Gen.Generator.Read_Package (Generator, "package.xml"); end if; -- Run the generation. Gen.Generator.Prepare (Generator); Gen.Generator.Generate_All (Generator); Gen.Generator.Finish (Generator); end Execute; -- ------------------------------ -- Write the help associated with the command. -- ------------------------------ overriding procedure Help (Cmd : in out Command; Generator : in out Gen.Generator.Handler) is pragma Unreferenced (Cmd, Generator); use Ada.Text_IO; begin Put_Line ("dist: Build the distribution files to prepare the server installation"); Put_Line ("Usage: dist target-dir [package.xml]"); New_Line; Put_Line (" The dist command reads the XML package description to build the" & " distribution tree."); Put_Line (" This command is intended to be used after the project is built. It prepares"); Put_Line (" the files for their installation on the target server in a " & "production environment."); Put_Line (" The package.xml describes what files are necessary on the server."); Put_Line (" It allows to make transformations such as compressing Javascript, CSS and " & "images"); end Help; end Gen.Commands.Distrib;
----------------------------------------------------------------------- -- gen-commands-distrib -- Distrib command for dynamo -- Copyright (C) 2012, 2013, 2014, 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.Text_IO; package body Gen.Commands.Distrib is -- ------------------------------ -- Execute the command with the arguments. -- ------------------------------ overriding procedure Execute (Cmd : in out Command; Name : in String; Args : in Argument_List'Class; Generator : in out Gen.Generator.Handler) is pragma Unreferenced (Cmd, Name); begin if Args.Get_Count = 0 or Args.Get_Count > 2 then Generator.Error ("Missing target directory"); return; end if; Generator.Read_Project ("dynamo.xml", True); -- Setup the target directory where the distribution is created. Generator.Set_Result_Directory (Args.Get_Argument (1)); -- Read the package description. if Args.Get_Count = 2 then Gen.Generator.Read_Package (Generator, Args.Get_Argument (2)); else Gen.Generator.Read_Package (Generator, "package.xml"); end if; -- Run the generation. Gen.Generator.Prepare (Generator); Gen.Generator.Generate_All (Generator); Gen.Generator.Finish (Generator); end Execute; -- ------------------------------ -- Write the help associated with the command. -- ------------------------------ overriding procedure Help (Cmd : in out Command; Name : in String; Generator : in out Gen.Generator.Handler) is pragma Unreferenced (Cmd, Name, Generator); use Ada.Text_IO; begin Put_Line ("dist: Build the distribution files to prepare the server installation"); Put_Line ("Usage: dist target-dir [package.xml]"); New_Line; Put_Line (" The dist command reads the XML package description to build the" & " distribution tree."); Put_Line (" This command is intended to be used after the project is built. It prepares"); Put_Line (" the files for their installation on the target server in a " & "production environment."); Put_Line (" The package.xml describes what files are necessary on the server."); Put_Line (" It allows to make transformations such as compressing Javascript, CSS and " & "images"); end Help; end Gen.Commands.Distrib;
Add Name parameter to the Help procedure
Add Name parameter to the Help procedure
Ada
apache-2.0
stcarrez/dynamo,stcarrez/dynamo,stcarrez/dynamo
dafeb816bb6e66826f0f0b21203a53df4fb942db
src/orka/interface/orka-behaviors.ads
src/orka/interface/orka-behaviors.ads
-- 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 Orka.Transforms.Singles.Matrices; package Orka.Behaviors is pragma Preelaborate; package Transforms renames Orka.Transforms.Singles.Matrices; type Visibility is (Invisible, Visible); type Behavior is limited interface; type Behavior_Ptr is not null access Behavior'Class; function Position (Object : Behavior) return Transforms.Vector4 is abstract; procedure Fixed_Update (Object : in out Behavior; Delta_Time : Duration) is null; -- Called zero to multiple times per frame and before Update -- -- Fixed_Update can be used to perform physics or other computations -- that require a stable Delta_Time that does not depend on the frame -- rate. If the game needs to catch up then Fixed_Update is called -- multiple times. If the game renders at a very high frame rate then -- Fixed_Update will not be called at all. procedure Update (Object : in out Behavior; Delta_Time : Duration) is null; -- Called once per frame and after any calls to Fixed_Update procedure After_Update (Object : in out Behavior; Delta_Time : Duration; View_Position : Transforms.Vector4) is null; -- Called once per frame and after Update procedure Visibility_Changed (Object : in out Behavior; State : Visibility) is null; procedure Render (Object : in out Behavior) is null; procedure After_Render (Object : in out Behavior) is null; type Behavior_Array is array (Positive range <>) of Behaviors.Behavior_Ptr; type Behavior_Array_Access is access Behavior_Array; Null_Behavior : constant Behavior_Ptr; Empty_Behavior_Array : constant Behavior_Array_Access; private type Origin_Behavior is new Behavior with null record; overriding function Position (Object : Origin_Behavior) return Transforms.Vector4 is ((0.0, 0.0, 0.0, 1.0)); Null_Behavior : constant Behavior_Ptr := new Origin_Behavior; Empty_Behavior_Array : constant Behavior_Array_Access := new Behavior_Array (1 .. 0); end Orka.Behaviors;
-- 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 Orka.Transforms.Singles.Matrices; package Orka.Behaviors is pragma Preelaborate; package Transforms renames Orka.Transforms.Singles.Matrices; type Visibility is (Invisible, Visible); type Behavior is limited interface; type Behavior_Ptr is not null access Behavior'Class; function Position (Object : Behavior) return Transforms.Vector4 is abstract; procedure Fixed_Update (Object : in out Behavior; Delta_Time : Duration) is null; -- Called zero to multiple times per frame and before Update -- -- Fixed_Update can be used to perform physics or other computations -- that require a stable Delta_Time that does not depend on the frame -- rate. If the game needs to catch up then Fixed_Update is called -- multiple times. If the game renders at a very high frame rate then -- Fixed_Update will not be called at all. procedure Update (Object : in out Behavior; Delta_Time : Duration) is null; -- Called once per frame and after any calls to Fixed_Update procedure After_Update (Object : in out Behavior; Delta_Time : Duration; View_Position : Transforms.Vector4) is null; -- Called once per frame and after Update procedure Visibility_Changed (Object : in out Behavior; State : Visibility) is null; procedure Render (Object : in out Behavior) is null; procedure After_Render (Object : in out Behavior) is null; type Behavior_Array is array (Positive range <>) of Behaviors.Behavior_Ptr; type Behavior_Array_Access is access Behavior_Array; Null_Behavior : constant Behavior_Ptr; function Empty_Behavior_Array return Behavior_Array_Access; private type Origin_Behavior is new Behavior with null record; overriding function Position (Object : Origin_Behavior) return Transforms.Vector4 is ((0.0, 0.0, 0.0, 1.0)); Null_Behavior : constant Behavior_Ptr := new Origin_Behavior; function Empty_Behavior_Array return Behavior_Array_Access is (new Behavior_Array'(1 .. 0 => Null_Behavior)); end Orka.Behaviors;
Fix compile error with GNAT CE 2018
Fix compile error with GNAT CE 2018 Signed-off-by: onox <[email protected]>
Ada
apache-2.0
onox/orka
294cd74fd0135188f4960ac49315fda94f1d244f
src/sys/os-unix/util-processes-os.adb
src/sys/os-unix/util-processes-os.adb
----------------------------------------------------------------------- -- util-processes-os -- System specific and low level operations -- Copyright (C) 2011, 2012, 2017, 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.Directories; with Ada.Unchecked_Deallocation; package body Util.Processes.Os is use Util.Systems.Os; use type Interfaces.C.size_t; use type Util.Systems.Types.File_Type; use type Ada.Directories.File_Kind; type Pipe_Type is array (0 .. 1) of File_Type; procedure Close (Pipes : in out Pipe_Type); -- ------------------------------ -- Create the output stream to read/write on the process input/output. -- Setup the file to be closed on exec. -- ------------------------------ function Create_Stream (File : in File_Type) return Util.Streams.Raw.Raw_Stream_Access is Stream : constant Util.Streams.Raw.Raw_Stream_Access := new Util.Streams.Raw.Raw_Stream; Status : constant Integer := Sys_Fcntl (File, F_SETFL, FD_CLOEXEC); pragma Unreferenced (Status); begin Stream.Initialize (File); return Stream; end Create_Stream; -- ------------------------------ -- Wait for the process to exit. -- ------------------------------ overriding procedure Wait (Sys : in out System_Process; Proc : in out Process'Class; Timeout : in Duration) is pragma Unreferenced (Sys, Timeout); use type Util.Streams.Output_Stream_Access; Result : Integer; Wpid : Integer; begin -- Close the input stream pipe if there is one. if Proc.Input /= null then Util.Streams.Raw.Raw_Stream'Class (Proc.Input.all).Close; end if; Wpid := Sys_Waitpid (Integer (Proc.Pid), Result'Address, 0); if Wpid = Integer (Proc.Pid) then Proc.Exit_Value := Result / 256; if Result mod 256 /= 0 then Proc.Exit_Value := (Result mod 256) * 1000; end if; end if; end Wait; -- ------------------------------ -- Terminate the process by sending a signal on Unix and exiting the process on Windows. -- This operation is not portable and has a different behavior between Unix and Windows. -- Its intent is to stop the process. -- ------------------------------ overriding procedure Stop (Sys : in out System_Process; Proc : in out Process'Class; Signal : in Positive := 15) is pragma Unreferenced (Sys); Result : Integer; pragma Unreferenced (Result); begin Result := Sys_Kill (Integer (Proc.Pid), Integer (Signal)); end Stop; -- ------------------------------ -- Close both ends of the pipe (used to cleanup in case or error). -- ------------------------------ procedure Close (Pipes : in out Pipe_Type) is Result : Integer; pragma Unreferenced (Result); begin if Pipes (0) /= NO_FILE then Result := Sys_Close (Pipes (0)); Pipes (0) := NO_FILE; end if; if Pipes (1) /= NO_FILE then Result := Sys_Close (Pipes (1)); Pipes (1) := NO_FILE; end if; end Close; procedure Prepare_Working_Directory (Sys : in out System_Process; Proc : in out Process'Class) is Dir : constant String := Ada.Strings.Unbounded.To_String (Proc.Dir); begin Interfaces.C.Strings.Free (Sys.Dir); if Dir'Length > 0 then if not Ada.Directories.Exists (Dir) or else Ada.Directories.Kind (Dir) /= Ada.Directories.Directory then raise Ada.Directories.Name_Error with "Invalid directory: " & Dir; end if; Sys.Dir := Interfaces.C.Strings.New_String (Dir); end if; end Prepare_Working_Directory; -- ------------------------------ -- Spawn a new process. -- ------------------------------ overriding procedure Spawn (Sys : in out System_Process; Proc : in out Process'Class; Mode : in Pipe_Mode := NONE) is use Interfaces.C.Strings; use type Interfaces.C.int; procedure Cleanup; -- Suppress all checks to make sure the child process will not raise any exception. pragma Suppress (All_Checks); Result : Integer; Stdin_Pipes : aliased Pipe_Type := (others => NO_FILE); Stdout_Pipes : aliased Pipe_Type := (others => NO_FILE); Stderr_Pipes : aliased Pipe_Type := (others => NO_FILE); procedure Cleanup is begin Close (Stdin_Pipes); Close (Stdout_Pipes); Close (Stderr_Pipes); end Cleanup; begin Sys.Prepare_Working_Directory (Proc); -- Since checks are disabled, verify by hand that the argv table is correct. if Sys.Argv = null or else Sys.Argc < 1 or else Sys.Argv (0) = Null_Ptr then raise Program_Error with "Invalid process argument list"; end if; -- Setup the pipes. if Mode = READ or Mode = READ_WRITE or Mode = READ_ALL then if Sys_Pipe (Stdout_Pipes'Address) /= 0 then raise Process_Error with "Cannot create stdout pipe"; end if; end if; if Mode = WRITE or Mode = READ_WRITE or Mode = READ_WRITE_ALL then if Sys_Pipe (Stdin_Pipes'Address) /= 0 then Cleanup; raise Process_Error with "Cannot create stdin pipe"; end if; end if; if Mode = READ_ERROR then if Sys_Pipe (Stderr_Pipes'Address) /= 0 then Cleanup; raise Process_Error with "Cannot create stderr pipe"; end if; end if; -- Create the new process by using vfork instead of fork. The parent process is blocked -- until the child executes the exec or exits. The child process uses the same stack -- as the parent. Proc.Pid := Sys_VFork; if Proc.Pid = 0 then -- Do not use any Ada type while in the child process. if Proc.To_Close /= null then for Fd of Proc.To_Close.all loop Result := Sys_Close (Fd); end loop; end if; if Mode = READ_ALL or Mode = READ_WRITE_ALL then Result := Sys_Dup2 (Stdout_Pipes (1), STDERR_FILENO); end if; if Stderr_Pipes (1) /= NO_FILE then if Stderr_Pipes (1) /= STDERR_FILENO then Result := Sys_Dup2 (Stderr_Pipes (1), STDERR_FILENO); Result := Sys_Close (Stderr_Pipes (1)); end if; Result := Sys_Close (Stderr_Pipes (0)); elsif Sys.Err_File /= Null_Ptr then -- Redirect the process error to a file. declare Fd : File_Type; begin if Sys.Err_Append then Fd := Sys_Open (Sys.Err_File, O_CREAT + O_WRONLY + O_APPEND, 8#644#); else Fd := Sys_Open (Sys.Err_File, O_CREAT + O_WRONLY + O_TRUNC, 8#644#); end if; if Fd < 0 then Sys_Exit (254); end if; Result := Sys_Dup2 (Fd, STDOUT_FILENO); Result := Sys_Close (Fd); end; end if; if Stdout_Pipes (1) /= NO_FILE then if Stdout_Pipes (1) /= STDOUT_FILENO then Result := Sys_Dup2 (Stdout_Pipes (1), STDOUT_FILENO); Result := Sys_Close (Stdout_Pipes (1)); end if; Result := Sys_Close (Stdout_Pipes (0)); elsif Sys.Out_File /= Null_Ptr then -- Redirect the process output to a file. declare Fd : File_Type; begin if Sys.Out_Append then Fd := Sys_Open (Sys.Out_File, O_CREAT + O_WRONLY + O_APPEND, 8#644#); else Fd := Sys_Open (Sys.Out_File, O_CREAT + O_WRONLY + O_TRUNC, 8#644#); end if; if Fd < 0 then Sys_Exit (254); end if; Result := Sys_Dup2 (Fd, STDOUT_FILENO); Result := Sys_Close (Fd); end; end if; if Stdin_Pipes (0) /= NO_FILE then if Stdin_Pipes (0) /= STDIN_FILENO then Result := Sys_Dup2 (Stdin_Pipes (0), STDIN_FILENO); Result := Sys_Close (Stdin_Pipes (0)); end if; Result := Sys_Close (Stdin_Pipes (1)); elsif Sys.In_File /= Null_Ptr then -- Redirect the process input from a file. declare Fd : File_Type; begin Fd := Sys_Open (Sys.In_File, O_RDONLY, 8#644#); if Fd < 0 then Sys_Exit (254); end if; Result := Sys_Dup2 (Fd, STDIN_FILENO); Result := Sys_Close (Fd); end; end if; if Sys.Dir /= Null_Ptr then Result := Sys_Chdir (Sys.Dir); if Result < 0 then Sys_Exit (253); end if; end if; Result := Sys_Execvp (Sys.Argv (0), Sys.Argv.all); Sys_Exit (255); end if; -- Process creation failed, cleanup and raise an exception. if Proc.Pid < 0 then Cleanup; raise Process_Error with "Cannot create process"; end if; if Stdin_Pipes (1) /= NO_FILE then Result := Sys_Close (Stdin_Pipes (0)); Proc.Input := Create_Stream (Stdin_Pipes (1)).all'Access; end if; if Stdout_Pipes (0) /= NO_FILE then Result := Sys_Close (Stdout_Pipes (1)); Proc.Output := Create_Stream (Stdout_Pipes (0)).all'Access; end if; if Stderr_Pipes (0) /= NO_FILE then Result := Sys_Close (Stderr_Pipes (1)); Proc.Error := Create_Stream (Stderr_Pipes (0)).all'Access; end if; end Spawn; procedure Free is new Ada.Unchecked_Deallocation (Name => Ptr_Ptr_Array, Object => Ptr_Array); -- ------------------------------ -- Append the argument to the process argument list. -- ------------------------------ overriding procedure Append_Argument (Sys : in out System_Process; Arg : in String) is begin if Sys.Argv = null then Sys.Argv := new Ptr_Array (0 .. 10); elsif Sys.Argc = Sys.Argv'Last - 1 then declare N : constant Ptr_Ptr_Array := new Ptr_Array (0 .. Sys.Argc + 32); begin N (0 .. Sys.Argc) := Sys.Argv (0 .. Sys.Argc); Free (Sys.Argv); Sys.Argv := N; end; end if; Sys.Argv (Sys.Argc) := Interfaces.C.Strings.New_String (Arg); Sys.Argc := Sys.Argc + 1; Sys.Argv (Sys.Argc) := Interfaces.C.Strings.Null_Ptr; end Append_Argument; -- ------------------------------ -- Set the process input, output and error streams to redirect and use specified files. -- ------------------------------ overriding procedure Set_Streams (Sys : in out System_Process; Input : in String; Output : in String; Error : in String; Append_Output : in Boolean; Append_Error : in Boolean; To_Close : in File_Type_Array_Access) is begin if Input'Length > 0 then Sys.In_File := Interfaces.C.Strings.New_String (Input); end if; if Output'Length > 0 then Sys.Out_File := Interfaces.C.Strings.New_String (Output); Sys.Out_Append := Append_Output; end if; if Error'Length > 0 then Sys.Err_File := Interfaces.C.Strings.New_String (Error); Sys.Err_Append := Append_Error; end if; Sys.To_Close := To_Close; end Set_Streams; -- ------------------------------ -- Deletes the storage held by the system process. -- ------------------------------ overriding procedure Finalize (Sys : in out System_Process) is begin if Sys.Argv /= null then for I in Sys.Argv'Range loop Interfaces.C.Strings.Free (Sys.Argv (I)); end loop; Free (Sys.Argv); end if; Interfaces.C.Strings.Free (Sys.In_File); Interfaces.C.Strings.Free (Sys.Out_File); Interfaces.C.Strings.Free (Sys.Err_File); Interfaces.C.Strings.Free (Sys.Dir); end Finalize; end Util.Processes.Os;
----------------------------------------------------------------------- -- util-processes-os -- System specific and low level operations -- Copyright (C) 2011, 2012, 2017, 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.Directories; with Ada.Unchecked_Deallocation; package body Util.Processes.Os is use Util.Systems.Os; use type Interfaces.C.size_t; use type Util.Systems.Types.File_Type; use type Ada.Directories.File_Kind; type Pipe_Type is array (0 .. 1) of File_Type; procedure Close (Pipes : in out Pipe_Type); -- ------------------------------ -- Create the output stream to read/write on the process input/output. -- Setup the file to be closed on exec. -- ------------------------------ function Create_Stream (File : in File_Type) return Util.Streams.Raw.Raw_Stream_Access is Stream : constant Util.Streams.Raw.Raw_Stream_Access := new Util.Streams.Raw.Raw_Stream; Status : constant Integer := Sys_Fcntl (File, F_SETFL, FD_CLOEXEC); pragma Unreferenced (Status); begin Stream.Initialize (File); return Stream; end Create_Stream; -- ------------------------------ -- Wait for the process to exit. -- ------------------------------ overriding procedure Wait (Sys : in out System_Process; Proc : in out Process'Class; Timeout : in Duration) is pragma Unreferenced (Sys, Timeout); use type Util.Streams.Output_Stream_Access; Result : Integer; Wpid : Integer; begin -- Close the input stream pipe if there is one. if Proc.Input /= null then Util.Streams.Raw.Raw_Stream'Class (Proc.Input.all).Close; end if; Wpid := Sys_Waitpid (Integer (Proc.Pid), Result'Address, 0); if Wpid = Integer (Proc.Pid) then Proc.Exit_Value := Result / 256; if Result mod 256 /= 0 then Proc.Exit_Value := (Result mod 256) * 1000; end if; end if; end Wait; -- ------------------------------ -- Terminate the process by sending a signal on Unix and exiting the process on Windows. -- This operation is not portable and has a different behavior between Unix and Windows. -- Its intent is to stop the process. -- ------------------------------ overriding procedure Stop (Sys : in out System_Process; Proc : in out Process'Class; Signal : in Positive := 15) is pragma Unreferenced (Sys); Result : Integer; pragma Unreferenced (Result); begin Result := Sys_Kill (Integer (Proc.Pid), Integer (Signal)); end Stop; -- ------------------------------ -- Close both ends of the pipe (used to cleanup in case or error). -- ------------------------------ procedure Close (Pipes : in out Pipe_Type) is Result : Integer; pragma Unreferenced (Result); begin if Pipes (0) /= NO_FILE then Result := Sys_Close (Pipes (0)); Pipes (0) := NO_FILE; end if; if Pipes (1) /= NO_FILE then Result := Sys_Close (Pipes (1)); Pipes (1) := NO_FILE; end if; end Close; procedure Prepare_Working_Directory (Sys : in out System_Process; Proc : in out Process'Class) is Dir : constant String := Ada.Strings.Unbounded.To_String (Proc.Dir); begin Interfaces.C.Strings.Free (Sys.Dir); if Dir'Length > 0 then if not Ada.Directories.Exists (Dir) or else Ada.Directories.Kind (Dir) /= Ada.Directories.Directory then raise Ada.Directories.Name_Error with "Invalid directory: " & Dir; end if; Sys.Dir := Interfaces.C.Strings.New_String (Dir); end if; end Prepare_Working_Directory; -- ------------------------------ -- Spawn a new process. -- ------------------------------ overriding procedure Spawn (Sys : in out System_Process; Proc : in out Process'Class; Mode : in Pipe_Mode := NONE) is use Interfaces.C.Strings; use type Interfaces.C.int; procedure Cleanup; -- Suppress all checks to make sure the child process will not raise any exception. pragma Suppress (All_Checks); Result : Integer; Stdin_Pipes : aliased Pipe_Type := (others => NO_FILE); Stdout_Pipes : aliased Pipe_Type := (others => NO_FILE); Stderr_Pipes : aliased Pipe_Type := (others => NO_FILE); procedure Cleanup is begin Close (Stdin_Pipes); Close (Stdout_Pipes); Close (Stderr_Pipes); end Cleanup; begin Sys.Prepare_Working_Directory (Proc); -- Since checks are disabled, verify by hand that the argv table is correct. if Sys.Argv = null or else Sys.Argc < 1 or else Sys.Argv (0) = Null_Ptr then raise Program_Error with "Invalid process argument list"; end if; -- Setup the pipes. if Mode = WRITE or Mode = READ_WRITE or Mode = READ_WRITE_ALL then if Sys_Pipe (Stdin_Pipes'Address) /= 0 then Cleanup; raise Process_Error with "Cannot create stdin pipe"; end if; end if; if Mode = READ or Mode = READ_WRITE or Mode = READ_ALL then if Sys_Pipe (Stdout_Pipes'Address) /= 0 then Cleanup; raise Process_Error with "Cannot create stdout pipe"; end if; end if; if Mode = READ_ERROR then if Sys_Pipe (Stderr_Pipes'Address) /= 0 then Cleanup; raise Process_Error with "Cannot create stderr pipe"; end if; end if; -- Create the new process by using vfork instead of fork. The parent process is blocked -- until the child executes the exec or exits. The child process uses the same stack -- as the parent. Proc.Pid := Sys_VFork; if Proc.Pid = 0 then -- Do not use any Ada type while in the child process. if Proc.To_Close /= null then for Fd of Proc.To_Close.all loop Result := Sys_Close (Fd); end loop; end if; -- Handle stdin/stdout/stderr pipe redirections unless they are file-redirected. if Sys.Err_File = Null_Ptr and Stdout_Pipes (1) /= NO_FILE then Result := Sys_Dup2 (Stdout_Pipes (1), STDERR_FILENO); end if; -- Redirect stdin to the pipe unless we use file redirection. if Sys.In_File = Null_Ptr and Stdin_Pipes (0) /= NO_FILE then if Stdin_Pipes (0) /= STDIN_FILENO then Result := Sys_Dup2 (Stdin_Pipes (0), STDIN_FILENO); end if; end if; if Stdin_Pipes (0) /= NO_FILE and Stdin_Pipes (0) /= STDIN_FILENO then Result := Sys_Close (Stdin_Pipes (0)); end if; if Stdin_Pipes (1) /= NO_FILE then Result := Sys_Close (Stdin_Pipes (1)); end if; -- Redirect stdout to the pipe unless we use file redirection. if Sys.Out_File = Null_Ptr and Stdout_Pipes (1) /= NO_FILE then if Stdout_Pipes (1) /= STDOUT_FILENO then Result := Sys_Dup2 (Stdout_Pipes (1), STDOUT_FILENO); end if; end if; if Stdout_Pipes (1) /= NO_FILE and Stdout_Pipes (1) /= STDOUT_FILENO then Result := Sys_Close (Stdout_Pipes (1)); end if; if Stdout_Pipes (0) /= NO_FILE then Result := Sys_Close (Stdout_Pipes (0)); end if; if Sys.Err_File = Null_Ptr and Stderr_Pipes (1) /= NO_FILE then if Stderr_Pipes (1) /= STDERR_FILENO then Result := Sys_Dup2 (Stderr_Pipes (1), STDERR_FILENO); Result := Sys_Close (Stderr_Pipes (1)); end if; Result := Sys_Close (Stderr_Pipes (0)); end if; if Sys.In_File /= Null_Ptr then -- Redirect the process input from a file. declare Fd : File_Type; begin Fd := Sys_Open (Sys.In_File, O_RDONLY, 8#644#); if Fd < 0 then Sys_Exit (254); end if; if Fd /= STDIN_FILENO then Result := Sys_Dup2 (Fd, STDIN_FILENO); Result := Sys_Close (Fd); end if; end; end if; if Sys.Out_File /= Null_Ptr then -- Redirect the process output to a file. declare Fd : File_Type; begin if Sys.Out_Append then Fd := Sys_Open (Sys.Out_File, O_CREAT + O_WRONLY + O_APPEND, 8#644#); else Fd := Sys_Open (Sys.Out_File, O_CREAT + O_WRONLY + O_TRUNC, 8#644#); end if; if Fd < 0 then Sys_Exit (254); end if; if Fd /= STDOUT_FILENO then Result := Sys_Dup2 (Fd, STDOUT_FILENO); Result := Sys_Close (Fd); end if; end; end if; if Sys.Err_File /= Null_Ptr then -- Redirect the process error to a file. declare Fd : File_Type; begin if Sys.Err_Append then Fd := Sys_Open (Sys.Err_File, O_CREAT + O_WRONLY + O_APPEND, 8#644#); else Fd := Sys_Open (Sys.Err_File, O_CREAT + O_WRONLY + O_TRUNC, 8#644#); end if; if Fd < 0 then Sys_Exit (254); end if; if Fd /= STDERR_FILENO then Result := Sys_Dup2 (Fd, STDERR_FILENO); Result := Sys_Close (Fd); end if; end; end if; if Sys.Dir /= Null_Ptr then Result := Sys_Chdir (Sys.Dir); if Result < 0 then Sys_Exit (253); end if; end if; Result := Sys_Execvp (Sys.Argv (0), Sys.Argv.all); Sys_Exit (255); end if; -- Process creation failed, cleanup and raise an exception. if Proc.Pid < 0 then Cleanup; raise Process_Error with "Cannot create process"; end if; if Stdin_Pipes (1) /= NO_FILE then Result := Sys_Close (Stdin_Pipes (0)); Proc.Input := Create_Stream (Stdin_Pipes (1)).all'Access; end if; if Stdout_Pipes (0) /= NO_FILE then Result := Sys_Close (Stdout_Pipes (1)); Proc.Output := Create_Stream (Stdout_Pipes (0)).all'Access; end if; if Stderr_Pipes (0) /= NO_FILE then Result := Sys_Close (Stderr_Pipes (1)); Proc.Error := Create_Stream (Stderr_Pipes (0)).all'Access; end if; end Spawn; procedure Free is new Ada.Unchecked_Deallocation (Name => Ptr_Ptr_Array, Object => Ptr_Array); -- ------------------------------ -- Append the argument to the process argument list. -- ------------------------------ overriding procedure Append_Argument (Sys : in out System_Process; Arg : in String) is begin if Sys.Argv = null then Sys.Argv := new Ptr_Array (0 .. 10); elsif Sys.Argc = Sys.Argv'Last - 1 then declare N : constant Ptr_Ptr_Array := new Ptr_Array (0 .. Sys.Argc + 32); begin N (0 .. Sys.Argc) := Sys.Argv (0 .. Sys.Argc); Free (Sys.Argv); Sys.Argv := N; end; end if; Sys.Argv (Sys.Argc) := Interfaces.C.Strings.New_String (Arg); Sys.Argc := Sys.Argc + 1; Sys.Argv (Sys.Argc) := Interfaces.C.Strings.Null_Ptr; end Append_Argument; -- ------------------------------ -- Set the process input, output and error streams to redirect and use specified files. -- ------------------------------ overriding procedure Set_Streams (Sys : in out System_Process; Input : in String; Output : in String; Error : in String; Append_Output : in Boolean; Append_Error : in Boolean; To_Close : in File_Type_Array_Access) is begin if Input'Length > 0 then Sys.In_File := Interfaces.C.Strings.New_String (Input); end if; if Output'Length > 0 then Sys.Out_File := Interfaces.C.Strings.New_String (Output); Sys.Out_Append := Append_Output; end if; if Error'Length > 0 then Sys.Err_File := Interfaces.C.Strings.New_String (Error); Sys.Err_Append := Append_Error; end if; Sys.To_Close := To_Close; end Set_Streams; -- ------------------------------ -- Deletes the storage held by the system process. -- ------------------------------ overriding procedure Finalize (Sys : in out System_Process) is begin if Sys.Argv /= null then for I in Sys.Argv'Range loop Interfaces.C.Strings.Free (Sys.Argv (I)); end loop; Free (Sys.Argv); end if; Interfaces.C.Strings.Free (Sys.In_File); Interfaces.C.Strings.Free (Sys.Out_File); Interfaces.C.Strings.Free (Sys.Err_File); Interfaces.C.Strings.Free (Sys.Dir); end Finalize; end Util.Processes.Os;
Fix handling redirecting stdin/stdout/stderr to a file at the same time as using pipes
Fix handling redirecting stdin/stdout/stderr to a file at the same time as using pipes
Ada
apache-2.0
stcarrez/ada-util,stcarrez/ada-util
18a1e9a76c3d700ae7f956a9c7bb6ef826b54299
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; synth_version_major : constant String := "1"; synth_version_minor : constant String := "68"; copyright_years : constant String := "2015-2017"; host_localbase : constant String := "/usr/local"; host_make : constant String := "/usr/bin/make"; host_pkg8 : constant String := host_localbase & "/sbin/pkg"; host_bmake : constant String := host_localbase & "/bin/bmake"; host_make_program : constant String := host_make; chroot_make : constant String := "/usr/bin/make"; chroot_bmake : constant String := "/usr/pkg/bin/bmake -m /usr/pkg/share/mk"; chroot_make_program : constant String := chroot_make; jobs_per_cpu : constant := 2; type cpu_range is range 1 .. 32; type scanners is range cpu_range'First .. cpu_range'Last; type builders is range cpu_range'First .. cpu_range'Last * jobs_per_cpu; type package_system is (ports_collection, pkgsrc); software_framework : constant package_system := ports_collection; -- Notes for tailoring Synth. Use sed to: -- 1. Modify host_localbase to value of LOCALBASE -- 2. Change software_framework to "pkgsrc" for pkgsrc version -- 3. Change host_make_program to "host_bmake" for Non-NetBSD pkgsrc platforms -- 4. Change chroot_make_program to "chroot_bmake" for pkgsrc version -- 5. On replicant.ads, change "/usr/local" to "/usr/pkg" on pkgsrc end Definitions;
-- This file is covered by the Internet Software Consortium (ISC) License -- Reference: ../License.txt package Definitions is pragma Pure; synth_version_major : constant String := "1"; synth_version_minor : constant String := "69"; copyright_years : constant String := "2015-2017"; host_localbase : constant String := "/usr/local"; host_make : constant String := "/usr/bin/make"; host_pkg8 : constant String := host_localbase & "/sbin/pkg"; host_bmake : constant String := host_localbase & "/bin/bmake"; host_make_program : constant String := host_make; chroot_make : constant String := "/usr/bin/make"; chroot_bmake : constant String := "/usr/pkg/bin/bmake -m /usr/pkg/share/mk"; chroot_make_program : constant String := chroot_make; jobs_per_cpu : constant := 2; type cpu_range is range 1 .. 32; type scanners is range cpu_range'First .. cpu_range'Last; type builders is range cpu_range'First .. cpu_range'Last * jobs_per_cpu; type package_system is (ports_collection, pkgsrc); software_framework : constant package_system := ports_collection; -- Notes for tailoring Synth. Use sed to: -- 1. Modify host_localbase to value of LOCALBASE -- 2. Change software_framework to "pkgsrc" for pkgsrc version -- 3. Change host_make_program to "host_bmake" for Non-NetBSD pkgsrc platforms -- 4. Change chroot_make_program to "chroot_bmake" for pkgsrc version -- 5. On replicant.ads, change "/usr/local" to "/usr/pkg" on pkgsrc end Definitions;
Bump version to 1.69
Bump version to 1.69 Items addressed since release 1.68 * Extend base multiplier for build_depends phase from 5 to 11 minutes This is primarily for textlive for which the extraction time on an older machine with a spinning disk was measured at 7 minutes. On that machine the watchdog could kick on ports requiring texlive. * Increase internal allocation of 28,000 maximum ports to 32,000. The FreeBSD ports tree went over 28k ports recently. Apparently nobody tried to use Synth to build every port on FreeBSD recently because it should have failed. * Fix an incorrect command exception handler (noticed during the development of ravenadm). * Augment package architecture determination to recognize ARM and ARM64 packages. Synth builds natively on ARM64. * Add FAQ entry explaining how to use Synth to crossbuild armv6 (and aarch64 for that matter) packages on FreeBSD/ARM64 (contributed by Jonathan Chen) * Update copyright years on the ISC license
Ada
isc
jrmarino/synth,jrmarino/synth,jrmarino/synth,jrmarino/synth
486c17202c0e48445ce2945ce695002a6fa2a82c
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
Letractively/ada-security
10f8d4bb4aea4d70f683fb6a6e53e6d73d3ea92e
awa/src/awa-applications.adb
awa/src/awa-applications.adb
----------------------------------------------------------------------- -- awa -- Ada Web Application -- Copyright (C) 2009, 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 Ada.IO_Exceptions; with ASF.Beans; with EL.Contexts.Default; with Util.Files; with Util.Log.Loggers; with AWA.Components.Factory; with AWA.Applications.Factory; with AWA.Applications.Configs; package body AWA.Applications is use Util.Log; Log : constant Loggers.Logger := Loggers.Create ("AWA.Applications.Configs"); -- ------------------------------ -- Initialize the application -- ------------------------------ overriding procedure Initialize (App : in out Application; Conf : in ASF.Applications.Config; Factory : in out ASF.Applications.Main.Application_Factory'Class) is URI : constant String := Conf.Get ("database"); begin AWA.Applications.Factory.Set_Application (Factory, App'Unchecked_Access); App.DB_Factory.Create (URI); ASF.Applications.Main.Application (App).Initialize (Conf, Factory); Application'Class (App).Initialize_Modules; App.Load_Configuration; end Initialize; -- ------------------------------ -- 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 Application) is begin ASF.Applications.Main.Application (App).Initialize_Servlets; 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 Application) is begin ASF.Applications.Main.Application (App).Initialize_Filters; end Initialize_Filters; -- ------------------------------ -- Initialize the ASF components provided by the application. -- This procedure is called by <b>Initialize</b>. -- It should register the component factories used by the application. -- ------------------------------ overriding procedure Initialize_Components (App : in out Application) is begin ASF.Applications.Main.Application (App).Initialize_Components; App.Add_Components (AWA.Components.Factory.Definition); end Initialize_Components; -- ------------------------------ -- Initialize the application configuration properties. Properties defined in <b>Conf</b> -- are expanded by using the EL expression resolver. -- ------------------------------ overriding procedure Initialize_Config (App : in out Application; Conf : in out ASF.Applications.Config) is begin ASF.Applications.Main.Application (App).Initialize_Config (Conf); AWA.Modules.Initialize (App.Modules, Conf); end Initialize_Config; -- ------------------------------ -- Initialize the AWA modules provided by the application. -- This procedure is called by <b>Initialize</b>. -- It should register the modules used by the application. -- ------------------------------ procedure Initialize_Modules (App : in out Application) is begin null; end Initialize_Modules; -- ------------------------------ -- Register the module in the registry. -- ------------------------------ procedure Load_Configuration (App : in out Application) is Paths : constant String := App.Get_Config (P_Module_Dir.P); Base : constant String := App.Get_Config (P_Config_File.P); Path : constant String := Util.Files.Find_File_Path (Base, Paths); Ctx : aliased EL.Contexts.Default.Default_Context; begin AWA.Applications.Configs.Read_Configuration (App, Path, Ctx'Unchecked_Access); exception when Ada.IO_Exceptions.Name_Error => Log.Warn ("Application configuration file '{0}' does not exist", Path); end Load_Configuration; -- ------------------------------ -- Register the module in the application -- ------------------------------ procedure Register (App : in Application_Access; Module : access AWA.Modules.Module'Class; Name : in String; URI : in String := "") is begin App.Register (Module.all'Unchecked_Access, Name, URI); end Register; -- ------------------------------ -- Get the database connection for reading -- ------------------------------ function Get_Session (App : Application) return ADO.Sessions.Session is begin return App.DB_Factory.Get_Session; end Get_Session; -- ------------------------------ -- Get the database connection for writing -- ------------------------------ function Get_Master_Session (App : Application) return ADO.Sessions.Master_Session is begin return App.DB_Factory.Get_Master_Session; end Get_Master_Session; -- ------------------------------ -- Find the module with the given name -- ------------------------------ function Find_Module (App : in Application; Name : in String) return AWA.Modules.Module_Access is begin return AWA.Modules.Find_By_Name (App.Modules, Name); end Find_Module; -- ------------------------------ -- Register the module in the application -- ------------------------------ procedure Register (App : in out Application; Module : in AWA.Modules.Module_Access; Name : in String; URI : in String := "") is -- procedure Set_Beans (Factory : in out ASF.Beans.Bean_Factory); -- procedure Set_Beans (Factory : in out ASF.Beans.Bean_Factory) is -- begin -- Module.Register_Factory (Factory); -- end Set_Beans; -- -- procedure Register_Beans is -- new ASF.Applications.Main.Register_Beans (Set_Beans); begin -- Module.Initialize (); AWA.Modules.Register (App.Modules'Unchecked_Access, App'Unchecked_Access, Module, Name, URI); -- Register_Beans (App); -- App.View.Register_Module (Module); SCz: 2011-08-10: must check if necessary end Register; end AWA.Applications;
----------------------------------------------------------------------- -- awa -- Ada Web Application -- Copyright (C) 2009, 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 Ada.IO_Exceptions; with ASF.Beans; with ADO.Drivers; with EL.Contexts.Default; with Util.Files; with Util.Log.Loggers; with AWA.Components.Factory; with AWA.Applications.Factory; with AWA.Applications.Configs; package body AWA.Applications is use Util.Log; Log : constant Loggers.Logger := Loggers.Create ("AWA.Applications.Configs"); -- ------------------------------ -- Initialize the application -- ------------------------------ overriding procedure Initialize (App : in out Application; Conf : in ASF.Applications.Config; Factory : in out ASF.Applications.Main.Application_Factory'Class) is begin AWA.Applications.Factory.Set_Application (Factory, App'Unchecked_Access); ASF.Applications.Main.Application (App).Initialize (Conf, Factory); Application'Class (App).Initialize_Modules; App.Load_Configuration; end Initialize; -- ------------------------------ -- 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 Application) is begin ASF.Applications.Main.Application (App).Initialize_Servlets; 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 Application) is begin ASF.Applications.Main.Application (App).Initialize_Filters; end Initialize_Filters; -- ------------------------------ -- Initialize the ASF components provided by the application. -- This procedure is called by <b>Initialize</b>. -- It should register the component factories used by the application. -- ------------------------------ overriding procedure Initialize_Components (App : in out Application) is begin ASF.Applications.Main.Application (App).Initialize_Components; App.Add_Components (AWA.Components.Factory.Definition); end Initialize_Components; -- ------------------------------ -- Initialize the application configuration properties. Properties defined in <b>Conf</b> -- are expanded by using the EL expression resolver. -- ------------------------------ overriding procedure Initialize_Config (App : in out Application; Conf : in out ASF.Applications.Config) is begin ASF.Applications.Main.Application (App).Initialize_Config (Conf); ADO.Drivers.Initialize (Conf); App.DB_Factory.Create (Conf.Get ("database")); AWA.Modules.Initialize (App.Modules, Conf); end Initialize_Config; -- ------------------------------ -- Initialize the AWA modules provided by the application. -- This procedure is called by <b>Initialize</b>. -- It should register the modules used by the application. -- ------------------------------ procedure Initialize_Modules (App : in out Application) is begin null; end Initialize_Modules; -- ------------------------------ -- Register the module in the registry. -- ------------------------------ procedure Load_Configuration (App : in out Application) is Paths : constant String := App.Get_Config (P_Module_Dir.P); Base : constant String := App.Get_Config (P_Config_File.P); Path : constant String := Util.Files.Find_File_Path (Base, Paths); Ctx : aliased EL.Contexts.Default.Default_Context; begin AWA.Applications.Configs.Read_Configuration (App, Path, Ctx'Unchecked_Access); exception when Ada.IO_Exceptions.Name_Error => Log.Warn ("Application configuration file '{0}' does not exist", Path); end Load_Configuration; -- ------------------------------ -- Register the module in the application -- ------------------------------ procedure Register (App : in Application_Access; Module : access AWA.Modules.Module'Class; Name : in String; URI : in String := "") is begin App.Register (Module.all'Unchecked_Access, Name, URI); end Register; -- ------------------------------ -- Get the database connection for reading -- ------------------------------ function Get_Session (App : Application) return ADO.Sessions.Session is begin return App.DB_Factory.Get_Session; end Get_Session; -- ------------------------------ -- Get the database connection for writing -- ------------------------------ function Get_Master_Session (App : Application) return ADO.Sessions.Master_Session is begin return App.DB_Factory.Get_Master_Session; end Get_Master_Session; -- ------------------------------ -- Find the module with the given name -- ------------------------------ function Find_Module (App : in Application; Name : in String) return AWA.Modules.Module_Access is begin return AWA.Modules.Find_By_Name (App.Modules, Name); end Find_Module; -- ------------------------------ -- Register the module in the application -- ------------------------------ procedure Register (App : in out Application; Module : in AWA.Modules.Module_Access; Name : in String; URI : in String := "") is -- procedure Set_Beans (Factory : in out ASF.Beans.Bean_Factory); -- procedure Set_Beans (Factory : in out ASF.Beans.Bean_Factory) is -- begin -- Module.Register_Factory (Factory); -- end Set_Beans; -- -- procedure Register_Beans is -- new ASF.Applications.Main.Register_Beans (Set_Beans); begin -- Module.Initialize (); AWA.Modules.Register (App.Modules'Unchecked_Access, App'Unchecked_Access, Module, Name, URI); -- Register_Beans (App); -- App.View.Register_Module (Module); SCz: 2011-08-10: must check if necessary end Register; end AWA.Applications;
Initialize the database connection in Initialize_Config so that the EL expressions in configuration properties gets evaluated
Initialize the database connection in Initialize_Config so that the EL expressions in configuration properties gets evaluated
Ada
apache-2.0
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
5a66b83f6b0fe16e39e85d63fdd19567ed6a5827
regtests/wiki-html_parser-tests.adb
regtests/wiki-html_parser-tests.adb
----------------------------------------------------------------------- -- wiki-html_parsers-tests -- Unit tests for the HTML parser -- Copyright (C) 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.Assertions; with Util.Strings; with Util.Log.Loggers; with GNAT.Source_Info; package body Wiki.Html_Parser.Tests is Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("Wiki.Html_Parser"); package Caller is new Util.Test_Caller (Test, "Wikis.Html_Parser"); procedure Assert_Equals is new Util.Assertions.Assert_Equals_T (State_Type); procedure Assert_Equals is new Util.Assertions.Assert_Equals_T (Html_Parser_State); procedure Assert_Equals is new Util.Assertions.Assert_Equals_T (Wiki.Strings.WChar); procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is begin Caller.Add_Test (Suite, "Test Wiki.Html_Parsers.Parse_Element", Test_Parse_Element'Access); Caller.Add_Test (Suite, "Test Wiki.Html_Parsers.Parse_Element (Attributes)", Test_Parse_Element_Attributes'Access); Caller.Add_Test (Suite, "Test Wiki.Html_Parsers.Parse_Element (Errors)", Test_Parse_Error'Access); Caller.Add_Test (Suite, "Test Wiki.Html_Parsers.Parse_Element (Doctype)", Test_Parse_Doctype'Access); Caller.Add_Test (Suite, "Test Wiki.Html_Parsers.Parse_Entity", Test_Parse_Entity'Access); end Add_Tests; procedure Check_Parser (T : in out Test; Expect : in Wiki.Strings.WString; Expect_Kind : in State_Type; Content : in Wiki.Strings.WString; Source : in String := GNAT.Source_Info.File; Line : in Natural := GNAT.Source_Info.Line) is P : Parser_Type; Last : Natural; procedure Process (Kind : in State_Type; Name : in Wiki.Strings.WString; Attributes : in out Wiki.Attributes.Attribute_List) is begin Assert_Equals (T, Expect_Kind, Kind, "Invalid state type", Source, Line); if Kind /= HTML_ERROR then T.Assert (Name = Expect, "Invalid name", Source, Line); end if; T.Attributes := Attributes; end Process; begin Parse_Element (P, Content, Content'First, Process'Access, Last); Util.Tests.Assert_Equals (T, Content'Last + 1, Last, "Invalid last index", Source, Line); Assert_Equals (T, P.State, State_None, "Invalid parser state", Source, Line); Parse_Element (P, Content, Content'First, Process'Access, Last); Util.Tests.Assert_Equals (T, Content'Last + 1, Last, "Invalid last index", Source, Line); Assert_Equals (T, P.State, State_None, "Invalid parser state", Source, Line); for I in 1 .. Content'Length loop declare First : Natural := Content'First; End_Pos : Natural := Content'First; Retry : Natural := 0; begin loop Parse_Element (P, Content (Content'First .. End_Pos), First, Process'Access, Last); exit when Last = Content'Last + 1; Retry := Retry + 1; First := Last; End_Pos := End_Pos + I; if End_Pos > Content'Last then End_Pos := Content'Last; end if; T.Assert (Retry <= Content'Length, "Too many retries", Source, Line); end loop; Assert_Equals (T, P.State, State_None, "Invalid parser state", Source, Line); end; end loop; end Check_Parser; procedure Check_Error (T : in out Test; Last_Pos : in Natural; Content : in Wiki.Strings.WString; Source : in String := GNAT.Source_Info.File; Line : in Natural := GNAT.Source_Info.Line) is P : Parser_Type; Last : Natural; procedure Process (Kind : in State_Type; Name : in Wiki.Strings.WString; Attributes : in out Wiki.Attributes.Attribute_List) is begin Assert_Equals (T, HTML_ERROR, Kind, "Invalid state type", Source, Line); end Process; begin Parse_Element (P, Content, Content'First, Process'Access, Last); Util.Tests.Assert_Equals (T, Last_Pos, Last, "Invalid last index", Source, Line); end Check_Error; -- ------------------------------ -- Test Parse_Element operation. -- ------------------------------ procedure Test_Parse_Element (T : in out Test) is begin Check_Parser (T, "a", HTML_START, "a>"); Check_Parser (T, "a", HTML_START, " a >"); Check_Parser (T, "input", HTML_START, "input>"); Check_Parser (T, "a", HTML_END, "/a>"); Check_Parser (T, "input", HTML_START_END, " input />"); Check_Parser (T, "br", HTML_START_END, "br/>"); Check_Parser (T, "img", HTML_END, "/img >"); end Test_Parse_Element; -- ------------------------------ -- Test parsing HTML with errors. -- ------------------------------ procedure Test_Parse_Error (T : in out Test) is begin Check_Error (T, 2, "a'"); Check_Error (T, 9, "input """); Check_Error (T, 7, "input ="); Check_Error (T, 17, "input abcd efgh ="); end Test_Parse_Error; procedure Check_Attribute (T : in out Test; Name : in String; Value : in Wiki.Strings.WString) is V : constant Wiki.Strings.WString := Wiki.Attributes.Get_Attribute (T.Attributes, Name); begin T.Assert (Value = V, "Invalid attribute " & Name); end Check_Attribute; -- ------------------------------ -- Test Parse_Element with attributes -- ------------------------------ procedure Test_Parse_Element_Attributes (T : in out Test) is begin Check_Parser (T, "a", HTML_START, "a href='toto' title=' bla bla '>"); Util.Tests.Assert_Equals (T, 2, Wiki.Attributes.Length (T.Attributes), "invalid number of attributes"); Check_Attribute (T, "href", "toto"); Check_Attribute (T, "title", " bla bla "); Check_Parser (T, "img", HTML_START_END, "img src=""plop"" width=4 height=5/>"); Util.Tests.Assert_Equals (T, 3, Wiki.Attributes.Length (T.Attributes), "invalid number of attributes"); Check_Attribute (T, "src", "plop"); Check_Attribute (T, "width", "4"); Check_Attribute (T, "height", "5"); Check_Parser (T, "select", HTML_START, "select id=a name=test >"); Util.Tests.Assert_Equals (T, 2, Wiki.Attributes.Length (T.Attributes), "invalid number of attributes"); Check_Attribute (T, "id", "a"); Check_Attribute (T, "name", "test"); end Test_Parse_Element_Attributes; -- ------------------------------ -- Test Parse_Doctype -- ------------------------------ procedure Test_Parse_Doctype (T : in out Test) is P : Parser_Type; Last : Natural; procedure Process (Kind : in State_Type; Name : in Wiki.Strings.WString; Attributes : in out Wiki.Attributes.Attribute_List) is begin T.Fail ("Should not be called"); end Process; begin Parse_Element (P, "!doctype html>", 1, Process'Access, Last); Util.Tests.Assert_Equals (T, 15, Last, "Invalid last index"); Parse_Element (P, "!doctype html> ", 1, Process'Access, Last); Util.Tests.Assert_Equals (T, 15, Last, "Invalid last index"); Parse_Element (P, "!-- blq blq < > -->", 1, Process'Access, Last); Util.Tests.Assert_Equals (T, 20, Last, "Invalid last index"); Parse_Element (P, "!-- blq blq < > --", 1, Process'Access, Last); Util.Tests.Assert_Equals (T, 19, Last, "Invalid last index"); Assert_Equals (T, P.State, State_Comment, "Invalid parser state"); Parse_Element (P, "bla -- blq blq < > -->", 1, Process'Access, Last); Util.Tests.Assert_Equals (T, 23, Last, "Invalid last index"); Assert_Equals (T, P.State, State_None, "Invalid parser state"); Parse_Element (P, "!doctype html ", 1, Process'Access, Last); Util.Tests.Assert_Equals (T, 16, Last, "Invalid last index"); Assert_Equals (T, P.State, State_Doctype, "Invalid parser state"); Parse_Element (P, "bla -- blq blq < > --x", 1, Process'Access, Last); Util.Tests.Assert_Equals (T, 19, Last, "Invalid last index"); Assert_Equals (T, P.State, State_None, "Invalid parser state"); end Test_Parse_Doctype; -- ------------------------------ -- Test Parse_Entity. -- ------------------------------ procedure Test_Parse_Entity (T : in out Test) is P : Parser_Type; Last : Natural; Entity : Wiki.Strings.WChar; begin Parse_Entity (P, "amp; ", 1, Entity, Last); Util.Tests.Assert_Equals (T, 5, Last, "Invalid last index"); Assert_Equals (T, '&', Entity, "Invalid parsed entity"); Parse_Entity (P, "dagger;", 1, Entity, Last); Util.Tests.Assert_Equals (T, 8, Last, "Invalid last index"); Assert_Equals (T, Wiki.Strings.WChar'Val (8224), Entity, "Invalid parsed entity"); Parse_Entity (P, "Dagger;", 1, Entity, Last); Util.Tests.Assert_Equals (T, 8, Last, "Invalid last index"); Assert_Equals (T, Wiki.Strings.WChar'Val (8225), Entity, "Invalid parsed entity"); Parse_Entity (P, "#1234;", 1, Entity, Last); Util.Tests.Assert_Equals (T, 7, Last, "Invalid last index"); Assert_Equals (T, Wiki.Strings.WChar'Val (1234), Entity, "Invalid parsed entity"); Parse_Entity (P, "#x1234;", 1, Entity, Last); Util.Tests.Assert_Equals (T, 8, Last, "Invalid last index"); Assert_Equals (T, Wiki.Strings.WChar'Val (16#1234#), Entity, "Invalid parsed entity"); Parse_Entity (P, "#xabCD;", 1, Entity, Last); Util.Tests.Assert_Equals (T, 8, Last, "Invalid last index"); Assert_Equals (T, Wiki.Strings.WChar'Val (16#abcd#), Entity, "Invalid parsed entity"); Parse_Entity (P, "dagobert;", 1, Entity, Last); Util.Tests.Assert_Equals (T, 10, Last, "Invalid last index"); Assert_Equals (T, NUL, Entity, "Invalid parsed entity"); Parse_Entity (P, "#x000000;", 1, Entity, Last); Util.Tests.Assert_Equals (T, 10, Last, "Invalid last index"); Assert_Equals (T, Wiki.Strings.WChar'Val (16#0FFFD#), Entity, "Invalid parsed entity"); Parse_Entity (P, "#000000;", 1, Entity, Last); Util.Tests.Assert_Equals (T, 9, Last, "Invalid last index"); Assert_Equals (T, Wiki.Strings.WChar'Val (16#0FFFD#), Entity, "Invalid parsed entity"); Parse_Entity (P, "#00000b;", 1, Entity, Last); Util.Tests.Assert_Equals (T, 9, Last, "Invalid last index"); Assert_Equals (T, NUL, Entity, "Invalid parsed entity"); Parse_Entity (P, "#x0000g0;", 1, Entity, Last); Util.Tests.Assert_Equals (T, 10, Last, "Invalid last index"); Assert_Equals (T, NUL, Entity, "Invalid parsed entity"); Parse_Entity (P, "bla bla bla bla bla ;", 1, Entity, Last); Util.Tests.Assert_Equals (T, 11, Last, "Invalid last index"); Assert_Equals (T, NUL, Entity, "Invalid parsed entity"); end Test_Parse_Entity; end Wiki.Html_Parser.Tests;
----------------------------------------------------------------------- -- wiki-html_parsers-tests -- Unit tests for the HTML parser -- Copyright (C) 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.Assertions; with GNAT.Source_Info; package body Wiki.Html_Parser.Tests is package Caller is new Util.Test_Caller (Test, "Wikis.Html_Parser"); procedure Assert_Equals is new Util.Assertions.Assert_Equals_T (State_Type); procedure Assert_Equals is new Util.Assertions.Assert_Equals_T (Html_Parser_State); procedure Assert_Equals is new Util.Assertions.Assert_Equals_T (Entity_State_Type); procedure Assert_Equals is new Util.Assertions.Assert_Equals_T (Wiki.Strings.WChar); procedure Check_Parser (T : in out Test; Expect : in Wiki.Strings.WString; Expect_Kind : in State_Type; Content : in Wiki.Strings.WString; Source : in String := GNAT.Source_Info.File; Line : in Natural := GNAT.Source_Info.Line); procedure Check_Error (T : in out Test; Last_Pos : in Natural; Content : in Wiki.Strings.WString; Source : in String := GNAT.Source_Info.File; Line : in Natural := GNAT.Source_Info.Line); procedure Check_Attribute (T : in out Test; Name : in String; Value : in Wiki.Strings.WString); procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is begin Caller.Add_Test (Suite, "Test Wiki.Html_Parsers.Parse_Element", Test_Parse_Element'Access); Caller.Add_Test (Suite, "Test Wiki.Html_Parsers.Parse_Element (Attributes)", Test_Parse_Element_Attributes'Access); Caller.Add_Test (Suite, "Test Wiki.Html_Parsers.Parse_Element (Errors)", Test_Parse_Error'Access); Caller.Add_Test (Suite, "Test Wiki.Html_Parsers.Parse_Element (Doctype)", Test_Parse_Doctype'Access); Caller.Add_Test (Suite, "Test Wiki.Html_Parsers.Parse_Entity", Test_Parse_Entity'Access); end Add_Tests; procedure Check_Parser (T : in out Test; Expect : in Wiki.Strings.WString; Expect_Kind : in State_Type; Content : in Wiki.Strings.WString; Source : in String := GNAT.Source_Info.File; Line : in Natural := GNAT.Source_Info.Line) is procedure Process (Kind : in State_Type; Name : in Wiki.Strings.WString; Attributes : in out Wiki.Attributes.Attribute_List); P : Parser_Type; Last : Natural; procedure Process (Kind : in State_Type; Name : in Wiki.Strings.WString; Attributes : in out Wiki.Attributes.Attribute_List) is begin Assert_Equals (T, Expect_Kind, Kind, "Invalid state type", Source, Line); if Kind /= HTML_ERROR then T.Assert (Name = Expect, "Invalid name", Source, Line); end if; T.Attributes := Attributes; end Process; begin Parse_Element (P, Content, Content'First, Process'Access, Last); Util.Tests.Assert_Equals (T, Content'Last + 1, Last, "Invalid last index", Source, Line); Assert_Equals (T, P.State, State_None, "Invalid parser state", Source, Line); Parse_Element (P, Content, Content'First, Process'Access, Last); Util.Tests.Assert_Equals (T, Content'Last + 1, Last, "Invalid last index", Source, Line); Assert_Equals (T, P.State, State_None, "Invalid parser state", Source, Line); for I in 1 .. Content'Length loop declare First : Natural := Content'First; End_Pos : Natural := Content'First; Retry : Natural := 0; begin loop Parse_Element (P, Content (Content'First .. End_Pos), First, Process'Access, Last); exit when Last = Content'Last + 1; Retry := Retry + 1; First := Last; End_Pos := End_Pos + I; if End_Pos > Content'Last then End_Pos := Content'Last; end if; T.Assert (Retry <= Content'Length, "Too many retries", Source, Line); end loop; Assert_Equals (T, P.State, State_None, "Invalid parser state", Source, Line); end; end loop; end Check_Parser; procedure Check_Error (T : in out Test; Last_Pos : in Natural; Content : in Wiki.Strings.WString; Source : in String := GNAT.Source_Info.File; Line : in Natural := GNAT.Source_Info.Line) is procedure Process (Kind : in State_Type; Name : in Wiki.Strings.WString; Attributes : in out Wiki.Attributes.Attribute_List); P : Parser_Type; Last : Natural; procedure Process (Kind : in State_Type; Name : in Wiki.Strings.WString; Attributes : in out Wiki.Attributes.Attribute_List) is pragma Unreferenced (Name, Attributes); begin Assert_Equals (T, HTML_ERROR, Kind, "Invalid state type", Source, Line); end Process; begin Parse_Element (P, Content, Content'First, Process'Access, Last); Util.Tests.Assert_Equals (T, Last_Pos, Last, "Invalid last index", Source, Line); end Check_Error; -- ------------------------------ -- Test Parse_Element operation. -- ------------------------------ procedure Test_Parse_Element (T : in out Test) is begin Check_Parser (T, "a", HTML_START, "a>"); Check_Parser (T, "a", HTML_START, " a >"); Check_Parser (T, "input", HTML_START, "input>"); Check_Parser (T, "a", HTML_END, "/a>"); Check_Parser (T, "input", HTML_START_END, " input />"); Check_Parser (T, "br", HTML_START_END, "br/>"); Check_Parser (T, "img", HTML_END, "/img >"); end Test_Parse_Element; -- ------------------------------ -- Test parsing HTML with errors. -- ------------------------------ procedure Test_Parse_Error (T : in out Test) is begin Check_Error (T, 2, "a'"); Check_Error (T, 9, "input """); Check_Error (T, 7, "input ="); Check_Error (T, 17, "input abcd efgh ="); end Test_Parse_Error; procedure Check_Attribute (T : in out Test; Name : in String; Value : in Wiki.Strings.WString) is V : constant Wiki.Strings.WString := Wiki.Attributes.Get_Attribute (T.Attributes, Name); begin T.Assert (Value = V, "Invalid attribute " & Name); end Check_Attribute; -- ------------------------------ -- Test Parse_Element with attributes -- ------------------------------ procedure Test_Parse_Element_Attributes (T : in out Test) is begin Check_Parser (T, "a", HTML_START, "a href='toto' title=' bla bla '>"); Util.Tests.Assert_Equals (T, 2, Wiki.Attributes.Length (T.Attributes), "invalid number of attributes"); Check_Attribute (T, "href", "toto"); Check_Attribute (T, "title", " bla bla "); Check_Parser (T, "img", HTML_START_END, "img src=""plop"" width=4 height=5/>"); Util.Tests.Assert_Equals (T, 3, Wiki.Attributes.Length (T.Attributes), "invalid number of attributes"); Check_Attribute (T, "src", "plop"); Check_Attribute (T, "width", "4"); Check_Attribute (T, "height", "5"); Check_Parser (T, "select", HTML_START, "select id=a name=test >"); Util.Tests.Assert_Equals (T, 2, Wiki.Attributes.Length (T.Attributes), "invalid number of attributes"); Check_Attribute (T, "id", "a"); Check_Attribute (T, "name", "test"); end Test_Parse_Element_Attributes; -- ------------------------------ -- Test Parse_Doctype -- ------------------------------ procedure Test_Parse_Doctype (T : in out Test) is procedure Process (Kind : in State_Type; Name : in Wiki.Strings.WString; Attributes : in out Wiki.Attributes.Attribute_List); P : Parser_Type; Last : Natural; procedure Process (Kind : in State_Type; Name : in Wiki.Strings.WString; Attributes : in out Wiki.Attributes.Attribute_List) is pragma Unreferenced (Kind, Name, Attributes); begin T.Fail ("Should not be called"); end Process; begin Parse_Element (P, "!doctype html>", 1, Process'Access, Last); Util.Tests.Assert_Equals (T, 15, Last, "Invalid last index"); Parse_Element (P, "!doctype html> ", 1, Process'Access, Last); Util.Tests.Assert_Equals (T, 15, Last, "Invalid last index"); Parse_Element (P, "!-- blq blq < > -->", 1, Process'Access, Last); Util.Tests.Assert_Equals (T, 20, Last, "Invalid last index"); Parse_Element (P, "!-- blq blq < > --", 1, Process'Access, Last); Util.Tests.Assert_Equals (T, 19, Last, "Invalid last index"); Assert_Equals (T, P.State, State_Comment, "Invalid parser state"); Parse_Element (P, "bla -- blq blq < > -->", 1, Process'Access, Last); Util.Tests.Assert_Equals (T, 23, Last, "Invalid last index"); Assert_Equals (T, P.State, State_None, "Invalid parser state"); Parse_Element (P, "!doctype html ", 1, Process'Access, Last); Util.Tests.Assert_Equals (T, 16, Last, "Invalid last index"); Assert_Equals (T, P.State, State_Doctype, "Invalid parser state"); Parse_Element (P, "bla -- blq blq < > --x", 1, Process'Access, Last); Util.Tests.Assert_Equals (T, 19, Last, "Invalid last index"); Assert_Equals (T, P.State, State_None, "Invalid parser state"); end Test_Parse_Doctype; -- ------------------------------ -- Test Parse_Entity. -- ------------------------------ procedure Test_Parse_Entity (T : in out Test) is P : Parser_Type; Last : Natural; Entity : Wiki.Strings.WChar; Status : Entity_State_Type := ENTITY_NONE; begin Parse_Entity (P, "amp; ", 1, Status, Entity, Last); Util.Tests.Assert_Equals (T, 5, Last, "Invalid last index"); Assert_Equals (T, '&', Entity, "Invalid parsed entity"); Parse_Entity (P, "dagger;", 1, Status, Entity, Last); Util.Tests.Assert_Equals (T, 8, Last, "Invalid last index"); Assert_Equals (T, Wiki.Strings.WChar'Val (8224), Entity, "Invalid parsed entity"); Parse_Entity (P, "Dagger;", 1, Status, Entity, Last); Util.Tests.Assert_Equals (T, 8, Last, "Invalid last index"); Assert_Equals (T, Wiki.Strings.WChar'Val (8225), Entity, "Invalid parsed entity"); Parse_Entity (P, "#1234;", 1, Status, Entity, Last); Util.Tests.Assert_Equals (T, 7, Last, "Invalid last index"); Assert_Equals (T, Wiki.Strings.WChar'Val (1234), Entity, "Invalid parsed entity"); Parse_Entity (P, "#x1234;", 1, Status, Entity, Last); Util.Tests.Assert_Equals (T, 8, Last, "Invalid last index"); Assert_Equals (T, Wiki.Strings.WChar'Val (16#1234#), Entity, "Invalid parsed entity"); Parse_Entity (P, "#xabCD;", 1, Status, Entity, Last); Util.Tests.Assert_Equals (T, 8, Last, "Invalid last index"); Assert_Equals (T, Wiki.Strings.WChar'Val (16#abcd#), Entity, "Invalid parsed entity"); Assert_Equals (T, ENTITY_VALID, Status, "Invalid status"); Parse_Entity (P, "dagobert;", 1, Status, Entity, Last); Util.Tests.Assert_Equals (T, 1, Last, "Invalid last index"); Assert_Equals (T, NUL, Entity, "Invalid parsed entity"); Assert_Equals (T, ENTITY_NONE, Status, "Invalid status"); Parse_Entity (P, "#x000000;", 1, Status, Entity, Last); Util.Tests.Assert_Equals (T, 10, Last, "Invalid last index"); Assert_Equals (T, Wiki.Strings.WChar'Val (16#0FFFD#), Entity, "Invalid parsed entity"); Parse_Entity (P, "#000000;", 1, Status, Entity, Last); Util.Tests.Assert_Equals (T, 9, Last, "Invalid last index"); Assert_Equals (T, Wiki.Strings.WChar'Val (16#0FFFD#), Entity, "Invalid parsed entity"); Parse_Entity (P, "#00000b;", 1, Status, Entity, Last); Assert_Equals (T, ENTITY_NONE, Status, "Invalid status"); Util.Tests.Assert_Equals (T, 1, Last, "Invalid last index"); Assert_Equals (T, NUL, Entity, "Invalid parsed entity"); Parse_Entity (P, "#x0000g0;", 1, Status, Entity, Last); Assert_Equals (T, ENTITY_NONE, Status, "Invalid status"); Util.Tests.Assert_Equals (T, 1, Last, "Invalid last index"); Assert_Equals (T, NUL, Entity, "Invalid parsed entity"); Parse_Entity (P, "bla bla bla bla bla ;", 1, Status, Entity, Last); Assert_Equals (T, ENTITY_NONE, Status, "Invalid status"); Util.Tests.Assert_Equals (T, 1, Last, "Invalid last index"); Assert_Equals (T, NUL, Entity, "Invalid parsed entity"); end Test_Parse_Entity; end Wiki.Html_Parser.Tests;
Update the unit test to check the status result
Update the unit test to check the status result
Ada
apache-2.0
stcarrez/ada-wiki,stcarrez/ada-wiki
badda207a5c726b9e02d0284ec787a6ed482ed04
src/natools-smaz_generic.ads
src/natools-smaz_generic.ads
------------------------------------------------------------------------------ -- Copyright (c) 2016, 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. -- ------------------------------------------------------------------------------ with Ada.Streams; generic type Dictionary_Code is (<>); with procedure Read_Code (Input : in Ada.Streams.Stream_Element_Array; Offset : in out Ada.Streams.Stream_Element_Offset; Code : out Dictionary_Code; Verbatim_Length : out Natural; Last_Code : in Dictionary_Code; Variable_Length_Verbatim : in Boolean); with procedure Read_Verbatim (Input : in Ada.Streams.Stream_Element_Array; Offset : in out Ada.Streams.Stream_Element_Offset; Output : out String); with procedure Skip_Verbatim (Input : in Ada.Streams.Stream_Element_Array; Offset : in out Ada.Streams.Stream_Element_Offset; Verbatim_Length : in Positive); with function Verbatim_Size (Input_Length : in Positive; Last_Code : in Dictionary_Code; Variable_Length_Verbatim : in Boolean) return Ada.Streams.Stream_Element_Count; with procedure Write_Code (Output : in out Ada.Streams.Stream_Element_Array; Offset : in out Ada.Streams.Stream_Element_Offset; Code : in Dictionary_Code); with procedure Write_Verbatim (Output : in out Ada.Streams.Stream_Element_Array; Offset : in out Ada.Streams.Stream_Element_Offset; Input : in String; Last_Code : in Dictionary_Code; Variable_Length_Verbatim : in Boolean); package Natools.Smaz_Generic is pragma Pure; type Offset_Array is array (Dictionary_Code range <>) of Positive; type Dictionary (Last_Code : Dictionary_Code; Values_Last : Natural) is record Variable_Length_Verbatim : Boolean; Max_Word_Length : Positive; Offsets : Offset_Array (Dictionary_Code'Succ (Dictionary_Code'First) .. Last_Code); Values : String (1 .. Values_Last); Hash : not null access function (Value : String) return Natural; end record with Dynamic_Predicate => (for all Code in Dictionary.Offsets'Range => Dictionary.Offsets (Code) in Dictionary.Values'Range) and then (for all Code in Dictionary_Code'First .. Dictionary.Last_Code => Code_Last (Dictionary.Offsets, Code, Dictionary.Values'Last) + 1 - Code_First (Dictionary.Offsets, Code, Dictionary.Values'First) in 1 .. Dictionary.Max_Word_Length); function Code_First (Offsets : in Offset_Array; Code : in Dictionary_Code; Fallback : in Positive) return Positive is (if Code in Offsets'Range then Offsets (Code) else Fallback); -- Return the first index of the value for Code in Dictionary.Values function Code_Last (Offsets : in Offset_Array; Code : in Dictionary_Code; Fallback : in Natural) return Natural is (if Dictionary_Code'Succ (Code) in Offsets'Range then Offsets (Dictionary_Code'Succ (Code)) - 1 else Fallback); -- Return the value index of the value for Code in Dictionary.Values function Is_Valid_Code (Dict : in Dictionary; Code : in Dictionary_Code) return Boolean is (Code in Dictionary_Code'First .. Dict.Last_Code); -- Return whether Code exists in Dict function Dict_Entry (Dict : in Dictionary; Code : in Dictionary_Code) return String is (Dict.Values (Code_First (Dict.Offsets, Code, Dict.Values'First) .. Code_Last (Dict.Offsets, Code, Dict.Values'Last))) with Pre => Is_Valid_Code (Dict, Code); -- Return the string for at the given Index in Dict function Dict_Entry_Length (Dict : in Dictionary; Code : in Dictionary_Code) return Positive is (1 + Code_Last (Dict.Offsets, Code, Dict.Values'Last) - Code_First (Dict.Offsets, Code, Dict.Values'First)) with Pre => Is_Valid_Code (Dict, Code); -- Return the length of the string for at the given Index in Dict function Compressed_Upper_Bound (Dict : in Dictionary; Input : in String) return Ada.Streams.Stream_Element_Count; -- Return the maximum number of bytes needed to encode Input procedure Compress (Dict : in Dictionary; Input : in String; Output_Buffer : out Ada.Streams.Stream_Element_Array; Output_Last : out Ada.Streams.Stream_Element_Offset); -- Encode Input into Output_Buffer function Compress (Dict : in Dictionary; Input : in String) return Ada.Streams.Stream_Element_Array; -- Return an encoded buffer for Input function Decompressed_Length (Dict : in Dictionary; Input : in Ada.Streams.Stream_Element_Array) return Natural; -- Return the exact length when Input is decoded procedure Decompress (Dict : in Dictionary; Input : in Ada.Streams.Stream_Element_Array; Output_Buffer : out String; Output_Last : out Natural); -- Decode Input into Output_Buffer function Decompress (Dict : in Dictionary; Input : in Ada.Streams.Stream_Element_Array) return String; -- Return a decoded buffer for Input end Natools.Smaz_Generic;
------------------------------------------------------------------------------ -- Copyright (c) 2016, 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. -- ------------------------------------------------------------------------------ with Ada.Streams; generic type Dictionary_Code is (<>); with procedure Read_Code (Input : in Ada.Streams.Stream_Element_Array; Offset : in out Ada.Streams.Stream_Element_Offset; Code : out Dictionary_Code; Verbatim_Length : out Natural; Last_Code : in Dictionary_Code; Variable_Length_Verbatim : in Boolean); with procedure Read_Verbatim (Input : in Ada.Streams.Stream_Element_Array; Offset : in out Ada.Streams.Stream_Element_Offset; Output : out String); with procedure Skip_Verbatim (Input : in Ada.Streams.Stream_Element_Array; Offset : in out Ada.Streams.Stream_Element_Offset; Verbatim_Length : in Positive); with function Verbatim_Size (Input_Length : in Positive; Last_Code : in Dictionary_Code; Variable_Length_Verbatim : in Boolean) return Ada.Streams.Stream_Element_Count; with procedure Write_Code (Output : in out Ada.Streams.Stream_Element_Array; Offset : in out Ada.Streams.Stream_Element_Offset; Code : in Dictionary_Code); with procedure Write_Verbatim (Output : in out Ada.Streams.Stream_Element_Array; Offset : in out Ada.Streams.Stream_Element_Offset; Input : in String; Last_Code : in Dictionary_Code; Variable_Length_Verbatim : in Boolean); package Natools.Smaz_Generic is pragma Pure; type Offset_Array is array (Dictionary_Code range <>) of Positive; type Dictionary (Last_Code : Dictionary_Code; Values_Last : Natural) is record Variable_Length_Verbatim : Boolean; Max_Word_Length : Positive; Offsets : Offset_Array (Dictionary_Code'Succ (Dictionary_Code'First) .. Last_Code); Values : String (1 .. Values_Last); Hash : not null access function (Value : String) return Natural; end record; function Code_First (Offsets : in Offset_Array; Code : in Dictionary_Code; Fallback : in Positive) return Positive is (if Code in Offsets'Range then Offsets (Code) else Fallback); -- Return the first index of the value for Code in Dictionary.Values function Code_Last (Offsets : in Offset_Array; Code : in Dictionary_Code; Fallback : in Natural) return Natural is (if Dictionary_Code'Succ (Code) in Offsets'Range then Offsets (Dictionary_Code'Succ (Code)) - 1 else Fallback); -- Return the value index of the value for Code in Dictionary.Values function Is_Valid_Code (Dict : in Dictionary; Code : in Dictionary_Code) return Boolean is (Code in Dictionary_Code'First .. Dict.Last_Code); -- Return whether Code exists in Dict function Dict_Entry (Dict : in Dictionary; Code : in Dictionary_Code) return String is (Dict.Values (Code_First (Dict.Offsets, Code, Dict.Values'First) .. Code_Last (Dict.Offsets, Code, Dict.Values'Last))) with Pre => Is_Valid_Code (Dict, Code); -- Return the string for at the given Index in Dict function Dict_Entry_Length (Dict : in Dictionary; Code : in Dictionary_Code) return Positive is (1 + Code_Last (Dict.Offsets, Code, Dict.Values'Last) - Code_First (Dict.Offsets, Code, Dict.Values'First)) with Pre => Is_Valid_Code (Dict, Code); -- Return the length of the string for at the given Index in Dict function Compressed_Upper_Bound (Dict : in Dictionary; Input : in String) return Ada.Streams.Stream_Element_Count; -- Return the maximum number of bytes needed to encode Input procedure Compress (Dict : in Dictionary; Input : in String; Output_Buffer : out Ada.Streams.Stream_Element_Array; Output_Last : out Ada.Streams.Stream_Element_Offset); -- Encode Input into Output_Buffer function Compress (Dict : in Dictionary; Input : in String) return Ada.Streams.Stream_Element_Array; -- Return an encoded buffer for Input function Decompressed_Length (Dict : in Dictionary; Input : in Ada.Streams.Stream_Element_Array) return Natural; -- Return the exact length when Input is decoded procedure Decompress (Dict : in Dictionary; Input : in Ada.Streams.Stream_Element_Array; Output_Buffer : out String; Output_Last : out Natural); -- Decode Input into Output_Buffer function Decompress (Dict : in Dictionary; Input : in Ada.Streams.Stream_Element_Array) return String; -- Return a decoded buffer for Input end Natools.Smaz_Generic;
remove the too-costly dynamic predicate
smaz_generic: remove the too-costly dynamic predicate
Ada
isc
faelys/natools
232ab82fff139c28c9422ecbf7ae0eaf02d992d6
orka/src/orka/windows/orka-os.adb
orka/src/orka/windows/orka-os.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. package body Orka.OS is procedure Set_Task_Name (Name : in String) is begin null; end Set_Task_Name; function Monotonic_Clock return Duration is begin raise Program_Error with "BUG: Monotonic_Clock not implemented yet on Windows"; return 0.0; end Monotonic_Clock; ---------------------------------------------------------------------------- subtype Size_Type is Interfaces.C.unsigned_long; procedure C_Fwrite (Value : String; Size : Size_Type; Count : Size_Type; File : System.Address) with Import, Convention => C, External_Name => "fwrite"; File_Standard_Output : constant System.Address with Import, Convention => C, External_Name => "stdout"; File_Standard_Error : constant System.Address with Import, Convention => C, External_Name => "stderr"; procedure Put_Line (Value : String; Kind : File_Kind := Standard_Output) is package L1 renames Ada.Characters.Latin_1; C_Value : constant String := Value & L1.LF; begin C_Fwrite (C_Value, 1, C_Value'Length, (case Kind is when Standard_Output => File_Standard_Output, when Standard_Error => File_Standard_Error)); end Put_Line; end Orka.OS;
-- 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 System; with Ada.Characters.Latin_1; package body Orka.OS is procedure Set_Task_Name (Name : in String) is begin null; end Set_Task_Name; function Monotonic_Clock return Duration is begin raise Program_Error with "BUG: Monotonic_Clock not implemented yet on Windows"; return 0.0; end Monotonic_Clock; ---------------------------------------------------------------------------- subtype Size_Type is Interfaces.C.unsigned_long; procedure C_Fwrite (Value : String; Size : Size_Type; Count : Size_Type; File : System.Address) with Import, Convention => C, External_Name => "fwrite"; File_Standard_Output : constant System.Address with Import, Convention => C, External_Name => "stdout"; File_Standard_Error : constant System.Address with Import, Convention => C, External_Name => "stderr"; procedure Put_Line (Value : String; Kind : File_Kind := Standard_Output) is package L1 renames Ada.Characters.Latin_1; C_Value : constant String := Value & L1.LF; begin C_Fwrite (C_Value, 1, C_Value'Length, (case Kind is when Standard_Output => File_Standard_Output, when Standard_Error => File_Standard_Error)); end Put_Line; end Orka.OS;
Fix missing importing used packages in package Orka.OS on Windows
Fix missing importing used packages in package Orka.OS on Windows Signed-off-by: onox <[email protected]>
Ada
apache-2.0
onox/orka
6a10503b156d61e4ef5e0f07a5f91d136db48036
src/asf-applications-main-configs.adb
src/asf-applications-main-configs.adb
----------------------------------------------------------------------- -- applications-main-configs -- Configuration support for ASF Applications -- Copyright (C) 2009, 2010, 2011, 2012, 2013, 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 Util.Log.Loggers; with EL.Functions.Namespaces; with ASF.Navigations; with ASF.Navigations.Mappers; with Servlet.Core.Mappers; with ASF.Servlets.Faces.Mappers; with ASF.Beans.Mappers; with ASF.Views.Nodes.Core; package body ASF.Applications.Main.Configs is use Util.Log; -- The logger Log : constant Loggers.Logger := Loggers.Create ("ASF.Applications.Main.Configs"); function Get_Locale (Value : in Util.Beans.Objects.Object) return Util.Locales.Locale; function Get_Locale (Value : in Util.Beans.Objects.Object) return Util.Locales.Locale is Name : constant String := Util.Beans.Objects.To_String (Value); Locale : constant Util.Locales.Locale := Util.Locales.Get_Locale (Name); begin return Locale; end Get_Locale; -- ------------------------------ -- Save in the application config object the value associated with the given field. -- When the <b>TAG_MESSAGE_BUNDLE</b> field is reached, insert the new bundle definition -- in the application. -- ------------------------------ procedure Set_Member (N : in out Application_Config; Field : in Application_Fields; Value : in Util.Beans.Objects.Object) is begin case Field is when TAG_MESSAGE_VAR => N.Name := Value; when TAG_MESSAGE_BUNDLE => declare Bundle : constant String := Util.Beans.Objects.To_String (Value); begin if Util.Beans.Objects.Is_Null (N.Name) then N.App.Register (Name => Bundle & "Msg", Bundle => Bundle); else N.App.Register (Name => Util.Beans.Objects.To_String (N.Name), Bundle => Bundle); end if; N.Name := Util.Beans.Objects.Null_Object; end; when TAG_DEFAULT_LOCALE => N.App.Set_Default_Locale (Get_Locale (Value)); when TAG_SUPPORTED_LOCALE => N.App.Add_Supported_Locale (Get_Locale (Value)); end case; end Set_Member; AMapper : aliased Application_Mapper.Mapper; -- ------------------------------ -- Setup the XML parser to read the managed bean definitions. -- By instantiating this package, the <b>Reader</b> gets populated with the XML mappings -- to read the servlet, managed beans and navigation rules. -- ------------------------------ package body Reader_Config is procedure Set_Property_Context (Params : in Util.Properties.Manager'Class); -- Get the navigation handler for the Navigation_Config instantiation -- GNAT crashes if the call is made in the instantiation part. Nav : constant ASF.Navigations.Navigation_Handler_Access := App.Get_Navigation_Handler; package Bean_Config is new ASF.Beans.Mappers.Reader_Config (Mapper, App.Factory'Access, Context.all'Access); package Navigation_Config is new ASF.Navigations.Mappers.Reader_Config (Mapper, Nav, Context.all'Access); package Servlet_Config is new Servlet.Core.Mappers.Reader_Config (Mapper, App.all'Access, Context.all'Access); package Faces_Config is new ASF.Servlets.Faces.Mappers.Reader_Config (Mapper, App.all'Access, Context.all'Access); pragma Warnings (Off, Bean_Config); pragma Warnings (Off, Navigation_Config); pragma Warnings (Off, Faces_Config); Config : aliased Application_Config; NS_Mapper : aliased EL.Functions.Namespaces.NS_Function_Mapper; procedure Set_Property_Context (Params : in Util.Properties.Manager'Class) is begin Prop_Context.Set_Properties (Params); end Set_Property_Context; begin -- Install the property context that gives access -- to the application configuration properties App.Get_Init_Parameters (Set_Property_Context'Access); Context.Set_Resolver (Prop_Context'Unchecked_Access); -- Setup the function mapper to resolve uses of functions within EL expressions. NS_Mapper.Set_Namespace (Prefix => "fn", URI => ASF.Views.Nodes.Core.FN_URI); NS_Mapper.Set_Function_Mapper (App.Functions'Unchecked_Access); Context.Set_Function_Mapper (NS_Mapper'Unchecked_Access); Mapper.Add_Mapping ("faces-config", AMapper'Access); Mapper.Add_Mapping ("module", AMapper'Access); Mapper.Add_Mapping ("web-app", AMapper'Access); Config.App := App; Servlet_Config.Config.Override_Context := Override_Context; Application_Mapper.Set_Context (Mapper, Config'Unchecked_Access); end Reader_Config; -- ------------------------------ -- Read the configuration file associated with the application. This includes: -- <ul> -- <li>The servlet and filter mappings</li> -- <li>The managed bean definitions</li> -- <li>The navigation rules</li> -- </ul> -- ------------------------------ procedure Read_Configuration (App : in out Application'Class; File : in String) is Reader : Util.Serialize.IO.XML.Parser; Mapper : Util.Serialize.Mappers.Processing; Context : aliased EL.Contexts.Default.Default_Context; -- Setup the <b>Reader</b> to parse and build the configuration for managed beans, -- navigation rules, servlet rules. Each package instantiation creates a local variable -- used while parsing the XML file. package Config is new Reader_Config (Mapper, App'Unchecked_Access, Context'Unchecked_Access); pragma Warnings (Off, Config); begin Log.Info ("Reading module configuration file {0}", File); -- Util.Serialize.IO.Dump (Reader, AWA.Modules.Log); -- Read the configuration file and record managed beans, navigation rules. Reader.Parse (File, Mapper); end Read_Configuration; -- ------------------------------ -- Create the configuration parameter definition instance. -- ------------------------------ package body Parameter is PARAM_NAME : aliased constant String := Name; PARAM_VALUE : aliased constant String := Default; 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; begin AMapper.Add_Mapping ("application/message-bundle/@var", TAG_MESSAGE_VAR); AMapper.Add_Mapping ("application/message-bundle", TAG_MESSAGE_BUNDLE); AMapper.Add_Mapping ("application/locale-config/default-locale", TAG_DEFAULT_LOCALE); AMapper.Add_Mapping ("application/locale-config/supported-locale", TAG_SUPPORTED_LOCALE); end ASF.Applications.Main.Configs;
----------------------------------------------------------------------- -- applications-main-configs -- Configuration support for ASF Applications -- Copyright (C) 2009, 2010, 2011, 2012, 2013, 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 Util.Log.Loggers; with Util.Serialize.IO.XML; with EL.Functions.Namespaces; with ASF.Navigations; with ASF.Navigations.Mappers; with Servlet.Core.Mappers; with ASF.Servlets.Faces.Mappers; with ASF.Beans.Mappers; with ASF.Views.Nodes.Core; package body ASF.Applications.Main.Configs is use Util.Log; -- The logger Log : constant Loggers.Logger := Loggers.Create ("ASF.Applications.Main.Configs"); function Get_Locale (Value : in Util.Beans.Objects.Object) return Util.Locales.Locale; function Get_Locale (Value : in Util.Beans.Objects.Object) return Util.Locales.Locale is Name : constant String := Util.Beans.Objects.To_String (Value); Locale : constant Util.Locales.Locale := Util.Locales.Get_Locale (Name); begin return Locale; end Get_Locale; -- ------------------------------ -- Save in the application config object the value associated with the given field. -- When the <b>TAG_MESSAGE_BUNDLE</b> field is reached, insert the new bundle definition -- in the application. -- ------------------------------ procedure Set_Member (N : in out Application_Config; Field : in Application_Fields; Value : in Util.Beans.Objects.Object) is begin case Field is when TAG_MESSAGE_VAR => N.Name := Value; when TAG_MESSAGE_BUNDLE => declare Bundle : constant String := Util.Beans.Objects.To_String (Value); begin if Util.Beans.Objects.Is_Null (N.Name) then N.App.Register (Name => Bundle & "Msg", Bundle => Bundle); else N.App.Register (Name => Util.Beans.Objects.To_String (N.Name), Bundle => Bundle); end if; N.Name := Util.Beans.Objects.Null_Object; end; when TAG_DEFAULT_LOCALE => N.App.Set_Default_Locale (Get_Locale (Value)); when TAG_SUPPORTED_LOCALE => N.App.Add_Supported_Locale (Get_Locale (Value)); end case; end Set_Member; AMapper : aliased Application_Mapper.Mapper; -- ------------------------------ -- Setup the XML parser to read the managed bean definitions. -- By instantiating this package, the <b>Reader</b> gets populated with the XML mappings -- to read the servlet, managed beans and navigation rules. -- ------------------------------ package body Reader_Config is procedure Set_Property_Context (Params : in Util.Properties.Manager'Class); -- Get the navigation handler for the Navigation_Config instantiation -- GNAT crashes if the call is made in the instantiation part. Nav : constant ASF.Navigations.Navigation_Handler_Access := App.Get_Navigation_Handler; package Bean_Config is new ASF.Beans.Mappers.Reader_Config (Mapper, App.Factory'Access, Context.all'Access); package Navigation_Config is new ASF.Navigations.Mappers.Reader_Config (Mapper, Nav, Context.all'Access); package Servlet_Config is new Servlet.Core.Mappers.Reader_Config (Mapper, App.all'Access, Context.all'Access); package Faces_Config is new ASF.Servlets.Faces.Mappers.Reader_Config (Mapper, App.all'Access, Context.all'Access); pragma Warnings (Off, Bean_Config); pragma Warnings (Off, Navigation_Config); pragma Warnings (Off, Faces_Config); Config : aliased Application_Config; NS_Mapper : aliased EL.Functions.Namespaces.NS_Function_Mapper; procedure Set_Property_Context (Params : in Util.Properties.Manager'Class) is begin Prop_Context.Set_Properties (Params); end Set_Property_Context; begin -- Install the property context that gives access -- to the application configuration properties App.Get_Init_Parameters (Set_Property_Context'Access); Context.Set_Resolver (Prop_Context'Unchecked_Access); -- Setup the function mapper to resolve uses of functions within EL expressions. NS_Mapper.Set_Namespace (Prefix => "fn", URI => ASF.Views.Nodes.Core.FN_URI); NS_Mapper.Set_Function_Mapper (App.Functions'Unchecked_Access); Context.Set_Function_Mapper (NS_Mapper'Unchecked_Access); Mapper.Add_Mapping ("faces-config", AMapper'Access); Mapper.Add_Mapping ("module", AMapper'Access); Mapper.Add_Mapping ("web-app", AMapper'Access); Config.App := App; Servlet_Config.Config.Override_Context := Override_Context; Application_Mapper.Set_Context (Mapper, Config'Unchecked_Access); end Reader_Config; -- ------------------------------ -- Read the configuration file associated with the application. This includes: -- <ul> -- <li>The servlet and filter mappings</li> -- <li>The managed bean definitions</li> -- <li>The navigation rules</li> -- </ul> -- ------------------------------ procedure Read_Configuration (App : in out Application'Class; File : in String) is Reader : Util.Serialize.IO.XML.Parser; Mapper : Util.Serialize.Mappers.Processing; Context : aliased EL.Contexts.Default.Default_Context; -- Setup the <b>Reader</b> to parse and build the configuration for managed beans, -- navigation rules, servlet rules. Each package instantiation creates a local variable -- used while parsing the XML file. package Config is new Reader_Config (Mapper, App'Unchecked_Access, Context'Unchecked_Access); pragma Warnings (Off, Config); begin Log.Info ("Reading module configuration file {0}", File); -- Util.Serialize.IO.Dump (Reader, AWA.Modules.Log); -- Read the configuration file and record managed beans, navigation rules. Reader.Parse (File, Mapper); end Read_Configuration; -- ------------------------------ -- Create the configuration parameter definition instance. -- ------------------------------ package body Parameter is PARAM_NAME : aliased constant String := Name; PARAM_VALUE : aliased constant String := Default; 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; begin AMapper.Add_Mapping ("application/message-bundle/@var", TAG_MESSAGE_VAR); AMapper.Add_Mapping ("application/message-bundle", TAG_MESSAGE_BUNDLE); AMapper.Add_Mapping ("application/locale-config/default-locale", TAG_DEFAULT_LOCALE); AMapper.Add_Mapping ("application/locale-config/supported-locale", TAG_SUPPORTED_LOCALE); end ASF.Applications.Main.Configs;
Fix compilation warnings
Fix compilation warnings
Ada
apache-2.0
stcarrez/ada-asf,stcarrez/ada-asf,stcarrez/ada-asf
5faa807aff1492fbfda474fb5565eb905d838c39
src/asf-components-widgets-inputs.adb
src/asf-components-widgets-inputs.adb
----------------------------------------------------------------------- -- asf-components-widgets-inputs -- Input widget 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 Ada.Strings.Unbounded; with Ada.Characters.Conversions; with ASF.Models.Selects; with ASF.Components.Base; with ASF.Components.Utils; with ASF.Components.Html.Messages; with ASF.Events.Faces.Actions; with ASF.Applications.Messages.Vectors; with Util.Strings.Transforms; with Util.Beans.Objects; package body ASF.Components.Widgets.Inputs is -- ------------------------------ -- Render the input field title. -- ------------------------------ procedure Render_Title (UI : in UIInput; Name : in String; Writer : in Response_Writer_Access; Context : in out Faces_Context'Class) is Title : constant Util.Beans.Objects.Object := UI.Get_Attribute (Context, "title"); begin Writer.Start_Element ("dt"); Writer.Start_Element ("label"); Writer.Write_Attribute ("for", Name); Writer.Write_Text (Title); Writer.End_Element ("label"); Writer.End_Element ("dt"); end Render_Title; -- ------------------------------ -- Render the input component. Starts the DL/DD list and write the input -- component with the possible associated error message. -- ------------------------------ overriding procedure Encode_Begin (UI : in UIInput; Context : in out Faces_Context'Class) is begin if not UI.Is_Rendered (Context) then return; end if; declare Id : constant String := To_String (UI.Get_Client_Id); Writer : constant Response_Writer_Access := Context.Get_Response_Writer; Messages : constant ASF.Applications.Messages.Vectors.Cursor := Context.Get_Messages (Id); Style : constant String := UI.Get_Attribute ("styleClass", Context); begin Writer.Start_Element ("dl"); Writer.Write_Attribute ("id", Id); if ASF.Applications.Messages.Vectors.Has_Element (Messages) then Writer.Write_Attribute ("class", Style & " asf-error"); elsif Style'Length > 0 then Writer.Write_Attribute ("class", Style); end if; UI.Render_Title (Id, Writer, Context); Writer.Start_Element ("dd"); UI.Render_Input (Context, Write_Id => False); end; end Encode_Begin; -- ------------------------------ -- Render the end of the input component. Closes the DL/DD list. -- ------------------------------ overriding procedure Encode_End (UI : in UIInput; Context : in out Faces_Context'Class) is use ASF.Components.Html.Messages; begin if not UI.Is_Rendered (Context) then return; end if; -- Render the error message associated with the input field. declare Id : constant String := To_String (UI.Get_Client_Id); Writer : constant Response_Writer_Access := Context.Get_Response_Writer; Messages : constant ASF.Applications.Messages.Vectors.Cursor := Context.Get_Messages (Id); begin if ASF.Applications.Messages.Vectors.Has_Element (Messages) then Write_Message (UI, ASF.Applications.Messages.Vectors.Element (Messages), SPAN_NO_STYLE, False, True, Context); end if; Writer.End_Element ("dd"); Writer.End_Element ("dl"); end; end Encode_End; -- ------------------------------ -- Render the end of the input component. Closes the DL/DD list. -- ------------------------------ overriding procedure Encode_End (UI : in UIComplete; Context : in out Faces_Context'Class) is begin if not UI.Is_Rendered (Context) then return; end if; -- Render the autocomplete script and finish the input component. declare Id : constant String := To_String (UI.Get_Client_Id); Writer : constant Response_Writer_Access := Context.Get_Response_Writer; begin Writer.Queue_Script ("$('#"); Writer.Queue_Script (Id); Writer.Queue_Script (" input').complete({"); Writer.Queue_Script ("});"); UIInput (UI).Encode_End (Context); end; end Encode_End; overriding procedure Process_Decodes (UI : in out UIComplete; Context : in out Faces_Context'Class) is begin if not UI.Is_Rendered (Context) then return; end if; declare Id : constant String := To_String (UI.Get_Client_Id); Val : constant String := Context.Get_Parameter (Id & ".match"); begin if Val'Length > 0 then UI.Match_Value := Util.Beans.Objects.To_Object (Val); else ASF.Components.Html.Forms.UIInput (UI).Process_Decodes (Context); end if; end; end Process_Decodes; procedure Render_List (UI : in UIComplete; Match : in String; Context : in out Faces_Context'Class) is use type Util.Beans.Basic.List_Bean_Access; List : constant Util.Beans.Basic.List_Bean_Access := ASF.Components.Utils.Get_List_Bean (UI, "autocompleteList", Context); Writer : constant Response_Writer_Access := Context.Get_Response_Writer; Need_Comma : Boolean := False; Count : Natural; procedure Render_Item (Label : in String) is Result : Ada.Strings.Unbounded.Unbounded_String; begin if Match'Length = 0 or else (Match'Length <= Label'Length and then Match = Label (Label'First .. Label'First + Match'Length - 1)) then if Need_Comma then Writer.Write (","); end if; Writer.Write ('"'); Util.Strings.Transforms.Escape_Java (Content => Label, Into => Result); Writer.Write (Result); Writer.Write ('"'); Need_Comma := True; end if; end Render_Item; begin Writer.Write ('['); if List /= null then Count := List.Get_Count; if List.all in ASF.Models.Selects.Select_Item_List'Class then declare S : constant access ASF.Models.Selects.Select_Item_List'Class := ASF.Models.Selects.Select_Item_List'Class (List.all)'Access; begin for I in 1 .. Count loop Render_Item (Ada.Characters.Conversions.To_String (S.Get_Select_Item (I).Get_Label)); end loop; end; else for I in 1 .. Count loop List.Set_Row_Index (I); declare Value : constant Util.Beans.Objects.Object := List.Get_Row; Label : constant String := Util.Beans.Objects.To_String (Value); begin Render_Item (Label); end; end loop; end if; end if; Writer.Write (']'); end Render_List; overriding procedure Process_Updates (UI : in out UIComplete; Context : in out Faces_Context'Class) is begin if not Util.Beans.Objects.Is_Empty (UI.Match_Value) then declare Value : constant access ASF.Views.Nodes.Tag_Attribute := UI.Get_Attribute ("match"); ME : EL.Expressions.Method_Expression; begin if Value /= null then declare VE : constant EL.Expressions.Value_Expression := ASF.Views.Nodes.Get_Value_Expression (Value.all); begin VE.Set_Value (Value => UI.Match_Value, Context => Context.Get_ELContext.all); end; end if; -- Post an event on this component to trigger the rendering of the completion -- list as part of an application/json output. The rendering is made by Broadcast. ASF.Events.Faces.Actions.Post_Event (UI => UI, Method => ME); end; else ASF.Components.Html.Forms.UIInput (UI).Process_Updates (Context); end if; -- exception -- when E : others => -- UI.Is_Valid := False; -- UI.Add_Message (CONVERTER_MESSAGE_NAME, "convert", Context); -- Log.Info (Utils.Get_Line_Info (UI) -- & ": Exception raised when updating value {0} for component {1}: {2}", -- EL.Objects.To_String (UI.Submitted_Value), -- To_String (UI.Get_Client_Id), Ada.Exceptions.Exception_Name (E)); end Process_Updates; -- ------------------------------ -- Broadcast the event to the event listeners installed on this component. -- Listeners are called in the order in which they were added. -- ------------------------------ overriding procedure Broadcast (UI : in out UIComplete; Event : not null access ASF.Events.Faces.Faces_Event'Class; Context : in out Faces_Context'Class) is pragma Unreferenced (Event); Match : constant String := Util.Beans.Objects.To_String (UI.Match_Value); begin Context.Get_Response.Set_Content_Type ("application/json; charset=UTF-8"); UI.Render_List (Match, Context); Context.Response_Completed; end Broadcast; end ASF.Components.Widgets.Inputs;
----------------------------------------------------------------------- -- asf-components-widgets-inputs -- Input widget 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 Ada.Strings.Unbounded; with Ada.Characters.Conversions; with ASF.Models.Selects; with ASF.Components.Utils; with ASF.Components.Html.Messages; with ASF.Events.Faces.Actions; with ASF.Applications.Messages.Vectors; with Util.Beans.Basic; with Util.Strings.Transforms; package body ASF.Components.Widgets.Inputs is -- ------------------------------ -- Render the input field title. -- ------------------------------ procedure Render_Title (UI : in UIInput; Name : in String; Writer : in Response_Writer_Access; Context : in out Faces_Context'Class) is Title : constant Util.Beans.Objects.Object := UI.Get_Attribute (Context, "title"); begin Writer.Start_Element ("dt"); Writer.Start_Element ("label"); Writer.Write_Attribute ("for", Name); Writer.Write_Text (Title); Writer.End_Element ("label"); Writer.End_Element ("dt"); end Render_Title; -- ------------------------------ -- Render the input component. Starts the DL/DD list and write the input -- component with the possible associated error message. -- ------------------------------ overriding procedure Encode_Begin (UI : in UIInput; Context : in out Faces_Context'Class) is begin if not UI.Is_Rendered (Context) then return; end if; declare Id : constant String := To_String (UI.Get_Client_Id); Writer : constant Response_Writer_Access := Context.Get_Response_Writer; Messages : constant ASF.Applications.Messages.Vectors.Cursor := Context.Get_Messages (Id); Style : constant String := UI.Get_Attribute ("styleClass", Context); begin Writer.Start_Element ("dl"); Writer.Write_Attribute ("id", Id); if ASF.Applications.Messages.Vectors.Has_Element (Messages) then Writer.Write_Attribute ("class", Style & " asf-error"); elsif Style'Length > 0 then Writer.Write_Attribute ("class", Style); end if; UI.Render_Title (Id, Writer, Context); Writer.Start_Element ("dd"); UI.Render_Input (Context, Write_Id => False); end; end Encode_Begin; -- ------------------------------ -- Render the end of the input component. Closes the DL/DD list. -- ------------------------------ overriding procedure Encode_End (UI : in UIInput; Context : in out Faces_Context'Class) is use ASF.Components.Html.Messages; begin if not UI.Is_Rendered (Context) then return; end if; -- Render the error message associated with the input field. declare Id : constant String := To_String (UI.Get_Client_Id); Writer : constant Response_Writer_Access := Context.Get_Response_Writer; Messages : constant ASF.Applications.Messages.Vectors.Cursor := Context.Get_Messages (Id); begin if ASF.Applications.Messages.Vectors.Has_Element (Messages) then Write_Message (UI, ASF.Applications.Messages.Vectors.Element (Messages), SPAN_NO_STYLE, False, True, Context); end if; Writer.End_Element ("dd"); Writer.End_Element ("dl"); end; end Encode_End; -- ------------------------------ -- Render the end of the input component. Closes the DL/DD list. -- ------------------------------ overriding procedure Encode_End (UI : in UIComplete; Context : in out Faces_Context'Class) is begin if not UI.Is_Rendered (Context) then return; end if; -- Render the autocomplete script and finish the input component. declare Id : constant String := To_String (UI.Get_Client_Id); Writer : constant Response_Writer_Access := Context.Get_Response_Writer; begin Writer.Queue_Script ("$('#"); Writer.Queue_Script (Id); Writer.Queue_Script (" input').complete({"); Writer.Queue_Script ("});"); UIInput (UI).Encode_End (Context); end; end Encode_End; overriding procedure Process_Decodes (UI : in out UIComplete; Context : in out Faces_Context'Class) is begin if not UI.Is_Rendered (Context) then return; end if; declare Id : constant String := To_String (UI.Get_Client_Id); Val : constant String := Context.Get_Parameter (Id & ".match"); begin if Val'Length > 0 then UI.Match_Value := Util.Beans.Objects.To_Object (Val); else ASF.Components.Html.Forms.UIInput (UI).Process_Decodes (Context); end if; end; end Process_Decodes; procedure Render_List (UI : in UIComplete; Match : in String; Context : in out Faces_Context'Class) is use type Util.Beans.Basic.List_Bean_Access; procedure Render_Item (Label : in String); List : constant Util.Beans.Basic.List_Bean_Access := ASF.Components.Utils.Get_List_Bean (UI, "autocompleteList", Context); Writer : constant Response_Writer_Access := Context.Get_Response_Writer; Need_Comma : Boolean := False; Count : Natural; procedure Render_Item (Label : in String) is Result : Ada.Strings.Unbounded.Unbounded_String; begin if Match'Length = 0 or else (Match'Length <= Label'Length and then Match = Label (Label'First .. Label'First + Match'Length - 1)) then if Need_Comma then Writer.Write (","); end if; Writer.Write ('"'); Util.Strings.Transforms.Escape_Java (Content => Label, Into => Result); Writer.Write (Result); Writer.Write ('"'); Need_Comma := True; end if; end Render_Item; begin Writer.Write ('['); if List /= null then Count := List.Get_Count; if List.all in ASF.Models.Selects.Select_Item_List'Class then declare S : constant access ASF.Models.Selects.Select_Item_List'Class := ASF.Models.Selects.Select_Item_List'Class (List.all)'Access; begin for I in 1 .. Count loop Render_Item (Ada.Characters.Conversions.To_String (S.Get_Select_Item (I).Get_Label)); end loop; end; else for I in 1 .. Count loop List.Set_Row_Index (I); declare Value : constant Util.Beans.Objects.Object := List.Get_Row; Label : constant String := Util.Beans.Objects.To_String (Value); begin Render_Item (Label); end; end loop; end if; end if; Writer.Write (']'); end Render_List; overriding procedure Process_Updates (UI : in out UIComplete; Context : in out Faces_Context'Class) is begin if not Util.Beans.Objects.Is_Empty (UI.Match_Value) then declare Value : constant access ASF.Views.Nodes.Tag_Attribute := UI.Get_Attribute ("match"); ME : EL.Expressions.Method_Expression; begin if Value /= null then declare VE : constant EL.Expressions.Value_Expression := ASF.Views.Nodes.Get_Value_Expression (Value.all); begin VE.Set_Value (Value => UI.Match_Value, Context => Context.Get_ELContext.all); end; end if; -- Post an event on this component to trigger the rendering of the completion -- list as part of an application/json output. The rendering is made by Broadcast. ASF.Events.Faces.Actions.Post_Event (UI => UI, Method => ME); end; else ASF.Components.Html.Forms.UIInput (UI).Process_Updates (Context); end if; -- exception -- when E : others => -- UI.Is_Valid := False; -- UI.Add_Message (CONVERTER_MESSAGE_NAME, "convert", Context); -- Log.Info (Utils.Get_Line_Info (UI) -- & ": Exception raised when updating value {0} for component {1}: {2}", -- EL.Objects.To_String (UI.Submitted_Value), -- To_String (UI.Get_Client_Id), Ada.Exceptions.Exception_Name (E)); end Process_Updates; -- ------------------------------ -- Broadcast the event to the event listeners installed on this component. -- Listeners are called in the order in which they were added. -- ------------------------------ overriding procedure Broadcast (UI : in out UIComplete; Event : not null access ASF.Events.Faces.Faces_Event'Class; Context : in out Faces_Context'Class) is pragma Unreferenced (Event); Match : constant String := Util.Beans.Objects.To_String (UI.Match_Value); begin Context.Get_Response.Set_Content_Type ("application/json; charset=UTF-8"); UI.Render_List (Match, Context); Context.Response_Completed; end Broadcast; -- ------------------------------ -- Render the end of the input date component. -- Generate the javascript code to activate the input date selector -- and closes the DL/DD list. -- ------------------------------ overriding procedure Encode_End (UI : in UIInputDate; Context : in out Faces_Context'Class) is use ASF.Components.Html.Messages; begin if not UI.Is_Rendered (Context) then return; end if; -- Render the input date script and finish the input component. declare Id : constant String := To_String (UI.Get_Client_Id); Writer : constant Response_Writer_Access := Context.Get_Response_Writer; Format : constant String := UI.Get_Attribute ("dateFormat", Context); begin Writer.Queue_Script ("$('#"); Writer.Queue_Script (Id); Writer.Queue_Script (" input').datepicker({"); if Format'Length > 0 then Writer.Queue_Script ("dateFormat: """); Writer.Queue_Script (Format); Writer.Queue_Script (""""); end if; Writer.Queue_Script ("});"); UIInput (UI).Encode_End (Context); end; end Encode_End; end ASF.Components.Widgets.Inputs;
Implement the inputDate component. Render the input field and write the javascript code to activate the jQuery date picker.
Implement the inputDate component. Render the input field and write the javascript code to activate the jQuery date picker.
Ada
apache-2.0
Letractively/ada-asf,Letractively/ada-asf,Letractively/ada-asf
59f1917d71219f5c42c5d59d2684bbfb603bb669
src/security-controllers.ads
src/security-controllers.ads
----------------------------------------------------------------------- -- security-controllers -- Controllers to verify a security permission -- 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 Security.Contexts; with Security.Permissions; -- == Security Controller == -- The <b>Security.Controllers</b> package defines the security controller used to -- verify that a given permission is granted. A security controller uses the security -- context and other controller specific and internal data to verify that the permission -- is granted. -- -- To implement a new security controller, one must: -- -- * Define a type that implements the <b>Controller</b> interface with the -- <b>Has_Permission</b> operation -- * Write a function to allocate instances of the given <b>Controller</b> type -- * Register the function under a unique name by using <b>Register_Controller</b> -- -- Security controller instances are created when the security policy rules are parsed. -- These instances are shared across possibly several concurrent requests. package Security.Controllers is Invalid_Controller : exception; -- ------------------------------ -- Security Controller interface -- ------------------------------ type Controller is limited interface; type Controller_Access is access all Controller'Class; -- Checks whether the permission defined by the <b>Handler</b> controller data is granted -- by the security context passed in <b>Context</b>. -- Returns true if such permission is granted. function Has_Permission (Handler : in Controller; Context : in Security.Contexts.Security_Context'Class; Permission : in Security.Permissions.Permission'Class) return Boolean is abstract; type Controller_Factory is not null access function return Controller_Access; -- To keep this implementation simple, a maximum of 32 security controller factory -- can be registered. ASF provides one based on roles. AWA provides another one -- based on entity ACLs. MAX_CONTROLLER_FACTORY : constant Positive := 32; -- Register in a global table the controller factory under the name <b>Name</b>. -- When this factory is used, the <b>Factory</b> operation will be called to -- create new instances of the controller. procedure Register_Controller (Name : in String; Factory : in Controller_Factory); -- Create a security controller by using the controller factory registered under -- the name <b>Name</b>. -- Raises <b>Invalid_Controller</b> if the name is not recognized. function Create_Controller (Name : in String) return Controller_Access; end Security.Controllers;
----------------------------------------------------------------------- -- security-controllers -- Controllers to verify a security permission -- 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 Security.Contexts; with Security.Permissions; -- == Security Controller == -- The <b>Security.Controllers</b> package defines the security controller used to -- verify that a given permission is granted. A security controller uses the security -- context and other controller specific and internal data to verify that the permission -- is granted. -- -- To implement a new security controller, one must: -- -- * Define a type that implements the <b>Controller</b> interface with the -- <b>Has_Permission</b> operation -- * Write a function to allocate instances of the given <b>Controller</b> type -- * Register the function under a unique name by using <b>Register_Controller</b> -- -- Security controller instances are created when the security policy rules are parsed. -- These instances are shared across possibly several concurrent requests. package Security.Controllers is Invalid_Controller : exception; -- ------------------------------ -- Security Controller interface -- ------------------------------ type Controller is limited interface; type Controller_Access is access all Controller'Class; -- Checks whether the permission defined by the <b>Handler</b> controller data is granted -- by the security context passed in <b>Context</b>. -- Returns true if such permission is granted. function Has_Permission (Handler : in Controller; Context : in Security.Contexts.Security_Context'Class; Permission : in Security.Permissions.Permission'Class) return Boolean is abstract; end Security.Controllers;
Remove the Controller_Factory which is not used
Remove the Controller_Factory which is not used
Ada
apache-2.0
Letractively/ada-security
a42e0536ae6dbf39350237aeeeb0b208f8052acd
src/ado-configs.ads
src/ado-configs.ads
----------------------------------------------------------------------- -- ado-configs -- Database connection configuration -- Copyright (C) 2010, 2011, 2012, 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.Finalization; with Util.Properties; package ADO.Configs is -- Configuration property to control the search paths to load XML queries. QUERY_PATHS_CONFIG : constant String := "ado.queries.paths"; -- Configuration property to control whether all the program XML queries must be -- loaded when the database configuration is setup. QUERY_LOAD_CONFIG : constant String := "ado.queries.load"; -- Configuration property to enable or disable the dynamic load of database driver. DYNAMIC_DRIVER_LOAD : constant String := "ado.drivers.load"; -- Configuration property to skip reading the database table entities. NO_ENTITY_LOAD : constant String := "ado.entities.ignore"; -- Raised when the connection URI is invalid. Connection_Error : exception; -- ------------------------------ -- The database configuration properties -- ------------------------------ type Configuration is new Ada.Finalization.Controlled with private; type Configuration_Access is access all Configuration'Class; -- Set the connection URL to connect to the database. -- The driver connection is a string of the form: -- -- driver://[host][:port]/[database][?property1][=value1]... -- -- If the string is invalid or if the driver cannot be found, -- the Connection_Error exception is raised. procedure Set_Connection (Config : in out Configuration; URI : in String); -- Get the connection URI that describes the database connection string. -- The returned string may contain connection authentication information. function Get_URI (Config : in Configuration) return String; -- Get the connection URI that describes the database connection string -- but the connection authentication is replaced by XXXX. function Get_Log_URI (Config : in Configuration) return String; -- Set a property on the datasource for the driver. -- The driver can retrieve the property to configure and open -- the database connection. procedure Set_Property (Config : in out Configuration; Name : in String; Value : in String); -- Get a property from the data source configuration. -- If the property does not exist, an empty string is returned. function Get_Property (Config : in Configuration; Name : in String) return String; -- Returns true if the configuration property is set to true/on. function Is_On (Config : in Configuration; Name : in String) return Boolean; -- Set the server hostname. procedure Set_Server (Config : in out Configuration; Server : in String); -- Get the server hostname. function Get_Server (Config : in Configuration) return String; -- Set the server port. procedure Set_Port (Config : in out Configuration; Port : in Natural); -- Get the server port. function Get_Port (Config : in Configuration) return Natural; -- Set the database name. procedure Set_Database (Config : in out Configuration; Database : in String); -- Get the database name. function Get_Database (Config : in Configuration) return String; -- Get the database driver name. function Get_Driver (Config : in Configuration) return String; -- Iterate over the configuration properties and execute the given procedure passing the -- property name and its value. procedure Iterate (Config : in Configuration; Process : access procedure (Name : in String; Item : in Util.Properties.Value)); private use Ada.Strings.Unbounded; type Configuration is new Ada.Finalization.Controlled with record URI : Unbounded_String; Log_URI : Unbounded_String; Driver : Unbounded_String; Server : Unbounded_String; Port : Natural := 0; Database : Unbounded_String; Properties : Util.Properties.Manager; end record; end ADO.Configs;
----------------------------------------------------------------------- -- ado-configs -- Database connection configuration -- Copyright (C) 2010, 2011, 2012, 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.Finalization; with Util.Properties; package ADO.Configs is -- Configuration property to control the search paths to load XML queries. QUERY_PATHS_CONFIG : constant String := "ado.queries.paths"; -- Configuration property to control whether all the program XML queries must be -- loaded when the database configuration is setup. QUERY_LOAD_CONFIG : constant String := "ado.queries.load"; -- Configuration property to enable or disable the dynamic load of database driver. DYNAMIC_DRIVER_LOAD : constant String := "ado.drivers.load"; -- Configuration property to skip reading the database table entities. NO_ENTITY_LOAD : constant String := "ado.entities.ignore"; -- Maximum number of columns allowed for a table (SQLite limit is 2000). MAX_COLUMNS : constant := 2000; -- Raised when the connection URI is invalid. Connection_Error : exception; -- ------------------------------ -- The database configuration properties -- ------------------------------ type Configuration is new Ada.Finalization.Controlled with private; type Configuration_Access is access all Configuration'Class; -- Set the connection URL to connect to the database. -- The driver connection is a string of the form: -- -- driver://[host][:port]/[database][?property1][=value1]... -- -- If the string is invalid or if the driver cannot be found, -- the Connection_Error exception is raised. procedure Set_Connection (Config : in out Configuration; URI : in String); -- Get the connection URI that describes the database connection string. -- The returned string may contain connection authentication information. function Get_URI (Config : in Configuration) return String; -- Get the connection URI that describes the database connection string -- but the connection authentication is replaced by XXXX. function Get_Log_URI (Config : in Configuration) return String; -- Set a property on the datasource for the driver. -- The driver can retrieve the property to configure and open -- the database connection. procedure Set_Property (Config : in out Configuration; Name : in String; Value : in String); -- Get a property from the data source configuration. -- If the property does not exist, an empty string is returned. function Get_Property (Config : in Configuration; Name : in String) return String; -- Returns true if the configuration property is set to true/on. function Is_On (Config : in Configuration; Name : in String) return Boolean; -- Set the server hostname. procedure Set_Server (Config : in out Configuration; Server : in String); -- Get the server hostname. function Get_Server (Config : in Configuration) return String; -- Set the server port. procedure Set_Port (Config : in out Configuration; Port : in Natural); -- Get the server port. function Get_Port (Config : in Configuration) return Natural; -- Set the database name. procedure Set_Database (Config : in out Configuration; Database : in String); -- Get the database name. function Get_Database (Config : in Configuration) return String; -- Get the database driver name. function Get_Driver (Config : in Configuration) return String; -- Iterate over the configuration properties and execute the given procedure passing the -- property name and its value. procedure Iterate (Config : in Configuration; Process : access procedure (Name : in String; Item : in Util.Properties.Value)); private use Ada.Strings.Unbounded; type Configuration is new Ada.Finalization.Controlled with record URI : Unbounded_String; Log_URI : Unbounded_String; Driver : Unbounded_String; Server : Unbounded_String; Port : Natural := 0; Database : Unbounded_String; Properties : Util.Properties.Manager; end record; end ADO.Configs;
Declare MAX_COLUMNS constant, use SQLite limit, 2000
Declare MAX_COLUMNS constant, use SQLite limit, 2000
Ada
apache-2.0
stcarrez/ada-ado
d6b87ff63a7142dcc96975e9318f97d84a7bd75d
src/ado-queries.ads
src/ado-queries.ads
----------------------------------------------------------------------- -- ado-queries -- Database Queries -- Copyright (C) 2009, 2010, 2011, 2012, 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.Strings; with Util.Refs; with ADO.SQL; with ADO.Drivers; with Interfaces; with Ada.Strings.Unbounded; package ADO.Queries is type Query_File; type Query_File_Access is access all Query_File; type Query_Definition; type Query_Definition_Access is access all Query_Definition; type Query_Info is limited private; type Query_Info_Access is access all Query_Info; type Query_Info_Ref_Access is private; Null_Query_Info_Ref : constant Query_Info_Ref_Access; -- ------------------------------ -- Query Context -- ------------------------------ -- The <b>Context</b> type holds the necessary information to build and execute -- a query whose SQL pattern is defined in an XML query file. type Context is new ADO.SQL.Query with private; -- Set the query definition which identifies the SQL query to execute. -- The query is represented by the <tt>sql</tt> XML entry. procedure Set_Query (Into : in out Context; Query : in Query_Definition_Access); -- Set the query count definition which identifies the SQL query to execute. -- The query count is represented by the <tt>sql-count</tt> XML entry. procedure Set_Count_Query (Into : in out Context; Query : in Query_Definition_Access); -- Set the query to execute as SQL statement. procedure Set_SQL (Into : in out Context; SQL : in String); procedure Set_Query (Into : in out Context; Name : in String); -- Set the limit for the SQL query. procedure Set_Limit (Into : in out Context; First : in Natural; Last : in Natural); -- Get the first row index. function Get_First_Row_Index (From : in Context) return Natural; -- Get the last row index. function Get_Last_Row_Index (From : in Context) return Natural; -- Get the maximum number of rows that the SQL query can return. -- This operation uses the <b>sql-count</b> query. function Get_Max_Row_Count (From : in Context) return Natural; -- Get the SQL query that correspond to the query context. function Get_SQL (From : in Context; Driver : in ADO.Drivers.Driver_Index) return String; -- ------------------------------ -- Query Definition -- ------------------------------ -- The <b>Query_Definition</b> holds the SQL query pattern which is defined -- in an XML query file. The query is identified by a name and a given XML -- query file can contain several queries. The Dynamo generator generates -- one instance of <b>Query_Definition</b> for each query defined in the XML -- file. The XML file is loaded during application initialization (or later) -- to get the SQL query pattern. Multi-thread concurrency is achieved by -- the Query_Info_Ref atomic reference. type Query_Definition is limited record -- The query name. Name : Util.Strings.Name_Access; -- The query file in which the query is defined. File : Query_File_Access; -- The next query defined in the query file. Next : Query_Definition_Access; -- The SQL query pattern (initialized when reading the XML query file). Query : Query_Info_Ref_Access; end record; function Get_SQL (From : in Query_Definition_Access; Driver : in ADO.Drivers.Driver_Index; Use_Count : in Boolean) return String; -- ------------------------------ -- Query File -- ------------------------------ -- The <b>Query_File</b> describes the SQL queries associated and loaded from -- a given XML query file. The Dynamo generator generates one instance of -- <b>Query_File</b> for each XML query file that it has read. The Path, -- Sha1_Map, Queries and Next are initialized statically by the generator (during -- package elaboration). type Query_File is limited record -- Query relative path name Name : Util.Strings.Name_Access; -- Query absolute path name (after path resolution). Path : Ada.Strings.Unbounded.String_Access; -- The SHA1 hash of the query map section. Sha1_Map : Util.Strings.Name_Access; -- Stamp when the query file will be checked. Next_Check : Interfaces.Unsigned_32; -- Stamp identifying the modification date of the query file. Last_Modified : Interfaces.Unsigned_32; -- The first query defined for that file. Queries : Query_Definition_Access; -- The next XML query file registered in the application. Next : Query_File_Access; end record; private type Context is new ADO.SQL.Query with record First : Natural := 0; Last : Natural := 0; Last_Index : Natural := 0; Max_Row_Count : Natural := 0; Query_Def : Query_Definition_Access := null; Is_Count : Boolean := False; end record; -- Find the query with the given name. -- Returns the query definition that matches the name or null if there is none function Find_Query (File : in Query_File; Name : in String) return Query_Definition_Access; use Ada.Strings.Unbounded; -- SQL query pattern type Query_Pattern is limited record SQL : Ada.Strings.Unbounded.Unbounded_String; end record; type Query_Pattern_Array is array (ADO.Drivers.Driver_Index) of Query_Pattern; type Query_Info is new Util.Refs.Ref_Entity with record Main_Query : Query_Pattern_Array; Count_Query : Query_Pattern_Array; end record; package Query_Info_Ref is new Util.Refs.References (Query_Info, Query_Info_Access); type Query_Info_Ref_Access is access all Query_Info_Ref.Atomic_Ref; Null_Query_Info_Ref : constant Query_Info_Ref_Access := null; end ADO.Queries;
----------------------------------------------------------------------- -- ado-queries -- Database Queries -- Copyright (C) 2009, 2010, 2011, 2012, 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.Strings; with Util.Refs; with ADO.SQL; with ADO.Drivers; with Interfaces; with Ada.Strings.Unbounded; -- == Introduction == -- Ada Database Objects provides a small framework which helps in -- using complex SQL queries in an application. -- The benefit of the framework are the following: -- -- * The SQL query result are directly mapped in Ada records, -- * It is easy to change or tune an SQL query without re-building the application, -- * The SQL query can be easily tuned for a given database -- -- The database query framework uses an XML query file: -- -- * The XML query file defines a mapping that represents the result of SQL queries, -- * The XML mapping is used by [http://code.google.com/p/ada-gen Dynamo] to generate an Ada record, -- * The XML query file also defines a set of SQL queries, each query being identified by a unique name, -- * The XML query file is read by the application to obtain the SQL query associated with a query name, -- * The application uses the `List` procedure generated by [http://code.google.com/p/ada-gen Dynamo]. -- -- == XML Query File and Mapping == -- === XML Query File === -- The XML query file uses the `query-mapping` root element. It should -- define at most one `class` mapping and several `query` definitions. -- The `class` definition should come first before any `query` definition. -- -- <query-mapping> -- <class>...</class> -- <query>...</query> -- </query-mapping> -- -- == SQL Result Mapping == -- The XML query mapping is very close to the database table mapping. -- The difference is that there is no need to specify and table name -- nor any SQL type. The XML query mapping is used to build an Ada -- record that correspond to query results. Unlike the database table mapping, -- the Ada record will not be tagged and its definition will expose all the record -- members directly. -- -- The following XML query mapping: -- -- <query-mapping> -- <class name='Samples.Model.User_Info'> -- <property name="name" type="String"> -- <comment>the user name</comment> -- </property> -- <property name="email" type="String"> -- <comment>the email address</comment> -- </property> -- </class> -- </query-mapping> -- -- will generate the following Ada record: -- -- package Samples.Model is -- type User_Info is record -- Name : Unbounded_String; -- Email : Unbounded_String; -- end record; -- end Samples.Model; -- -- The same query mapping can be used by different queries. -- -- === SQL Queries === -- The XML query file defines a list of SQL queries that the application -- can use. Each query is associated with a unique name. The application -- will use that name to identify the SQL query to execute. For each query, -- the file also describes the SQL query pattern that must be used for -- the query execution. -- -- <query name='xxx' class='Samples.Model.User_Info'> -- <sql driver='mysql'> -- select u.name, u.email from user -- </sql> -- <sql driver='sqlite'> -- ... -- </sql> -- <sql-count driver='mysql'> -- select count(*) from user u -- </sql-count> -- </query> -- -- The query contains basically two SQL patterns. The `sql` element represents -- the main SQL pattern. This is the SQL that is used by the `List` operation. -- In some cases, the result set returned by the query is limited to return only -- a maximum number of rows. This is often use in paginated lists. -- -- The `sql-count` element represents an SQL query to indicate the total number -- of elements if the SQL query was not limited. package ADO.Queries is type Query_File; type Query_File_Access is access all Query_File; type Query_Definition; type Query_Definition_Access is access all Query_Definition; type Query_Info is limited private; type Query_Info_Access is access all Query_Info; type Query_Info_Ref_Access is private; Null_Query_Info_Ref : constant Query_Info_Ref_Access; -- ------------------------------ -- Query Context -- ------------------------------ -- The <b>Context</b> type holds the necessary information to build and execute -- a query whose SQL pattern is defined in an XML query file. type Context is new ADO.SQL.Query with private; -- Set the query definition which identifies the SQL query to execute. -- The query is represented by the <tt>sql</tt> XML entry. procedure Set_Query (Into : in out Context; Query : in Query_Definition_Access); -- Set the query count definition which identifies the SQL query to execute. -- The query count is represented by the <tt>sql-count</tt> XML entry. procedure Set_Count_Query (Into : in out Context; Query : in Query_Definition_Access); -- Set the query to execute as SQL statement. procedure Set_SQL (Into : in out Context; SQL : in String); procedure Set_Query (Into : in out Context; Name : in String); -- Set the limit for the SQL query. procedure Set_Limit (Into : in out Context; First : in Natural; Last : in Natural); -- Get the first row index. function Get_First_Row_Index (From : in Context) return Natural; -- Get the last row index. function Get_Last_Row_Index (From : in Context) return Natural; -- Get the maximum number of rows that the SQL query can return. -- This operation uses the <b>sql-count</b> query. function Get_Max_Row_Count (From : in Context) return Natural; -- Get the SQL query that correspond to the query context. function Get_SQL (From : in Context; Driver : in ADO.Drivers.Driver_Index) return String; -- ------------------------------ -- Query Definition -- ------------------------------ -- The <b>Query_Definition</b> holds the SQL query pattern which is defined -- in an XML query file. The query is identified by a name and a given XML -- query file can contain several queries. The Dynamo generator generates -- one instance of <b>Query_Definition</b> for each query defined in the XML -- file. The XML file is loaded during application initialization (or later) -- to get the SQL query pattern. Multi-thread concurrency is achieved by -- the Query_Info_Ref atomic reference. type Query_Definition is limited record -- The query name. Name : Util.Strings.Name_Access; -- The query file in which the query is defined. File : Query_File_Access; -- The next query defined in the query file. Next : Query_Definition_Access; -- The SQL query pattern (initialized when reading the XML query file). Query : Query_Info_Ref_Access; end record; function Get_SQL (From : in Query_Definition_Access; Driver : in ADO.Drivers.Driver_Index; Use_Count : in Boolean) return String; -- ------------------------------ -- Query File -- ------------------------------ -- The <b>Query_File</b> describes the SQL queries associated and loaded from -- a given XML query file. The Dynamo generator generates one instance of -- <b>Query_File</b> for each XML query file that it has read. The Path, -- Sha1_Map, Queries and Next are initialized statically by the generator (during -- package elaboration). type Query_File is limited record -- Query relative path name Name : Util.Strings.Name_Access; -- Query absolute path name (after path resolution). Path : Ada.Strings.Unbounded.String_Access; -- The SHA1 hash of the query map section. Sha1_Map : Util.Strings.Name_Access; -- Stamp when the query file will be checked. Next_Check : Interfaces.Unsigned_32; -- Stamp identifying the modification date of the query file. Last_Modified : Interfaces.Unsigned_32; -- The first query defined for that file. Queries : Query_Definition_Access; -- The next XML query file registered in the application. Next : Query_File_Access; end record; private type Context is new ADO.SQL.Query with record First : Natural := 0; Last : Natural := 0; Last_Index : Natural := 0; Max_Row_Count : Natural := 0; Query_Def : Query_Definition_Access := null; Is_Count : Boolean := False; end record; -- Find the query with the given name. -- Returns the query definition that matches the name or null if there is none function Find_Query (File : in Query_File; Name : in String) return Query_Definition_Access; use Ada.Strings.Unbounded; -- SQL query pattern type Query_Pattern is limited record SQL : Ada.Strings.Unbounded.Unbounded_String; end record; type Query_Pattern_Array is array (ADO.Drivers.Driver_Index) of Query_Pattern; type Query_Info is new Util.Refs.Ref_Entity with record Main_Query : Query_Pattern_Array; Count_Query : Query_Pattern_Array; end record; package Query_Info_Ref is new Util.Refs.References (Query_Info, Query_Info_Access); type Query_Info_Ref_Access is access all Query_Info_Ref.Atomic_Ref; Null_Query_Info_Ref : constant Query_Info_Ref_Access := null; end ADO.Queries;
Add some documentation
Add some documentation
Ada
apache-2.0
stcarrez/ada-ado
f9564b651d68ad18d3793c119d9e6ce9fdd95742
ravenadm.adb
ravenadm.adb
-- This file is covered by the Internet Software Consortium (ISC) License -- Reference: License.txt with Ada.Command_Line; with Ada.Text_IO; with Parameters; with Pilot; with Unix; procedure Ravenadm is package CLI renames Ada.Command_Line; package TIO renames Ada.Text_IO; type mandate_type is (unset, help, dev, build, force, test, status, configure, locate); type dev_mandate is (unset, dump, makefile, distinfo, buildsheet, template); procedure scan_first_command_word; function scan_dev_command_word return dev_mandate; function get_arg (arg_number : Positive) return String; mandate : mandate_type := unset; procedure scan_first_command_word is first : constant String := CLI.Argument (1); begin if first = "help" then mandate := help; elsif first = "dev" then mandate := dev; elsif first = "build" then mandate := build; elsif first = "force" then mandate := force; elsif first = "test" then mandate := test; elsif first = "status" then mandate := status; elsif first = "configure" then mandate := configure; elsif first = "locate" then mandate := locate; end if; end scan_first_command_word; function scan_dev_command_word return dev_mandate is -- Check argument count before calling second : constant String := CLI.Argument (2); begin if second = "dump" then return dump; elsif second = "makefile" then return makefile; elsif second = "distinfo" then return distinfo; elsif second = "buildsheet" then return buildsheet; elsif second = "template" then return template; else return unset; end if; end scan_dev_command_word; function get_arg (arg_number : Positive) return String is begin if CLI.Argument_Count >= arg_number then return CLI.Argument (arg_number); else return ""; end if; end get_arg; begin if CLI.Argument_Count = 0 then Pilot.display_usage; return; end if; scan_first_command_word; if mandate = unset then Pilot.react_to_unknown_first_level_command (CLI.Argument (1)); return; end if; -------------------------------------------------------------------------------------------- -- Validation block start -------------------------------------------------------------------------------------------- if Pilot.already_running then return; end if; if not Parameters.load_configuration then return; end if; case mandate is when build | test | status => -- All commands involving replicant slaves if Pilot.launch_clash_detected then return; end if; when others => null; end case; case mandate is when build | test => if Parameters.configuration.avec_ncurses and then not Pilot.TERM_defined_in_environment then return; end if; when others => null; end case; case mandate is when configure | help => null; when others => if not Parameters.all_paths_valid then return; end if; end case; case mandate is when help => null; when others => if Pilot.insufficient_privileges then return; end if; end case; if Pilot.previous_run_mounts_detected and then not Pilot.old_mounts_successfully_removed then return; end if; if Pilot.previous_realfs_work_detected and then not Pilot.old_realfs_work_successfully_removed then return; end if; if Pilot.ravenexec_missing then return; end if; case mandate is when build | force | test => if not Pilot.store_origins (start_from => 2) then return; end if; when status => if CLI.Argument_Count > 1 then if not Pilot.store_origins (start_from => 2) then return; end if; end if; when others => null; end case; case mandate is when build | force | test | status => if not Pilot.slave_platform_determined then return; end if; when others => null; end case; Pilot.create_pidfile; Unix.ignore_background_tty; if mandate /= configure then Unix.cone_of_silence (deploy => True); end if; -------------------------------------------------------------------------------------------- -- Validation block end -------------------------------------------------------------------------------------------- case mandate is when status => -------------------------------- -- status command -------------------------------- if CLI.Argument_Count > 1 then if Pilot.scan_stack_of_single_ports (always_build => False) and then Pilot.sanity_check_then_prefail (delete_first => False, dry_run => True) then Pilot.perform_bulk_run (testmode => False); end if; else null; -- reserved for upgrade_system_everything maybe end if; when build => -------------------------------- -- build command -------------------------------- if Pilot.scan_stack_of_single_ports (always_build => False) and then Pilot.sanity_check_then_prefail (delete_first => False, dry_run => False) then Pilot.perform_bulk_run (testmode => False); end if; when force => -------------------------------- -- force command -------------------------------- if Pilot.scan_stack_of_single_ports (always_build => False) and then Pilot.sanity_check_then_prefail (delete_first => True, dry_run => False) then Pilot.perform_bulk_run (testmode => False); end if; when dev => -------------------------------- -- dev command -------------------------------- if CLI.Argument_Count > 1 then declare dev_subcmd : dev_mandate := scan_dev_command_word; begin case dev_subcmd is when unset => Pilot.react_to_unknown_second_level_command (CLI.Argument (1), CLI.Argument (2)); when dump => Pilot.dump_ravensource (get_arg (3)); when distinfo => Pilot.generate_distinfo; when buildsheet => Pilot.generate_buildsheet (get_arg (3), get_arg (4)); when makefile => Pilot.generate_makefile (get_arg (3), get_arg (4)); when template => Pilot.print_spec_template (get_arg (3)); end case; end; else Pilot.react_to_unknown_second_level_command (CLI.Argument (1), ""); end if; when help => -------------------------------- -- help command -------------------------------- null; -- tbw when test => -------------------------------- -- test command -------------------------------- if Pilot.scan_stack_of_single_ports (always_build => True) and then Pilot.sanity_check_then_prefail (delete_first => True, dry_run => False) then if Pilot.interact_with_single_builder then Pilot.bulk_run_then_interact_with_final_port; else Pilot.perform_bulk_run (testmode => True); end if; end if; when configure => -------------------------------- -- configure -------------------------------- Pilot.launch_configure_menu; when locate => -------------------------------- -- locate -------------------------------- Pilot.locate (get_arg (2)); when unset => null; end case; Unix.cone_of_silence (deploy => False); Pilot.destroy_pidfile; end Ravenadm;
-- This file is covered by the Internet Software Consortium (ISC) License -- Reference: License.txt with Ada.Command_Line; with Ada.Text_IO; with Parameters; with Pilot; with Unix; procedure Ravenadm is package CLI renames Ada.Command_Line; package TIO renames Ada.Text_IO; type mandate_type is (unset, help, dev, build, force, test, status, configure, locate); type dev_mandate is (unset, dump, makefile, distinfo, buildsheet, template); procedure scan_first_command_word; function scan_dev_command_word return dev_mandate; function get_arg (arg_number : Positive) return String; mandate : mandate_type := unset; low_rights : Boolean := False; procedure scan_first_command_word is first : constant String := CLI.Argument (1); begin if first = "help" then mandate := help; elsif first = "dev" then mandate := dev; elsif first = "build" then mandate := build; elsif first = "force" then mandate := force; elsif first = "test" then mandate := test; elsif first = "status" then mandate := status; elsif first = "configure" then mandate := configure; elsif first = "locate" then mandate := locate; end if; end scan_first_command_word; function scan_dev_command_word return dev_mandate is -- Check argument count before calling second : constant String := CLI.Argument (2); begin if second = "dump" then return dump; elsif second = "makefile" then return makefile; elsif second = "distinfo" then return distinfo; elsif second = "buildsheet" then return buildsheet; elsif second = "template" then return template; else return unset; end if; end scan_dev_command_word; function get_arg (arg_number : Positive) return String is begin if CLI.Argument_Count >= arg_number then return CLI.Argument (arg_number); else return ""; end if; end get_arg; begin if CLI.Argument_Count = 0 then Pilot.display_usage; return; end if; scan_first_command_word; if mandate = unset then Pilot.react_to_unknown_first_level_command (CLI.Argument (1)); return; end if; -------------------------------------------------------------------------------------------- -- Validation block start -------------------------------------------------------------------------------------------- if Pilot.already_running then return; end if; if not Parameters.load_configuration then return; end if; case mandate is when build | test | status => -- All commands involving replicant slaves if Pilot.launch_clash_detected then return; end if; when others => null; end case; case mandate is when build | test => if Parameters.configuration.avec_ncurses and then not Pilot.TERM_defined_in_environment then return; end if; when others => null; end case; case mandate is when configure | help => null; when others => if not Parameters.all_paths_valid then return; end if; end case; case mandate is when help | locate => null; low_rights := True; when others => if Pilot.insufficient_privileges then return; end if; end case; if Pilot.previous_run_mounts_detected and then not Pilot.old_mounts_successfully_removed then return; end if; if Pilot.previous_realfs_work_detected and then not Pilot.old_realfs_work_successfully_removed then return; end if; if Pilot.ravenexec_missing then return; end if; case mandate is when build | force | test => if not Pilot.store_origins (start_from => 2) then return; end if; when status => if CLI.Argument_Count > 1 then if not Pilot.store_origins (start_from => 2) then return; end if; end if; when others => null; end case; case mandate is when build | force | test | status => if not Pilot.slave_platform_determined then return; end if; when others => null; end case; if not low_rights then Pilot.create_pidfile; Unix.ignore_background_tty; end if; if mandate /= configure then Unix.cone_of_silence (deploy => True); end if; -------------------------------------------------------------------------------------------- -- Validation block end -------------------------------------------------------------------------------------------- case mandate is when status => -------------------------------- -- status command -------------------------------- if CLI.Argument_Count > 1 then if Pilot.scan_stack_of_single_ports (always_build => False) and then Pilot.sanity_check_then_prefail (delete_first => False, dry_run => True) then Pilot.perform_bulk_run (testmode => False); end if; else null; -- reserved for upgrade_system_everything maybe end if; when build => -------------------------------- -- build command -------------------------------- if Pilot.scan_stack_of_single_ports (always_build => False) and then Pilot.sanity_check_then_prefail (delete_first => False, dry_run => False) then Pilot.perform_bulk_run (testmode => False); end if; when force => -------------------------------- -- force command -------------------------------- if Pilot.scan_stack_of_single_ports (always_build => False) and then Pilot.sanity_check_then_prefail (delete_first => True, dry_run => False) then Pilot.perform_bulk_run (testmode => False); end if; when dev => -------------------------------- -- dev command -------------------------------- if CLI.Argument_Count > 1 then declare dev_subcmd : dev_mandate := scan_dev_command_word; begin case dev_subcmd is when unset => Pilot.react_to_unknown_second_level_command (CLI.Argument (1), CLI.Argument (2)); when dump => Pilot.dump_ravensource (get_arg (3)); when distinfo => Pilot.generate_distinfo; when buildsheet => Pilot.generate_buildsheet (get_arg (3), get_arg (4)); when makefile => Pilot.generate_makefile (get_arg (3), get_arg (4)); when template => Pilot.print_spec_template (get_arg (3)); end case; end; else Pilot.react_to_unknown_second_level_command (CLI.Argument (1), ""); end if; when help => -------------------------------- -- help command -------------------------------- null; -- tbw when test => -------------------------------- -- test command -------------------------------- if Pilot.scan_stack_of_single_ports (always_build => True) and then Pilot.sanity_check_then_prefail (delete_first => True, dry_run => False) then if Pilot.interact_with_single_builder then Pilot.bulk_run_then_interact_with_final_port; else Pilot.perform_bulk_run (testmode => True); end if; end if; when configure => -------------------------------- -- configure -------------------------------- Pilot.launch_configure_menu; when locate => -------------------------------- -- locate -------------------------------- Pilot.locate (get_arg (2)); when unset => null; end case; Unix.cone_of_silence (deploy => False); if not low_rights then Pilot.destroy_pidfile; end if; end Ravenadm;
Allow "locate" command to be run by user.
Allow "locate" command to be run by user.
Ada
isc
jrmarino/ravenadm,jrmarino/ravenadm,jrmarino/ravenadm
5efdeb81402f05641ba2bfb31da3c639078f8776
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; synth_version_major : constant String := "1"; synth_version_minor : constant String := "30"; copyright_years : constant String := "2015-2016"; host_localbase : constant String := "/usr/local"; host_pkg8 : constant String := host_localbase & "/sbin/pkg"; jobs_per_cpu : constant := 2; type cpu_range is range 1 .. 32; type scanners is range cpu_range'First .. cpu_range'Last; type builders is range cpu_range'First .. cpu_range'Last * jobs_per_cpu; end Definitions;
-- This file is covered by the Internet Software Consortium (ISC) License -- Reference: ../License.txt package Definitions is pragma Pure; synth_version_major : constant String := "1"; synth_version_minor : constant String := "31"; copyright_years : constant String := "2015-2016"; host_localbase : constant String := "/usr/local"; host_pkg8 : constant String := host_localbase & "/sbin/pkg"; jobs_per_cpu : constant := 2; type cpu_range is range 1 .. 32; type scanners is range cpu_range'First .. cpu_range'Last; type builders is range cpu_range'First .. cpu_range'Last * jobs_per_cpu; end Definitions;
Set to version 1.31
Set to version 1.31
Ada
isc
jrmarino/synth,jrmarino/synth,jrmarino/synth,jrmarino/synth
189196dc9f2ae4cd7b18efbe28ae512970ece2d7
src/wiki-render.ads
src/wiki-render.ads
----------------------------------------------------------------------- -- wiki-render -- Wiki renderer -- Copyright (C) 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.Strings.Wide_Wide_Unbounded; with Wiki.Nodes; with Wiki.Documents; -- == Wiki Renderer == -- The <tt>Wiki.Render</tt> package represents the renderer that takes a wiki document -- and render the result either in text, HTML or another format. -- -- @include wiki-render-html.ads -- @include wiki-render-text.ads -- @include wiki-render-wiki.ads package Wiki.Render is pragma Preelaborate; use Ada.Strings.Wide_Wide_Unbounded; type Link_Renderer is limited interface; type Link_Renderer_Access is access all Link_Renderer'Class; -- Get the image link that must be rendered from the wiki image link. procedure Make_Image_Link (Renderer : in Link_Renderer; Link : in Wide_Wide_String; URI : out Unbounded_Wide_Wide_String; Width : out Natural; Height : out Natural) is abstract; -- Get the page link that must be rendered from the wiki page link. procedure Make_Page_Link (Renderer : in Link_Renderer; Link : in Wide_Wide_String; URI : out Unbounded_Wide_Wide_String; Exists : out Boolean) is abstract; type Default_Link_Renderer is new Link_Renderer with null record; -- Get the image link that must be rendered from the wiki image link. overriding procedure Make_Image_Link (Renderer : in Default_Link_Renderer; Link : in Wide_Wide_String; URI : out Unbounded_Wide_Wide_String; Width : out Natural; Height : out Natural); -- Get the page link that must be rendered from the wiki page link. overriding procedure Make_Page_Link (Renderer : in Default_Link_Renderer; Link : in Wide_Wide_String; URI : out Unbounded_Wide_Wide_String; Exists : out Boolean); -- ------------------------------ -- Document renderer -- ------------------------------ type Renderer is limited interface; type Renderer_Access is access all Renderer'Class; -- Render the node instance from the document. procedure Render (Engine : in out Renderer; Doc : in Wiki.Documents.Document; Node : in Wiki.Nodes.Node_Type) is abstract; -- Finish the rendering pass after all the wiki document nodes are rendered. procedure Finish (Engine : in out Renderer; Doc : in Wiki.Documents.Document) is null; -- Render the list of nodes from the document. procedure Render (Engine : in out Renderer'Class; Doc : in Wiki.Documents.Document; List : in Wiki.Nodes.Node_List_Access); -- Render the document. procedure Render (Engine : in out Renderer'Class; Doc : in Wiki.Documents.Document); end Wiki.Render;
----------------------------------------------------------------------- -- wiki-render -- Wiki renderer -- Copyright (C) 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.Nodes; with Wiki.Strings; with Wiki.Documents; -- == Wiki Renderer == -- The <tt>Wiki.Render</tt> package represents the renderer that takes a wiki document -- and render the result either in text, HTML or another format. -- -- @include wiki-render-html.ads -- @include wiki-render-text.ads -- @include wiki-render-wiki.ads package Wiki.Render is pragma Preelaborate; type Link_Renderer is limited interface; type Link_Renderer_Access is access all Link_Renderer'Class; -- Get the image link that must be rendered from the wiki image link. procedure Make_Image_Link (Renderer : in Link_Renderer; Link : in Wiki.Strings.WString; URI : out Wiki.Strings.UString; Width : out Natural; Height : out Natural) is abstract; -- Get the page link that must be rendered from the wiki page link. procedure Make_Page_Link (Renderer : in Link_Renderer; Link : in Wiki.Strings.WString; URI : out Wiki.Strings.UString; Exists : out Boolean) is abstract; type Default_Link_Renderer is new Link_Renderer with null record; -- Get the image link that must be rendered from the wiki image link. overriding procedure Make_Image_Link (Renderer : in Default_Link_Renderer; Link : in Wiki.Strings.WString; URI : out Wiki.Strings.UString; Width : out Natural; Height : out Natural); -- Get the page link that must be rendered from the wiki page link. overriding procedure Make_Page_Link (Renderer : in Default_Link_Renderer; Link : in Wiki.Strings.WString; URI : out Wiki.Strings.UString; Exists : out Boolean); -- ------------------------------ -- Document renderer -- ------------------------------ type Renderer is limited interface; type Renderer_Access is access all Renderer'Class; -- Render the node instance from the document. procedure Render (Engine : in out Renderer; Doc : in Wiki.Documents.Document; Node : in Wiki.Nodes.Node_Type) is abstract; -- Finish the rendering pass after all the wiki document nodes are rendered. procedure Finish (Engine : in out Renderer; Doc : in Wiki.Documents.Document) is null; -- Render the list of nodes from the document. procedure Render (Engine : in out Renderer'Class; Doc : in Wiki.Documents.Document; List : in Wiki.Nodes.Node_List_Access); -- Render the document. procedure Render (Engine : in out Renderer'Class; Doc : in Wiki.Documents.Document); end Wiki.Render;
Use the Wiki.Strings.WString and UString types
Use the Wiki.Strings.WString and UString types
Ada
apache-2.0
stcarrez/ada-wiki,stcarrez/ada-wiki
0abc2acc8dda97d837c1cbcde5060f7c56d004bf
matp/src/frames/mat-frames-targets.ads
matp/src/frames/mat-frames-targets.ads
----------------------------------------------------------------------- -- mat-frames-targets - Representation of stack frames -- 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 Ada.Finalization; package MAT.Frames.Targets is type Target_Frames is tagged limited private; -- Insert in the frame tree the new stack frame represented by <tt>Pc</tt>. -- If the frame is already known, the frame reference counter is incremented. -- The frame represented by <tt>Pc</tt> is returned in <tt>Result</tt>. procedure Insert (Frame : in out Target_Frames; Pc : in Frame_Table; Result : out Frame_Type); private protected type Frames_Type is -- Insert in the frame tree the new stack frame represented by <tt>Pc</tt>. -- If the frame is already known, the frame reference counter is incremented. -- The frame represented by <tt>Pc</tt> is returned in <tt>Result</tt>. procedure Insert (Pc : in Frame_Table; Result : out Frame_Type); -- Clear and destroy all the frame instances. procedure Clear; private Root : Frame_Type := Create_Root; end Frames_Type; type Target_Frames is new Ada.Finalization.Limited_Controlled with record Frames : Frames_Type; end record; -- Release all the stack frames. overriding procedure Finalize (Frames : in out Target_Frames); end MAT.Frames.Targets;
----------------------------------------------------------------------- -- mat-frames-targets - Representation of stack frames -- 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 Ada.Finalization; package MAT.Frames.Targets is type Target_Frames is tagged limited private; type Target_Frames_Access is access all Target_Frames'Class; -- Insert in the frame tree the new stack frame represented by <tt>Pc</tt>. -- If the frame is already known, the frame reference counter is incremented. -- The frame represented by <tt>Pc</tt> is returned in <tt>Result</tt>. procedure Insert (Frame : in out Target_Frames; Pc : in Frame_Table; Result : out Frame_Type); -- Get the number of different stack frames which have been registered. function Get_Frame_Count (Frame : in Target_Frames) return Natural; private protected type Frames_Type is -- Insert in the frame tree the new stack frame represented by <tt>Pc</tt>. -- If the frame is already known, the frame reference counter is incremented. -- The frame represented by <tt>Pc</tt> is returned in <tt>Result</tt>. procedure Insert (Pc : in Frame_Table; Result : out Frame_Type); -- Clear and destroy all the frame instances. procedure Clear; private Root : Frame_Type := Create_Root; end Frames_Type; type Target_Frames is new Ada.Finalization.Limited_Controlled with record Frames : Frames_Type; end record; -- Release all the stack frames. overriding procedure Finalize (Frames : in out Target_Frames); end MAT.Frames.Targets;
Declare the Target_Frames_Access type and Get_Frame_Count function
Declare the Target_Frames_Access type and Get_Frame_Count function
Ada
apache-2.0
stcarrez/mat,stcarrez/mat,stcarrez/mat
11b384544bb2a93ee7d5e0af7b43e90a5f9d1fa1
src/ado-configs.ads
src/ado-configs.ads
----------------------------------------------------------------------- -- ado-configs -- Database connection configuration -- Copyright (C) 2010, 2011, 2012, 2016, 2017, 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.Finalization; with Util.Properties; package ADO.Configs is -- Configuration property to control the search paths to load XML queries. QUERY_PATHS_CONFIG : constant String := "ado.queries.paths"; -- Configuration property to control whether all the program XML queries must be -- loaded when the database configuration is setup. QUERY_LOAD_CONFIG : constant String := "ado.queries.load"; -- Configuration property to enable or disable the dynamic load of database driver. DYNAMIC_DRIVER_LOAD : constant String := "ado.drivers.load"; -- Configuration property to skip reading the database table entities. NO_ENTITY_LOAD : constant String := "ado.entities.ignore"; -- Maximum number of columns allowed for a table (SQLite limit is 2000). MAX_COLUMNS : constant := 2000; -- Maximum number of database drivers (MySQL, PostgreSQL, SQLite, X). MAX_DRIVERS : constant := 4; -- Raised when the connection URI is invalid. Connection_Error : exception; -- Initialize the drivers and the library by reading the property file -- and configure the runtime with it. procedure Initialize (Config : in String); -- Initialize the drivers and the library and configure the runtime with the given properties. procedure Initialize (Config : in Util.Properties.Manager'Class); -- Get the global configuration property identified by the name. -- If the configuration property does not exist, returns the default value. function Get_Config (Name : in String; Default : in String := "") return String; -- Returns true if the global configuration property is set to true/on. function Is_On (Name : in String) return Boolean; -- ------------------------------ -- The database configuration properties -- ------------------------------ type Configuration is new Ada.Finalization.Controlled with private; type Configuration_Access is access all Configuration'Class; -- Set the connection URL to connect to the database. -- The driver connection is a string of the form: -- -- driver://[host][:port]/[database][?property1][=value1]... -- -- If the string is invalid or if the driver cannot be found, -- the Connection_Error exception is raised. procedure Set_Connection (Config : in out Configuration; URI : in String); -- Get the connection URI that describes the database connection string. -- The returned string may contain connection authentication information. function Get_URI (Config : in Configuration) return String; -- Get the connection URI that describes the database connection string -- but the connection authentication is replaced by XXXX. function Get_Log_URI (Config : in Configuration) return String; -- Set a property on the datasource for the driver. -- The driver can retrieve the property to configure and open -- the database connection. procedure Set_Property (Config : in out Configuration; Name : in String; Value : in String); -- Get a property from the data source configuration. -- If the property does not exist, an empty string is returned. function Get_Property (Config : in Configuration; Name : in String) return String; -- Returns true if the configuration property is set to true/on. function Is_On (Config : in Configuration; Name : in String) return Boolean; -- Set the server hostname. procedure Set_Server (Config : in out Configuration; Server : in String); -- Get the server hostname. function Get_Server (Config : in Configuration) return String; -- Set the server port. procedure Set_Port (Config : in out Configuration; Port : in Natural); -- Get the server port. function Get_Port (Config : in Configuration) return Natural; -- Set the database name. procedure Set_Database (Config : in out Configuration; Database : in String); -- Get the database name. function Get_Database (Config : in Configuration) return String; -- Get the database driver name. function Get_Driver (Config : in Configuration) return String; -- Iterate over the configuration properties and execute the given procedure passing the -- property name and its value. procedure Iterate (Config : in Configuration; Process : access procedure (Name : in String; Item : in Util.Properties.Value)); type Driver_Index is new Natural range 0 .. 4; private use Ada.Strings.Unbounded; type Configuration is new Ada.Finalization.Controlled with record URI : Unbounded_String; Log_URI : Unbounded_String; Driver : Unbounded_String; Server : Unbounded_String; Port : Natural := 0; Database : Unbounded_String; Properties : Util.Properties.Manager; end record; end ADO.Configs;
----------------------------------------------------------------------- -- ado-configs -- Database connection configuration -- Copyright (C) 2010, 2011, 2012, 2016, 2017, 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.Finalization; with Util.Properties; package ADO.Configs is -- Configuration property to control the search paths to load XML queries. QUERY_PATHS_CONFIG : constant String := "ado.queries.paths"; -- Configuration property to control whether all the program XML queries must be -- loaded when the database configuration is setup. QUERY_LOAD_CONFIG : constant String := "ado.queries.load"; -- Configuration property to enable or disable the dynamic load of database driver. DYNAMIC_DRIVER_LOAD : constant String := "ado.drivers.load"; -- Configuration property to skip reading the database table entities. NO_ENTITY_LOAD : constant String := "ado.entities.ignore"; -- Maximum number of columns allowed for a table (SQLite limit is 2000). MAX_COLUMNS : constant := 2000; -- Maximum number of database drivers (MySQL, PostgreSQL, SQLite, X). MAX_DRIVERS : constant := 4; -- Raised when the connection URI is invalid. Connection_Error : exception; -- Initialize the drivers and the library by reading the property file -- and configure the runtime with it. procedure Initialize (Config : in String); -- Initialize the drivers and the library and configure the runtime with the given properties. procedure Initialize (Config : in Util.Properties.Manager'Class); -- Get the global configuration property identified by the name. -- If the configuration property does not exist, returns the default value. function Get_Config (Name : in String; Default : in String := "") return String; -- Returns true if the global configuration property is set to true/on. function Is_On (Name : in String) return Boolean; -- ------------------------------ -- The database configuration properties -- ------------------------------ type Configuration is new Ada.Finalization.Controlled with private; type Configuration_Access is access all Configuration'Class; -- Set the connection URL to connect to the database. -- The driver connection is a string of the form: -- -- driver://[host][:port]/[database][?property1][=value1]... -- -- If the string is invalid or if the driver cannot be found, -- the Connection_Error exception is raised. procedure Set_Connection (Config : in out Configuration; URI : in String); -- Get the connection URI that describes the database connection string. -- The returned string may contain connection authentication information. function Get_URI (Config : in Configuration) return String; -- Get the connection URI that describes the database connection string -- but the connection authentication is replaced by XXXX. function Get_Log_URI (Config : in Configuration) return String; -- Set a property on the datasource for the driver. -- The driver can retrieve the property to configure and open -- the database connection. procedure Set_Property (Config : in out Configuration; Name : in String; Value : in String); -- Get a property from the data source configuration. -- If the property does not exist, an empty string is returned. function Get_Property (Config : in Configuration; Name : in String) return String; -- Returns true if the configuration property is set to true/on. function Is_On (Config : in Configuration; Name : in String) return Boolean; -- Set the server hostname. procedure Set_Server (Config : in out Configuration; Server : in String); -- Get the server hostname. function Get_Server (Config : in Configuration) return String; -- Set the server port. procedure Set_Port (Config : in out Configuration; Port : in Natural); -- Get the server port. function Get_Port (Config : in Configuration) return Natural; -- Set the database name. procedure Set_Database (Config : in out Configuration; Database : in String); -- Get the database name. function Get_Database (Config : in Configuration) return String; -- Get the database driver name. function Get_Driver (Config : in Configuration) return String; -- Iterate over the configuration properties and execute the given procedure passing the -- property name and its value. procedure Iterate (Config : in Configuration; Process : access procedure (Name : in String; Item : in Util.Properties.Value)); type Driver_Index is new Natural range 0 .. MAX_DRIVERS; private use Ada.Strings.Unbounded; type Configuration is new Ada.Finalization.Controlled with record URI : Unbounded_String; Log_URI : Unbounded_String; Driver : Unbounded_String; Server : Unbounded_String; Port : Natural := 0; Database : Unbounded_String; Properties : Util.Properties.Manager; end record; end ADO.Configs;
Update Driver_Index type to use the MAX_DRIVERS constant
Update Driver_Index type to use the MAX_DRIVERS constant
Ada
apache-2.0
stcarrez/ada-ado
e37cc435251223ad00636af9fd3b282af2d0fb9c
src/sys/encoders/util-encoders-sha256.ads
src/sys/encoders/util-encoders-sha256.ads
----------------------------------------------------------------------- -- util-encoders-sha256 -- Compute SHA-256 hash -- 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.Streams; with GNAT.SHA256; package Util.Encoders.SHA256 is -- The SHA-256 binary hash (256-bit). subtype Hash_Array is Ada.Streams.Stream_Element_Array (0 .. 31); -- The SHA-256 hash as hexadecimal string. subtype Digest is String (1 .. 64); subtype Base64_Digest is String (1 .. 44); -- ------------------------------ -- SHA256 Context -- ------------------------------ subtype Context is GNAT.SHA256.Context; -- Update the hash with the string. procedure Update (E : in out Context; S : in String) renames GNAT.SHA256.Update; -- Update the hash with the string. procedure Update (E : in out Context; S : in Ada.Streams.Stream_Element_Array) renames GNAT.SHA256.Update; -- Computes the SHA256 hash and returns the raw binary hash in <b>Hash</b>. procedure Finish (E : in out Context; Hash : out Hash_Array); -- Computes the SHA256 hash and returns the hexadecimal hash in <b>Hash</b>. procedure Finish (E : in out Context; Hash : out Digest); -- Computes the SHA256 hash and returns the base64 hash in <b>Hash</b>. procedure Finish_Base64 (E : in out Context; Hash : out Base64_Digest); end Util.Encoders.SHA256;
----------------------------------------------------------------------- -- util-encoders-sha256 -- Compute SHA-256 hash -- Copyright (C) 2017, 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.Streams; with GNAT.SHA256; package Util.Encoders.SHA256 is HASH_SIZE : constant := 32; -- The SHA-256 binary hash (256-bit). subtype Hash_Array is Ada.Streams.Stream_Element_Array (0 .. HASH_SIZE - 1); -- The SHA-256 hash as hexadecimal string. subtype Digest is String (1 .. 2 * HASH_SIZE); subtype Base64_Digest is String (1 .. 44); -- ------------------------------ -- SHA256 Context -- ------------------------------ subtype Context is GNAT.SHA256.Context; -- Update the hash with the string. procedure Update (E : in out Context; S : in String) renames GNAT.SHA256.Update; -- Update the hash with the string. procedure Update (E : in out Context; S : in Ada.Streams.Stream_Element_Array) renames GNAT.SHA256.Update; -- Computes the SHA256 hash and returns the raw binary hash in <b>Hash</b>. procedure Finish (E : in out Context; Hash : out Hash_Array); -- Computes the SHA256 hash and returns the hexadecimal hash in <b>Hash</b>. procedure Finish (E : in out Context; Hash : out Digest); -- Computes the SHA256 hash and returns the base64 hash in <b>Hash</b>. procedure Finish_Base64 (E : in out Context; Hash : out Base64_Digest); end Util.Encoders.SHA256;
Define HASH_SIZE and use it
Define HASH_SIZE and use it
Ada
apache-2.0
stcarrez/ada-util,stcarrez/ada-util
5861e203bb50e2d5712511d4ec81e5e119916ad5
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 := "23"; copyright_years : constant String := "2015-2019"; 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"; ports_default : constant String := "floating"; default_ssl : constant String := "libressl"; default_mysql : constant String := "oracle-5.7"; default_lua : constant String := "5.3"; default_perl : constant String := "5.28"; default_pgsql : constant String := "10"; default_php : constant String := "7.2"; default_python3 : constant String := "3.7"; default_ruby : constant String := "2.5"; default_tcltk : constant String := "8.6"; default_firebird : constant String := "2.5"; default_compiler : constant String := "gcc8"; compiler_version : constant String := "8.3.0"; previous_compiler : constant String := "8.2.0"; binutils_version : constant String := "2.32"; previous_binutils : constant String := "2.30"; arc_ext : constant String := ".tzst"; jobs_per_cpu : constant := 2; 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/pkg-static"; 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 := "23"; copyright_years : constant String := "2015-2019"; 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"; ports_default : constant String := "floating"; default_ssl : constant String := "libressl"; default_mysql : constant String := "oracle-5.7"; default_lua : constant String := "5.3"; default_perl : constant String := "5.28"; default_pgsql : constant String := "10"; default_php : constant String := "7.2"; default_python3 : constant String := "3.7"; default_ruby : constant String := "2.5"; default_tcltk : constant String := "8.6"; default_firebird : constant String := "2.5"; default_compiler : constant String := "gcc8"; compiler_version : constant String := "8.3.0"; previous_compiler : constant String := "8.2.0"; binutils_version : constant String := "2.32"; previous_binutils : constant String := "2.31.1"; arc_ext : constant String := ".tzst"; jobs_per_cpu : constant := 2; 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/pkg-static"; ravenexec : constant String := host_localbase & "/libexec/ravenexec"; end Definitions;
define previous binutils
define previous binutils
Ada
isc
jrmarino/ravenadm,jrmarino/ravenadm,jrmarino/ravenadm
ec5787990425b3f68f859daab534fd11d1075d2a
src/instruction.ads
src/instruction.ads
package Instruction is end package;
package Instruction is end Instruction;
Add instruction package
Add instruction package
Ada
mit
peterfrankjohnson/assembler
c9b3c2356f59ae10cff1dd88049d1869658bc112
awa/samples/src/atlas-applications.adb
awa/samples/src/atlas-applications.adb
----------------------------------------------------------------------- -- atlas -- atlas applications ----------------------------------------------------------------------- -- 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. ----------------------------------------------------------------------- with Ada.IO_Exceptions; with GNAT.MD5; with Util.Log.Loggers; with Util.Properties; with Util.Strings.Transforms; with EL.Functions; with ASF.Applications; with ASF.Applications.Main; with ASF.Applications.Main.Configs; with AWA.Applications.Configs; with AWA.Applications.Factory; -- with Atlas.XXX.Module; package body Atlas.Applications is use AWA.Applications; Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("Atlas"); procedure Set_Functions (Mapper : in out EL.Functions.Function_Mapper'Class); -- ------------------------------ -- 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_Gravatar_Link (Email : in String) return String is E : constant String := Util.Strings.Transforms.To_Lower_Case (Email); C : constant GNAT.MD5.Message_Digest := GNAT.MD5.Digest (E); begin return "http://www.gravatar.com/avatar/" & C; end Get_Gravatar_Link; -- ------------------------------ -- EL function to convert an Email address to a Gravatar image. -- ------------------------------ function To_Gravatar_Link (Email : in Util.Beans.Objects.Object) return Util.Beans.Objects.Object is Link : constant String := Get_Gravatar_Link (Util.Beans.Objects.To_String (Email)); begin return Util.Beans.Objects.To_Object (Link); end To_Gravatar_Link; procedure Set_Functions (Mapper : in out EL.Functions.Function_Mapper'Class) is begin Mapper.Set_Function (Name => "gravatar", Namespace => ATLAS_NS_URI, Func => To_Gravatar_Link'Access); end Set_Functions; -- ------------------------------ -- Initialize the application: -- <ul> -- <li>Register the servlets and filters. -- <li>Register the application modules. -- <li>Define the servlet and filter mappings. -- </ul> -- ------------------------------ procedure Initialize (App : in Application_Access) is Fact : AWA.Applications.Factory.Application_Factory; C : ASF.Applications.Config; begin App.Self := App; begin C.Load_Properties ("atlas.properties"); Util.Log.Loggers.Initialize (Util.Properties.Manager (C)); exception when Ada.IO_Exceptions.Name_Error => Log.Error ("Cannot read application configuration file {0}", CONFIG_PATH); end; App.Initialize (C, Fact); App.Set_Global ("contextPath", CONTEXT_PATH); end Initialize; -- ------------------------------ -- Initialize the ASF components provided by the application. -- This procedure is called by <b>Initialize</b>. -- It should register the component factories used by the application. -- ------------------------------ overriding procedure Initialize_Components (App : in out Application) is procedure Register is new ASF.Applications.Main.Register_Functions (Set_Functions); begin Register (App); AWA.Applications.Application (App).Initialize_Components; App.Add_Converter (Name => "smartDateConverter", Converter => App.Self.Rel_Date_Converter'Access); App.Add_Converter (Name => "sizeConverter", Converter => App.Self.Size_Converter'Access); end Initialize_Components; -- ------------------------------ -- 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 Application) is begin Log.Info ("Initializing application servlets..."); AWA.Applications.Application (App).Initialize_Servlets; App.Add_Servlet (Name => "faces", Server => App.Self.Faces'Access); App.Add_Servlet (Name => "files", Server => App.Self.Files'Access); App.Add_Servlet (Name => "ajax", Server => App.Self.Ajax'Access); App.Add_Servlet (Name => "measures", Server => App.Self.Measures'Access); App.Add_Servlet (Name => "auth", Server => App.Self.Auth'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 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; -- ------------------------------ -- Initialize the AWA modules provided by the application. -- This procedure is called by <b>Initialize</b>. -- It should register the modules used by the application. -- ------------------------------ overriding procedure Initialize_Modules (App : in out Application) is begin Log.Info ("Initializing application modules..."); Register (App => App.Self.all'Access, Name => AWA.Users.Modules.NAME, URI => "user", Module => App.User_Module'Access); Register (App => App.Self.all'Access, Name => AWA.Workspaces.Modules.NAME, URI => "workspaces", Module => App.Workspace_Module'Access); Register (App => App.Self.all'Access, Name => AWA.Mail.Modules.NAME, URI => "mail", Module => App.Mail_Module'Access); Register (App => App.Self.all'Access, Name => AWA.Blogs.Modules.NAME, URI => "blogs", Module => App.Blog_Module'Access); Register (App => App.Self.all'Access, Name => AWA.Storages.Modules.NAME, URI => "storages", Module => App.Storage_Module'Access); Register (App => App.Self.all'Access, Name => AWA.Images.Modules.NAME, URI => "images", Module => App.Image_Module'Access); Register (App => App.Self.all'Access, Name => AWA.Questions.Modules.NAME, URI => "questions", Module => App.Question_Module'Access); Register (App => App.Self.all'Access, Name => Atlas.Microblog.Modules.NAME, URI => "microblog", Module => App.Microblog_Module'Access); end Initialize_Modules; end Atlas.Applications;
----------------------------------------------------------------------- -- atlas -- atlas applications ----------------------------------------------------------------------- -- 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. ----------------------------------------------------------------------- with Ada.IO_Exceptions; with GNAT.MD5; with Util.Log.Loggers; with Util.Properties; with Util.Strings.Transforms; with EL.Functions; with ASF.Applications; with ASF.Applications.Main; with AWA.Applications.Factory; -- with Atlas.XXX.Module; package body Atlas.Applications is use AWA.Applications; Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("Atlas"); procedure Set_Functions (Mapper : in out EL.Functions.Function_Mapper'Class); -- ------------------------------ -- 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_Gravatar_Link (Email : in String) return String is E : constant String := Util.Strings.Transforms.To_Lower_Case (Email); C : constant GNAT.MD5.Message_Digest := GNAT.MD5.Digest (E); begin return "http://www.gravatar.com/avatar/" & C; end Get_Gravatar_Link; -- ------------------------------ -- EL function to convert an Email address to a Gravatar image. -- ------------------------------ function To_Gravatar_Link (Email : in Util.Beans.Objects.Object) return Util.Beans.Objects.Object is Link : constant String := Get_Gravatar_Link (Util.Beans.Objects.To_String (Email)); begin return Util.Beans.Objects.To_Object (Link); end To_Gravatar_Link; procedure Set_Functions (Mapper : in out EL.Functions.Function_Mapper'Class) is begin Mapper.Set_Function (Name => "gravatar", Namespace => ATLAS_NS_URI, Func => To_Gravatar_Link'Access); end Set_Functions; -- ------------------------------ -- Initialize the application: -- <ul> -- <li>Register the servlets and filters. -- <li>Register the application modules. -- <li>Define the servlet and filter mappings. -- </ul> -- ------------------------------ procedure Initialize (App : in Application_Access) is Fact : AWA.Applications.Factory.Application_Factory; C : ASF.Applications.Config; begin App.Self := App; begin C.Load_Properties ("atlas.properties"); Util.Log.Loggers.Initialize (Util.Properties.Manager (C)); exception when Ada.IO_Exceptions.Name_Error => Log.Error ("Cannot read application configuration file {0}", CONFIG_PATH); end; App.Initialize (C, Fact); App.Set_Global ("contextPath", CONTEXT_PATH); end Initialize; -- ------------------------------ -- Initialize the ASF components provided by the application. -- This procedure is called by <b>Initialize</b>. -- It should register the component factories used by the application. -- ------------------------------ overriding procedure Initialize_Components (App : in out Application) is procedure Register is new ASF.Applications.Main.Register_Functions (Set_Functions); begin Register (App); AWA.Applications.Application (App).Initialize_Components; App.Add_Converter (Name => "smartDateConverter", Converter => App.Self.Rel_Date_Converter'Access); App.Add_Converter (Name => "sizeConverter", Converter => App.Self.Size_Converter'Access); end Initialize_Components; -- ------------------------------ -- 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 Application) is begin Log.Info ("Initializing application servlets..."); AWA.Applications.Application (App).Initialize_Servlets; App.Add_Servlet (Name => "faces", Server => App.Self.Faces'Access); App.Add_Servlet (Name => "files", Server => App.Self.Files'Access); App.Add_Servlet (Name => "ajax", Server => App.Self.Ajax'Access); App.Add_Servlet (Name => "measures", Server => App.Self.Measures'Access); App.Add_Servlet (Name => "auth", Server => App.Self.Auth'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 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; -- ------------------------------ -- Initialize the AWA modules provided by the application. -- This procedure is called by <b>Initialize</b>. -- It should register the modules used by the application. -- ------------------------------ overriding procedure Initialize_Modules (App : in out Application) is begin Log.Info ("Initializing application modules..."); Register (App => App.Self.all'Access, Name => AWA.Users.Modules.NAME, URI => "user", Module => App.User_Module'Access); Register (App => App.Self.all'Access, Name => AWA.Workspaces.Modules.NAME, URI => "workspaces", Module => App.Workspace_Module'Access); Register (App => App.Self.all'Access, Name => AWA.Mail.Modules.NAME, URI => "mail", Module => App.Mail_Module'Access); Register (App => App.Self.all'Access, Name => AWA.Blogs.Modules.NAME, URI => "blogs", Module => App.Blog_Module'Access); Register (App => App.Self.all'Access, Name => AWA.Storages.Modules.NAME, URI => "storages", Module => App.Storage_Module'Access); Register (App => App.Self.all'Access, Name => AWA.Images.Modules.NAME, URI => "images", Module => App.Image_Module'Access); Register (App => App.Self.all'Access, Name => AWA.Votes.Modules.NAME, URI => "votes", Module => App.Vote_Module'Access); Register (App => App.Self.all'Access, Name => AWA.Questions.Modules.NAME, URI => "questions", Module => App.Question_Module'Access); Register (App => App.Self.all'Access, Name => Atlas.Microblog.Modules.NAME, URI => "microblog", Module => App.Microblog_Module'Access); end Initialize_Modules; end Atlas.Applications;
Add the vote plugin
Add the vote plugin
Ada
apache-2.0
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
2ab3c6844e31677fa78e8ac13611596a14be593e
arch/ARM/STM32/drivers/stm32-pwm.adb
arch/ARM/STM32/drivers/stm32-pwm.adb
------------------------------------------------------------------------------ -- -- -- Copyright (C) 2015-2017, AdaCore -- -- -- -- 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 the copyright holder 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 THE COPYRIGHT HOLDERS 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 THE COPYRIGHT -- -- HOLDER 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. -- -- -- ------------------------------------------------------------------------------ with System; use System; with STM32_SVD; use STM32_SVD; with STM32.Device; use STM32.Device; package body STM32.PWM is procedure Compute_Prescalar_And_Period (This : access Timer; Requested_Frequency : Hertz; Prescalar : out UInt32; Period : out UInt32) with Pre => Requested_Frequency > 0; -- Computes the minimum prescaler and thus the maximum resolution for the -- given timer, based on the system clocks and the requested frequency. -- Computes the period required for the requested frequency. function Timer_Period (This : PWM_Modulator) return UInt32 is (Current_Autoreload (This.Generator.all)); procedure Configure_PWM_GPIO (Output : GPIO_Point; PWM_AF : GPIO_Alternate_Function); -- TODO: move these two functions to the STM32.Device packages? function Has_APB2_Frequency (This : Timer) return Boolean; -- timers 1, 8, 9, 10, 11 function Has_APB1_Frequency (This : Timer) return Boolean; -- timers 3, 4, 6, 7, 12, 13, 14 -------------------- -- Set_Duty_Cycle -- -------------------- procedure Set_Duty_Cycle (This : in out PWM_Modulator; Value : Percentage) is Pulse : UInt16; begin This.Duty_Cycle := Value; if Value = 0 then Set_Compare_Value (This.Generator.all, This.Channel, UInt16'(0)); else Pulse := UInt16 ((Timer_Period (This) + 1) * UInt32 (Value) / 100) - 1; -- for a Value of 0, the computation of Pulse wraps around to -- 65535, so we only compute it when not zero Set_Compare_Value (This.Generator.all, This.Channel, Pulse); end if; end Set_Duty_Cycle; ------------------- -- Set_Duty_Time -- ------------------- procedure Set_Duty_Time (This : in out PWM_Modulator; Value : Microseconds) is Pulse : UInt16; Period : constant UInt32 := Timer_Period (This) + 1; uS_Per_Period : constant UInt32 := Microseconds_Per_Period (This); begin if Value = 0 then Set_Compare_Value (This.Generator.all, This.Channel, UInt16'(0)); else Pulse := UInt16 ((Period * Value) / uS_Per_Period) - 1; -- for a Value of 0, the computation of Pulse wraps around to -- 65535, so we only compute it when not zero Set_Compare_Value (This.Generator.all, This.Channel, Pulse); end if; end Set_Duty_Time; ------------------------ -- Current_Duty_Cycle -- ------------------------ function Current_Duty_Cycle (This : PWM_Modulator) return Percentage is begin return This.Duty_Cycle; end Current_Duty_Cycle; ------------------------- -- Configure_PWM_Timer -- ------------------------- procedure Configure_PWM_Timer (Generator : not null access Timer; Frequency : Hertz) is Computed_Prescalar : UInt32; Computed_Period : UInt32; begin Enable_Clock (Generator.all); Compute_Prescalar_And_Period (Generator, Requested_Frequency => Frequency, Prescalar => Computed_Prescalar, Period => Computed_Period); Computed_Period := Computed_Period - 1; Configure (Generator.all, Prescaler => UInt16 (Computed_Prescalar), Period => Computed_Period, Clock_Divisor => Div1, Counter_Mode => Up); Set_Autoreload_Preload (Generator.all, True); if Advanced_Timer (Generator.all) then Enable_Main_Output (Generator.all); end if; Enable (Generator.all); end Configure_PWM_Timer; ------------------------ -- Attach_PWM_Channel -- ------------------------ procedure Attach_PWM_Channel (This : in out PWM_Modulator; Generator : not null access Timer; Channel : Timer_Channel; Point : GPIO_Point; PWM_AF : GPIO_Alternate_Function; Polarity : Timer_Output_Compare_Polarity := High) is begin This.Channel := Channel; This.Generator := Generator; Enable_Clock (Point); Configure_PWM_GPIO (Point, PWM_AF); Configure_Channel_Output (This.Generator.all, Channel => Channel, Mode => PWM1, State => Disable, Pulse => 0, Polarity => Polarity); Set_Compare_Value (This.Generator.all, Channel, UInt16 (0)); Disable_Channel (This.Generator.all, Channel); end Attach_PWM_Channel; ------------------------ -- Attach_PWM_Channel -- ------------------------ procedure Attach_PWM_Channel (This : in out PWM_Modulator; Generator : not null access Timer; Channel : Timer_Channel; Point : GPIO_Point; Complementary_Point : GPIO_Point; PWM_AF : GPIO_Alternate_Function; Polarity : Timer_Output_Compare_Polarity; Idle_State : Timer_Capture_Compare_State; Complementary_Polarity : Timer_Output_Compare_Polarity; Complementary_Idle_State : Timer_Capture_Compare_State) is begin This.Channel := Channel; This.Generator := Generator; Enable_Clock (Point); Enable_Clock (Complementary_Point); Configure_PWM_GPIO (Point, PWM_AF); Configure_PWM_GPIO (Complementary_Point, PWM_AF); Configure_Channel_Output (This.Generator.all, Channel => Channel, Mode => PWM1, State => Disable, Pulse => 0, Polarity => Polarity, Idle_State => Idle_State, Complementary_Polarity => Complementary_Polarity, Complementary_Idle_State => Complementary_Idle_State); Set_Compare_Value (This.Generator.all, Channel, UInt16 (0)); Disable_Channel (This.Generator.all, Channel); end Attach_PWM_Channel; ------------------- -- Enable_Output -- ------------------- procedure Enable_Output (This : in out PWM_Modulator) is begin Enable_Channel (This.Generator.all, This.Channel); end Enable_Output; --------------------------------- -- Enable_Complementary_Output -- --------------------------------- procedure Enable_Complementary_Output (This : in out PWM_Modulator) is begin Enable_Complementary_Channel (This.Generator.all, This.Channel); end Enable_Complementary_Output; -------------------- -- Output_Enabled -- -------------------- function Output_Enabled (This : PWM_Modulator) return Boolean is begin return Channel_Enabled (This.Generator.all, This.Channel); end Output_Enabled; ---------------------------------- -- Complementary_Output_Enabled -- ---------------------------------- function Complementary_Output_Enabled (This : PWM_Modulator) return Boolean is begin return Complementary_Channel_Enabled (This.Generator.all, This.Channel); end Complementary_Output_Enabled; -------------------- -- Disable_Output -- -------------------- procedure Disable_Output (This : in out PWM_Modulator) is begin Disable_Channel (This.Generator.all, This.Channel); end Disable_Output; ---------------------------------- -- Disable_Complementary_Output -- ---------------------------------- procedure Disable_Complementary_Output (This : in out PWM_Modulator) is begin Disable_Complementary_Channel (This.Generator.all, This.Channel); end Disable_Complementary_Output; ------------------ -- Set_Polarity -- ------------------ procedure Set_Polarity (This : in PWM_Modulator; Polarity : in Timer_Output_Compare_Polarity) is begin Set_Output_Polarity (This.Generator.all, This.Channel, Polarity); end Set_Polarity; -------------------------------- -- Set_Complementary_Polarity -- -------------------------------- procedure Set_Complementary_Polarity (This : in PWM_Modulator; Polarity : in Timer_Output_Compare_Polarity) is begin Set_Output_Complementary_Polarity (This.Generator.all, This.Channel, Polarity); end Set_Complementary_Polarity; ------------------------ -- Configure_PWM_GPIO -- ------------------------ procedure Configure_PWM_GPIO (Output : GPIO_Point; PWM_AF : GPIO_Alternate_Function) is Configuration : GPIO_Port_Configuration; begin Configuration.Mode := Mode_AF; Configuration.Output_Type := Push_Pull; Configuration.Speed := Speed_100MHz; Configuration.Resistors := Floating; Output.Configure_IO (Configuration); Output.Configure_Alternate_Function (PWM_AF); Output.Lock; end Configure_PWM_GPIO; ---------------------------------- -- Compute_Prescalar_and_Period -- ---------------------------------- procedure Compute_Prescalar_And_Period (This : access Timer; Requested_Frequency : Hertz; Prescalar : out UInt32; Period : out UInt32) is Max_Prescalar : constant := 16#FFFF#; Max_Period : UInt32; Hardware_Frequency : UInt32; Clocks : constant RCC_System_Clocks := System_Clock_Frequencies; CK_CNT : UInt32; begin if Has_APB1_Frequency (This.all) then Hardware_Frequency := Clocks.TIMCLK1; elsif Has_APB2_Frequency (This.all) then Hardware_Frequency := Clocks.TIMCLK2; else raise Unknown_Timer; end if; if Has_32bit_Counter (This.all) then Max_Period := 16#FFFF_FFFF#; else Max_Period := 16#FFFF#; end if; if Requested_Frequency > Hardware_Frequency then raise Invalid_Request with "Freq too high"; end if; Prescalar := 0; loop -- Compute the Counter's clock CK_CNT := Hardware_Frequency / (Prescalar + 1); -- Determine the CK_CNT periods to achieve the requested frequency Period := CK_CNT / Requested_Frequency; exit when not ((Period > Max_Period) and (Prescalar <= Max_Prescalar)); Prescalar := Prescalar + 1; end loop; if Prescalar > Max_Prescalar then raise Invalid_Request with "Freq too low"; end if; end Compute_Prescalar_And_Period; ----------------------------- -- Microseconds_Per_Period -- ----------------------------- function Microseconds_Per_Period (This : PWM_Modulator) return Microseconds is Result : UInt32; Counter_Frequency : UInt32; Platform_Frequency : UInt32; Clocks : constant RCC_System_Clocks := System_Clock_Frequencies; Period : constant UInt32 := Timer_Period (This) + 1; Prescalar : constant UInt16 := Current_Prescaler (This.Generator.all) + 1; begin if Has_APB1_Frequency (This.Generator.all) then Platform_Frequency := Clocks.TIMCLK1; else Platform_Frequency := Clocks.TIMCLK2; end if; Counter_Frequency := (Platform_Frequency / UInt32 (Prescalar)) / Period; Result := 1_000_000 / Counter_Frequency; return Result; end Microseconds_Per_Period; ------------------------ -- Has_APB2_Frequency -- ------------------------ function Has_APB2_Frequency (This : Timer) return Boolean is (This'Address = STM32_SVD.TIM1_Base or This'Address = STM32_SVD.TIM8_Base or This'Address = STM32_SVD.TIM9_Base or This'Address = STM32_SVD.TIM10_Base or This'Address = STM32_SVD.TIM11_Base); ------------------------ -- Has_APB1_Frequency -- ------------------------ function Has_APB1_Frequency (This : Timer) return Boolean is (This'Address = STM32_SVD.TIM2_Base or This'Address = STM32_SVD.TIM3_Base or This'Address = STM32_SVD.TIM4_Base or This'Address = STM32_SVD.TIM5_Base or This'Address = STM32_SVD.TIM6_Base or This'Address = STM32_SVD.TIM7_Base or This'Address = STM32_SVD.TIM12_Base or This'Address = STM32_SVD.TIM13_Base or This'Address = STM32_SVD.TIM14_Base); end STM32.PWM;
------------------------------------------------------------------------------ -- -- -- Copyright (C) 2015-2017, AdaCore -- -- -- -- 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 the copyright holder 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 THE COPYRIGHT HOLDERS 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 THE COPYRIGHT -- -- HOLDER 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. -- -- -- ------------------------------------------------------------------------------ with System; use System; with STM32_SVD; use STM32_SVD; with STM32.Device; use STM32.Device; package body STM32.PWM is procedure Compute_Prescalar_And_Period (This : access Timer; Requested_Frequency : Hertz; Prescalar : out UInt32; Period : out UInt32) with Pre => Requested_Frequency > 0; -- Computes the minimum prescaler and thus the maximum resolution for the -- given timer, based on the system clocks and the requested frequency. -- Computes the period required for the requested frequency. function Timer_Period (This : PWM_Modulator) return UInt32 is (Current_Autoreload (This.Generator.all)); procedure Configure_PWM_GPIO (Output : GPIO_Point; PWM_AF : GPIO_Alternate_Function); -- TODO: move these two functions to the STM32.Device packages? function Has_APB2_Frequency (This : Timer) return Boolean; -- timers 1, 8, 9, 10, 11 function Has_APB1_Frequency (This : Timer) return Boolean; -- timers 3, 4, 6, 7, 12, 13, 14 -------------------- -- Set_Duty_Cycle -- -------------------- procedure Set_Duty_Cycle (This : in out PWM_Modulator; Value : Percentage) is Pulse16 : UInt16; Pulse32 : UInt32; begin This.Duty_Cycle := Value; if Value = 0 then Set_Compare_Value (This.Generator.all, This.Channel, UInt16'(0)); else -- for a Value of 0, the computation of Pulse wraps around, so we -- only compute it when not zero if Has_32bit_CC_Values (This.Generator.all) then Pulse32 := UInt32 ((Timer_Period (This) + 1) * UInt32 (Value) / 100) - 1; Set_Compare_Value (This.Generator.all, This.Channel, Pulse32); else Pulse16 := UInt16 ((Timer_Period (This) + 1) * UInt32 (Value) / 100) - 1; Set_Compare_Value (This.Generator.all, This.Channel, Pulse16); end if; end if; end Set_Duty_Cycle; ------------------- -- Set_Duty_Time -- ------------------- procedure Set_Duty_Time (This : in out PWM_Modulator; Value : Microseconds) is Pulse16 : UInt16; Pulse32 : UInt32; Period : constant UInt32 := Timer_Period (This) + 1; uS_Per_Period : constant UInt32 := Microseconds_Per_Period (This); begin if Value = 0 then Set_Compare_Value (This.Generator.all, This.Channel, UInt16'(0)); else -- for a Value of 0, the computation of Pulse wraps around, so we -- only compute it when not zero if Has_32bit_CC_Values (This.Generator.all) then Pulse32 := UInt32 ((Period / uS_Per_Period) * Value) - 1; Set_Compare_Value (This.Generator.all, This.Channel, Pulse32); else Pulse16 := UInt16 ((Period * Value) / uS_Per_Period) - 1; Set_Compare_Value (This.Generator.all, This.Channel, Pulse16); end if; end if; end Set_Duty_Time; ------------------------ -- Current_Duty_Cycle -- ------------------------ function Current_Duty_Cycle (This : PWM_Modulator) return Percentage is begin return This.Duty_Cycle; end Current_Duty_Cycle; ------------------------- -- Configure_PWM_Timer -- ------------------------- procedure Configure_PWM_Timer (Generator : not null access Timer; Frequency : Hertz) is Computed_Prescalar : UInt32; Computed_Period : UInt32; begin Enable_Clock (Generator.all); Compute_Prescalar_And_Period (Generator, Requested_Frequency => Frequency, Prescalar => Computed_Prescalar, Period => Computed_Period); Computed_Period := Computed_Period - 1; Configure (Generator.all, Prescaler => UInt16 (Computed_Prescalar), Period => Computed_Period, Clock_Divisor => Div1, Counter_Mode => Up); Set_Autoreload_Preload (Generator.all, True); if Advanced_Timer (Generator.all) then Enable_Main_Output (Generator.all); end if; Enable (Generator.all); end Configure_PWM_Timer; ------------------------ -- Attach_PWM_Channel -- ------------------------ procedure Attach_PWM_Channel (This : in out PWM_Modulator; Generator : not null access Timer; Channel : Timer_Channel; Point : GPIO_Point; PWM_AF : GPIO_Alternate_Function; Polarity : Timer_Output_Compare_Polarity := High) is begin This.Channel := Channel; This.Generator := Generator; Enable_Clock (Point); Configure_PWM_GPIO (Point, PWM_AF); Configure_Channel_Output (This.Generator.all, Channel => Channel, Mode => PWM1, State => Disable, Pulse => 0, Polarity => Polarity); Set_Compare_Value (This.Generator.all, Channel, UInt16 (0)); Disable_Channel (This.Generator.all, Channel); end Attach_PWM_Channel; ------------------------ -- Attach_PWM_Channel -- ------------------------ procedure Attach_PWM_Channel (This : in out PWM_Modulator; Generator : not null access Timer; Channel : Timer_Channel; Point : GPIO_Point; Complementary_Point : GPIO_Point; PWM_AF : GPIO_Alternate_Function; Polarity : Timer_Output_Compare_Polarity; Idle_State : Timer_Capture_Compare_State; Complementary_Polarity : Timer_Output_Compare_Polarity; Complementary_Idle_State : Timer_Capture_Compare_State) is begin This.Channel := Channel; This.Generator := Generator; Enable_Clock (Point); Enable_Clock (Complementary_Point); Configure_PWM_GPIO (Point, PWM_AF); Configure_PWM_GPIO (Complementary_Point, PWM_AF); Configure_Channel_Output (This.Generator.all, Channel => Channel, Mode => PWM1, State => Disable, Pulse => 0, Polarity => Polarity, Idle_State => Idle_State, Complementary_Polarity => Complementary_Polarity, Complementary_Idle_State => Complementary_Idle_State); Set_Compare_Value (This.Generator.all, Channel, UInt16 (0)); Disable_Channel (This.Generator.all, Channel); end Attach_PWM_Channel; ------------------- -- Enable_Output -- ------------------- procedure Enable_Output (This : in out PWM_Modulator) is begin Enable_Channel (This.Generator.all, This.Channel); end Enable_Output; --------------------------------- -- Enable_Complementary_Output -- --------------------------------- procedure Enable_Complementary_Output (This : in out PWM_Modulator) is begin Enable_Complementary_Channel (This.Generator.all, This.Channel); end Enable_Complementary_Output; -------------------- -- Output_Enabled -- -------------------- function Output_Enabled (This : PWM_Modulator) return Boolean is begin return Channel_Enabled (This.Generator.all, This.Channel); end Output_Enabled; ---------------------------------- -- Complementary_Output_Enabled -- ---------------------------------- function Complementary_Output_Enabled (This : PWM_Modulator) return Boolean is begin return Complementary_Channel_Enabled (This.Generator.all, This.Channel); end Complementary_Output_Enabled; -------------------- -- Disable_Output -- -------------------- procedure Disable_Output (This : in out PWM_Modulator) is begin Disable_Channel (This.Generator.all, This.Channel); end Disable_Output; ---------------------------------- -- Disable_Complementary_Output -- ---------------------------------- procedure Disable_Complementary_Output (This : in out PWM_Modulator) is begin Disable_Complementary_Channel (This.Generator.all, This.Channel); end Disable_Complementary_Output; ------------------ -- Set_Polarity -- ------------------ procedure Set_Polarity (This : in PWM_Modulator; Polarity : in Timer_Output_Compare_Polarity) is begin Set_Output_Polarity (This.Generator.all, This.Channel, Polarity); end Set_Polarity; -------------------------------- -- Set_Complementary_Polarity -- -------------------------------- procedure Set_Complementary_Polarity (This : in PWM_Modulator; Polarity : in Timer_Output_Compare_Polarity) is begin Set_Output_Complementary_Polarity (This.Generator.all, This.Channel, Polarity); end Set_Complementary_Polarity; ------------------------ -- Configure_PWM_GPIO -- ------------------------ procedure Configure_PWM_GPIO (Output : GPIO_Point; PWM_AF : GPIO_Alternate_Function) is Configuration : GPIO_Port_Configuration; begin Configuration.Mode := Mode_AF; Configuration.Output_Type := Push_Pull; Configuration.Speed := Speed_100MHz; Configuration.Resistors := Floating; Output.Configure_IO (Configuration); Output.Configure_Alternate_Function (PWM_AF); Output.Lock; end Configure_PWM_GPIO; ---------------------------------- -- Compute_Prescalar_and_Period -- ---------------------------------- procedure Compute_Prescalar_And_Period (This : access Timer; Requested_Frequency : Hertz; Prescalar : out UInt32; Period : out UInt32) is Max_Prescalar : constant := 16#FFFF#; Max_Period : UInt32; Hardware_Frequency : UInt32; Clocks : constant RCC_System_Clocks := System_Clock_Frequencies; CK_CNT : UInt32; begin if Has_APB1_Frequency (This.all) then Hardware_Frequency := Clocks.TIMCLK1; elsif Has_APB2_Frequency (This.all) then Hardware_Frequency := Clocks.TIMCLK2; else raise Unknown_Timer; end if; if Has_32bit_Counter (This.all) then Max_Period := 16#FFFF_FFFF#; else Max_Period := 16#FFFF#; end if; if Requested_Frequency > Hardware_Frequency then raise Invalid_Request with "Freq too high"; end if; Prescalar := 0; loop -- Compute the Counter's clock CK_CNT := Hardware_Frequency / (Prescalar + 1); -- Determine the CK_CNT periods to achieve the requested frequency Period := CK_CNT / Requested_Frequency; exit when not ((Period > Max_Period) and (Prescalar <= Max_Prescalar)); Prescalar := Prescalar + 1; end loop; if Prescalar > Max_Prescalar then raise Invalid_Request with "Freq too low"; end if; end Compute_Prescalar_And_Period; ----------------------------- -- Microseconds_Per_Period -- ----------------------------- function Microseconds_Per_Period (This : PWM_Modulator) return Microseconds is Result : UInt32; Counter_Frequency : UInt32; Platform_Frequency : UInt32; Clocks : constant RCC_System_Clocks := System_Clock_Frequencies; Period : constant UInt32 := Timer_Period (This) + 1; Prescalar : constant UInt16 := Current_Prescaler (This.Generator.all) + 1; begin if Has_APB1_Frequency (This.Generator.all) then Platform_Frequency := Clocks.TIMCLK1; else Platform_Frequency := Clocks.TIMCLK2; end if; Counter_Frequency := (Platform_Frequency / UInt32 (Prescalar)) / Period; Result := 1_000_000 / Counter_Frequency; return Result; end Microseconds_Per_Period; ------------------------ -- Has_APB2_Frequency -- ------------------------ function Has_APB2_Frequency (This : Timer) return Boolean is (This'Address = STM32_SVD.TIM1_Base or This'Address = STM32_SVD.TIM8_Base or This'Address = STM32_SVD.TIM9_Base or This'Address = STM32_SVD.TIM10_Base or This'Address = STM32_SVD.TIM11_Base); ------------------------ -- Has_APB1_Frequency -- ------------------------ function Has_APB1_Frequency (This : Timer) return Boolean is (This'Address = STM32_SVD.TIM2_Base or This'Address = STM32_SVD.TIM3_Base or This'Address = STM32_SVD.TIM4_Base or This'Address = STM32_SVD.TIM5_Base or This'Address = STM32_SVD.TIM6_Base or This'Address = STM32_SVD.TIM7_Base or This'Address = STM32_SVD.TIM12_Base or This'Address = STM32_SVD.TIM13_Base or This'Address = STM32_SVD.TIM14_Base); end STM32.PWM;
Handle 32 bits timers
STM32.PWM: Handle 32 bits timers
Ada
bsd-3-clause
Fabien-Chouteau/Ada_Drivers_Library,simonjwright/Ada_Drivers_Library,AdaCore/Ada_Drivers_Library,simonjwright/Ada_Drivers_Library,Fabien-Chouteau/Ada_Drivers_Library,AdaCore/Ada_Drivers_Library
bd4e2546526bd87a6539803485b34671ab999883
src/gen-model-enums.adb
src/gen-model-enums.adb
----------------------------------------------------------------------- -- gen-model-enums -- Enum definitions -- 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. ----------------------------------------------------------------------- package body Gen.Model.Enums is -- ------------------------------ -- 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 : Value_Definition; Name : String) return Util.Beans.Objects.Object is begin if Name = "value" then return Util.Beans.Objects.To_Object (From.Number); else return Definition (From).Get_Value (Name); end if; end Get_Value; -- ------------------------------ -- 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 : Enum_Definition; Name : String) return Util.Beans.Objects.Object is begin if Name = "values" then return From.Values_Bean; elsif Name = "name" then return Util.Beans.Objects.To_Object (From.Type_Name); elsif Name = "isEnum" then return Util.Beans.Objects.To_Object (True); else return Mappings.Mapping_Definition (From).Get_Value (Name); end if; end Get_Value; -- ------------------------------ -- Prepare the generation of the model. -- ------------------------------ overriding procedure Prepare (O : in out Enum_Definition) is begin O.Target := O.Type_Name; null; end Prepare; -- ------------------------------ -- Initialize the table definition instance. -- ------------------------------ overriding procedure Initialize (O : in out Enum_Definition) is begin O.Values_Bean := Util.Beans.Objects.To_Object (O.Values'Unchecked_Access, Util.Beans.Objects.STATIC); end Initialize; -- ------------------------------ -- Add an enum value to this enum definition and return the new value. -- ------------------------------ procedure Add_Value (Enum : in out Enum_Definition; Name : in String; Value : out Value_Definition_Access) is begin Value := new Value_Definition; Value.Name := To_Unbounded_String (Name); Value.Number := Enum.Values.Get_Count; Enum.Values.Append (Value); end Add_Value; -- ------------------------------ -- Create an enum with the given name. -- ------------------------------ function Create_Enum (Name : in Unbounded_String) return Enum_Definition_Access is Enum : constant Enum_Definition_Access := new Enum_Definition; begin Enum.Name := Name; declare Pos : constant Natural := Index (Enum.Name, ".", Ada.Strings.Backward); begin if Pos > 0 then Enum.Pkg_Name := Unbounded_Slice (Enum.Name, 1, Pos - 1); Enum.Type_Name := Unbounded_Slice (Enum.Name, Pos + 1, Length (Enum.Name)); else Enum.Pkg_Name := To_Unbounded_String ("ADO"); Enum.Type_Name := Enum.Name; end if; end; return Enum; end Create_Enum; end Gen.Model.Enums;
----------------------------------------------------------------------- -- gen-model-enums -- Enum definitions -- 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. ----------------------------------------------------------------------- package body Gen.Model.Enums is -- ------------------------------ -- 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 : Value_Definition; Name : String) return Util.Beans.Objects.Object is begin if Name = "value" then return Util.Beans.Objects.To_Object (From.Number); else return Definition (From).Get_Value (Name); end if; end Get_Value; -- ------------------------------ -- 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 : Enum_Definition; Name : String) return Util.Beans.Objects.Object is begin if Name = "values" then return From.Values_Bean; elsif Name = "name" then return Util.Beans.Objects.To_Object (From.Type_Name); elsif Name = "isEnum" then return Util.Beans.Objects.To_Object (True); elsif Name = "sqlType" then return Util.Beans.Objects.To_Object (From.Sql_Type); else return Mappings.Mapping_Definition (From).Get_Value (Name); end if; end Get_Value; -- ------------------------------ -- Prepare the generation of the model. -- ------------------------------ overriding procedure Prepare (O : in out Enum_Definition) is begin O.Target := O.Type_Name; null; end Prepare; -- ------------------------------ -- Initialize the table definition instance. -- ------------------------------ overriding procedure Initialize (O : in out Enum_Definition) is begin O.Values_Bean := Util.Beans.Objects.To_Object (O.Values'Unchecked_Access, Util.Beans.Objects.STATIC); end Initialize; -- ------------------------------ -- Add an enum value to this enum definition and return the new value. -- ------------------------------ procedure Add_Value (Enum : in out Enum_Definition; Name : in String; Value : out Value_Definition_Access) is begin Value := new Value_Definition; Value.Name := To_Unbounded_String (Name); Value.Number := Enum.Values.Get_Count; Enum.Values.Append (Value); end Add_Value; -- ------------------------------ -- Create an enum with the given name. -- ------------------------------ function Create_Enum (Name : in Unbounded_String) return Enum_Definition_Access is Enum : constant Enum_Definition_Access := new Enum_Definition; begin Enum.Name := Name; declare Pos : constant Natural := Index (Enum.Name, ".", Ada.Strings.Backward); begin if Pos > 0 then Enum.Pkg_Name := Unbounded_Slice (Enum.Name, 1, Pos - 1); Enum.Type_Name := Unbounded_Slice (Enum.Name, Pos + 1, Length (Enum.Name)); else Enum.Pkg_Name := To_Unbounded_String ("ADO"); Enum.Type_Name := Enum.Name; end if; end; return Enum; end Create_Enum; end Gen.Model.Enums;
Add support for the sqlType bean attribute
Add support for the sqlType bean attribute
Ada
apache-2.0
stcarrez/dynamo,stcarrez/dynamo,stcarrez/dynamo
0cb604a87badb1b32915f170ad018579fa9c0b66
matp/src/mat-expressions.adb
matp/src/mat-expressions.adb
----------------------------------------------------------------------- -- mat-expressions -- Expressions for event and memory slot selection -- 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.Unchecked_Deallocation; with MAT.Expressions.Parser; package body MAT.Expressions is procedure Free is new Ada.Unchecked_Deallocation (Object => Node_Type, Name => Node_Type_Access); -- Destroy recursively the node, releasing the storage. procedure Destroy (Node : in out Node_Type_Access); -- ------------------------------ -- Create a NOT expression node. -- ------------------------------ function Create_Not (Expr : in Expression_Type) return Expression_Type is Result : Expression_Type; begin Result.Node := new Node_Type'(Ref_Counter => Util.Concurrent.Counters.ONE, Kind => N_NOT, Expr => Expr.Node); Util.Concurrent.Counters.Increment (Expr.Node.Ref_Counter); return Result; end Create_Not; -- ------------------------------ -- Create a AND expression node. -- ------------------------------ function Create_And (Left : in Expression_Type; Right : in Expression_Type) return Expression_Type is Result : Expression_Type; begin Result.Node := new Node_Type'(Ref_Counter => Util.Concurrent.Counters.ONE, Kind => N_AND, Left => Left.Node, Right => Right.Node); Util.Concurrent.Counters.Increment (Left.Node.Ref_Counter); Util.Concurrent.Counters.Increment (Right.Node.Ref_Counter); return Result; end Create_And; -- ------------------------------ -- Create a OR expression node. -- ------------------------------ function Create_Or (Left : in Expression_Type; Right : in Expression_Type) return Expression_Type is Result : Expression_Type; begin Result.Node := new Node_Type'(Ref_Counter => Util.Concurrent.Counters.ONE, Kind => N_OR, Left => Left.Node, Right => Right.Node); Util.Concurrent.Counters.Increment (Left.Node.Ref_Counter); Util.Concurrent.Counters.Increment (Right.Node.Ref_Counter); return Result; end Create_Or; -- ------------------------------ -- Create an INSIDE expression node. -- ------------------------------ function Create_Inside (Name : in Ada.Strings.Unbounded.Unbounded_String; Kind : in Inside_Type) return Expression_Type is Result : Expression_Type; begin Result.Node := new Node_Type'(Ref_Counter => Util.Concurrent.Counters.ONE, Kind => N_INSIDE, Name => Name, Inside => Kind); return Result; end Create_Inside; -- ------------------------------ -- Create an size range expression node. -- ------------------------------ function Create_Size (Min : in MAT.Types.Target_Size; Max : in MAT.Types.Target_Size) return Expression_Type is Result : Expression_Type; begin Result.Node := new Node_Type'(Ref_Counter => Util.Concurrent.Counters.ONE, Kind => N_RANGE_SIZE, Min_Size => Min, Max_Size => Max); return Result; end Create_Size; -- ------------------------------ -- Create an addr range expression node. -- ------------------------------ function Create_Addr (Min : in MAT.Types.Target_Addr; Max : in MAT.Types.Target_Addr) return Expression_Type is Result : Expression_Type; begin Result.Node := new Node_Type'(Ref_Counter => Util.Concurrent.Counters.ONE, Kind => N_RANGE_ADDR, Min_Addr => Min, Max_Addr => Max); return Result; end Create_Addr; -- ------------------------------ -- Create an time range expression node. -- ------------------------------ function Create_Time (Min : in MAT.Types.Target_Tick_Ref; Max : in MAT.Types.Target_Tick_Ref) return Expression_Type is Result : Expression_Type; begin Result.Node := new Node_Type'(Ref_Counter => Util.Concurrent.Counters.ONE, Kind => N_RANGE_TIME, Min_Time => Min, Max_Time => Max); return Result; end Create_Time; -- ------------------------------ -- Create a thread ID range expression node. -- ------------------------------ function Create_Thread (Min : in MAT.Types.Target_Thread_Ref; Max : in MAT.Types.Target_Thread_Ref) return Expression_Type is Result : Expression_Type; begin Result.Node := new Node_Type'(Ref_Counter => Util.Concurrent.Counters.ONE, Kind => N_THREAD, Min_Thread => Min, Max_Thread => Max); return Result; end Create_Thread; -- ------------------------------ -- Create a event type expression check. -- ------------------------------ function Create_Event_Type (Event_Kind : in MAT.Events.Targets.Probe_Index_Type) return Expression_Type is Result : Expression_Type; begin Result.Node := new Node_Type'(Ref_Counter => Util.Concurrent.Counters.ONE, Kind => N_TYPE, Event_Kind => Event_Kind); return Result; end Create_Event_Type; -- ------------------------------ -- Create an event ID range expression node. -- ------------------------------ function Create_Event (Min : in MAT.Events.Targets.Event_Id_Type; Max : in MAT.Events.Targets.Event_Id_Type) return Expression_Type is Result : Expression_Type; begin Result.Node := new Node_Type'(Ref_Counter => Util.Concurrent.Counters.ONE, Kind => N_EVENT, Min_Event => Min, Max_Event => Max); return Result; end Create_Event; -- ------------------------------ -- Evaluate the expression to check if the memory slot described by the -- context is selected. Returns True if the memory slot is selected. -- ------------------------------ function Is_Selected (Node : in Expression_Type; Addr : in MAT.Types.Target_Addr; Allocation : in MAT.Memory.Allocation) return Boolean is begin if Node.Node = null then return True; else return Is_Selected (Node.Node.all, Addr, Allocation); end if; end Is_Selected; -- ------------------------------ -- Evaluate the expression to check if the event described by the -- context is selected. Returns True if the event is selected. -- ------------------------------ function Is_Selected (Node : in Expression_Type; Event : in MAT.Events.Targets.Probe_Event_Type) return Boolean is begin return Is_Selected (Node.Node.all, Event); end Is_Selected; -- ------------------------------ -- Evaluate the node against the context. Returns True if the node expression -- selects the memory slot defined by the context. -- ------------------------------ function Is_Selected (Node : in Node_Type; Addr : in MAT.Types.Target_Addr; Allocation : in MAT.Memory.Allocation) return Boolean is use type MAT.Types.Target_Size; use type MAT.Types.Target_Tick_Ref; begin case Node.Kind is when N_NOT => return not Is_Selected (Node.Expr.all, Addr, Allocation); when N_AND => return Is_Selected (Node.Left.all, Addr, Allocation) and then Is_Selected (Node.Right.all, Addr, Allocation); when N_OR => return Is_Selected (Node.Left.all, Addr, Allocation) or else Is_Selected (Node.Right.all, Addr, Allocation); when N_RANGE_SIZE => return Allocation.Size >= Node.Min_Size and Allocation.Size <= Node.Max_Size; when N_RANGE_ADDR => return Addr >= Node.Min_Addr and Addr <= Node.Max_Addr; when N_RANGE_TIME => return Allocation.Time >= Node.Min_Time and Allocation.Time <= Node.Max_Time; when others => return False; end case; end Is_Selected; -- ------------------------------ -- Evaluate the expression to check if the event described by the -- context is selected. Returns True if the event is selected. -- ------------------------------ function Is_Selected (Node : in Node_Type; Event : in MAT.Events.Targets.Probe_Event_Type) return Boolean is use type MAT.Types.Target_Size; use type MAT.Types.Target_Tick_Ref; use type MAT.Types.Target_Thread_Ref; use type MAT.Events.Targets.Event_Id_Type; use type MAT.Events.Targets.Probe_Index_Type; begin case Node.Kind is when N_NOT => return not Is_Selected (Node.Expr.all, Event); when N_AND => return Is_Selected (Node.Left.all, Event) and then Is_Selected (Node.Right.all, Event); when N_OR => return Is_Selected (Node.Left.all, Event) or else Is_Selected (Node.Right.all, Event); when N_RANGE_SIZE => return Event.Size >= Node.Min_Size and Event.Size <= Node.Max_Size; when N_RANGE_ADDR => return Event.Addr >= Node.Min_Addr and Event.Addr <= Node.Max_Addr; when N_RANGE_TIME => return Event.Time >= Node.Min_Time and Event.Time <= Node.Max_Time; when N_EVENT => return Event.Id >= Node.Min_Event and Event.Id <= Node.Max_Event; when N_THREAD => return Event.Thread >= Node.Min_Thread and Event.Thread <= Node.Max_Thread; when N_TYPE => return Event.Index = Node.Event_Kind; when others => return False; end case; end Is_Selected; -- ------------------------------ -- Parse the string and return the expression tree. -- ------------------------------ function Parse (Expr : in String) return Expression_Type is begin return MAT.Expressions.Parser.Parse (Expr); end Parse; -- ------------------------------ -- Destroy recursively the node, releasing the storage. -- ------------------------------ procedure Destroy (Node : in out Node_Type_Access) is Release : Boolean; begin if Node /= null then Util.Concurrent.Counters.Decrement (Node.Ref_Counter, Release); if Release then case Node.Kind is when N_NOT => Destroy (Node.Expr); when N_AND | N_OR => Destroy (Node.Left); Destroy (Node.Right); when others => null; end case; Free (Node); else Node := null; end if; end if; end Destroy; -- ------------------------------ -- Release the reference and destroy the expression tree if it was the last reference. -- ------------------------------ overriding procedure Finalize (Obj : in out Expression_Type) is begin if Obj.Node /= null then Destroy (Obj.Node); end if; end Finalize; -- ------------------------------ -- Update the reference after an assignment. -- ------------------------------ overriding procedure Adjust (Obj : in out Expression_Type) is begin if Obj.Node /= null then Util.Concurrent.Counters.Increment (Obj.Node.Ref_Counter); end if; end Adjust; end MAT.Expressions;
----------------------------------------------------------------------- -- mat-expressions -- Expressions for event and memory slot selection -- 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.Unchecked_Deallocation; with MAT.Expressions.Parser; package body MAT.Expressions is procedure Free is new Ada.Unchecked_Deallocation (Object => Node_Type, Name => Node_Type_Access); -- Destroy recursively the node, releasing the storage. procedure Destroy (Node : in out Node_Type_Access); -- ------------------------------ -- Create a NOT expression node. -- ------------------------------ function Create_Not (Expr : in Expression_Type) return Expression_Type is Result : Expression_Type; begin Result.Node := new Node_Type'(Ref_Counter => Util.Concurrent.Counters.ONE, Kind => N_NOT, Expr => Expr.Node); Util.Concurrent.Counters.Increment (Expr.Node.Ref_Counter); return Result; end Create_Not; -- ------------------------------ -- Create a AND expression node. -- ------------------------------ function Create_And (Left : in Expression_Type; Right : in Expression_Type) return Expression_Type is Result : Expression_Type; begin Result.Node := new Node_Type'(Ref_Counter => Util.Concurrent.Counters.ONE, Kind => N_AND, Left => Left.Node, Right => Right.Node); Util.Concurrent.Counters.Increment (Left.Node.Ref_Counter); Util.Concurrent.Counters.Increment (Right.Node.Ref_Counter); return Result; end Create_And; -- ------------------------------ -- Create a OR expression node. -- ------------------------------ function Create_Or (Left : in Expression_Type; Right : in Expression_Type) return Expression_Type is Result : Expression_Type; begin Result.Node := new Node_Type'(Ref_Counter => Util.Concurrent.Counters.ONE, Kind => N_OR, Left => Left.Node, Right => Right.Node); Util.Concurrent.Counters.Increment (Left.Node.Ref_Counter); Util.Concurrent.Counters.Increment (Right.Node.Ref_Counter); return Result; end Create_Or; -- ------------------------------ -- Create an INSIDE expression node. -- ------------------------------ function Create_Inside (Name : in Ada.Strings.Unbounded.Unbounded_String; Kind : in Inside_Type) return Expression_Type is Result : Expression_Type; begin Result.Node := new Node_Type'(Ref_Counter => Util.Concurrent.Counters.ONE, Kind => N_INSIDE, Name => Name, Inside => Kind); return Result; end Create_Inside; -- ------------------------------ -- Create an size range expression node. -- ------------------------------ function Create_Size (Min : in MAT.Types.Target_Size; Max : in MAT.Types.Target_Size) return Expression_Type is Result : Expression_Type; begin Result.Node := new Node_Type'(Ref_Counter => Util.Concurrent.Counters.ONE, Kind => N_RANGE_SIZE, Min_Size => Min, Max_Size => Max); return Result; end Create_Size; -- ------------------------------ -- Create an addr range expression node. -- ------------------------------ function Create_Addr (Min : in MAT.Types.Target_Addr; Max : in MAT.Types.Target_Addr) return Expression_Type is Result : Expression_Type; begin Result.Node := new Node_Type'(Ref_Counter => Util.Concurrent.Counters.ONE, Kind => N_HAS_ADDR, Min_Addr => Min, Max_Addr => Max); return Result; end Create_Addr; -- ------------------------------ -- Create an time range expression node. -- ------------------------------ function Create_Time (Min : in MAT.Types.Target_Tick_Ref; Max : in MAT.Types.Target_Tick_Ref) return Expression_Type is Result : Expression_Type; begin Result.Node := new Node_Type'(Ref_Counter => Util.Concurrent.Counters.ONE, Kind => N_RANGE_TIME, Min_Time => Min, Max_Time => Max); return Result; end Create_Time; -- ------------------------------ -- Create a thread ID range expression node. -- ------------------------------ function Create_Thread (Min : in MAT.Types.Target_Thread_Ref; Max : in MAT.Types.Target_Thread_Ref) return Expression_Type is Result : Expression_Type; begin Result.Node := new Node_Type'(Ref_Counter => Util.Concurrent.Counters.ONE, Kind => N_THREAD, Min_Thread => Min, Max_Thread => Max); return Result; end Create_Thread; -- ------------------------------ -- Create a event type expression check. -- ------------------------------ function Create_Event_Type (Event_Kind : in MAT.Events.Targets.Probe_Index_Type) return Expression_Type is Result : Expression_Type; begin Result.Node := new Node_Type'(Ref_Counter => Util.Concurrent.Counters.ONE, Kind => N_TYPE, Event_Kind => Event_Kind); return Result; end Create_Event_Type; -- ------------------------------ -- Create an event ID range expression node. -- ------------------------------ function Create_Event (Min : in MAT.Events.Targets.Event_Id_Type; Max : in MAT.Events.Targets.Event_Id_Type) return Expression_Type is Result : Expression_Type; begin Result.Node := new Node_Type'(Ref_Counter => Util.Concurrent.Counters.ONE, Kind => N_EVENT, Min_Event => Min, Max_Event => Max); return Result; end Create_Event; -- ------------------------------ -- Evaluate the expression to check if the memory slot described by the -- context is selected. Returns True if the memory slot is selected. -- ------------------------------ function Is_Selected (Node : in Expression_Type; Addr : in MAT.Types.Target_Addr; Allocation : in MAT.Memory.Allocation) return Boolean is begin if Node.Node = null then return True; else return Is_Selected (Node.Node.all, Addr, Allocation); end if; end Is_Selected; -- ------------------------------ -- Evaluate the expression to check if the event described by the -- context is selected. Returns True if the event is selected. -- ------------------------------ function Is_Selected (Node : in Expression_Type; Event : in MAT.Events.Targets.Probe_Event_Type) return Boolean is begin return Is_Selected (Node.Node.all, Event); end Is_Selected; -- ------------------------------ -- Evaluate the node against the context. Returns True if the node expression -- selects the memory slot defined by the context. -- ------------------------------ function Is_Selected (Node : in Node_Type; Addr : in MAT.Types.Target_Addr; Allocation : in MAT.Memory.Allocation) return Boolean is use type MAT.Types.Target_Size; use type MAT.Types.Target_Tick_Ref; begin case Node.Kind is when N_NOT => return not Is_Selected (Node.Expr.all, Addr, Allocation); when N_AND => return Is_Selected (Node.Left.all, Addr, Allocation) and then Is_Selected (Node.Right.all, Addr, Allocation); when N_OR => return Is_Selected (Node.Left.all, Addr, Allocation) or else Is_Selected (Node.Right.all, Addr, Allocation); when N_RANGE_SIZE => return Allocation.Size >= Node.Min_Size and Allocation.Size <= Node.Max_Size; when N_RANGE_ADDR => return Addr >= Node.Min_Addr and Addr <= Node.Max_Addr; when N_RANGE_TIME => return Allocation.Time >= Node.Min_Time and Allocation.Time <= Node.Max_Time; when others => return False; end case; end Is_Selected; -- ------------------------------ -- Evaluate the expression to check if the event described by the -- context is selected. Returns True if the event is selected. -- ------------------------------ function Is_Selected (Node : in Node_Type; Event : in MAT.Events.Targets.Probe_Event_Type) return Boolean is use type MAT.Types.Target_Size; use type MAT.Types.Target_Tick_Ref; use type MAT.Types.Target_Thread_Ref; use type MAT.Events.Targets.Event_Id_Type; use type MAT.Events.Targets.Probe_Index_Type; begin case Node.Kind is when N_NOT => return not Is_Selected (Node.Expr.all, Event); when N_AND => return Is_Selected (Node.Left.all, Event) and then Is_Selected (Node.Right.all, Event); when N_OR => return Is_Selected (Node.Left.all, Event) or else Is_Selected (Node.Right.all, Event); when N_RANGE_SIZE => return Event.Size >= Node.Min_Size and Event.Size <= Node.Max_Size; when N_RANGE_ADDR => return Event.Addr >= Node.Min_Addr and Event.Addr <= Node.Max_Addr; when N_RANGE_TIME => return Event.Time >= Node.Min_Time and Event.Time <= Node.Max_Time; when N_EVENT => return Event.Id >= Node.Min_Event and Event.Id <= Node.Max_Event; when N_THREAD => return Event.Thread >= Node.Min_Thread and Event.Thread <= Node.Max_Thread; when N_TYPE => return Event.Index = Node.Event_Kind; when N_HAS_ADDR => if Event.Index = MAT.Events.Targets.MSG_MALLOC or Event.Index = MAT.Events.Targets.MSG_REALLOC then return Event.Addr <= Node.Min_Addr and Event.Addr + Event.Size >= Node.Max_Addr; end if; return False; when others => return False; end case; end Is_Selected; -- ------------------------------ -- Parse the string and return the expression tree. -- ------------------------------ function Parse (Expr : in String) return Expression_Type is begin return MAT.Expressions.Parser.Parse (Expr); end Parse; -- ------------------------------ -- Destroy recursively the node, releasing the storage. -- ------------------------------ procedure Destroy (Node : in out Node_Type_Access) is Release : Boolean; begin if Node /= null then Util.Concurrent.Counters.Decrement (Node.Ref_Counter, Release); if Release then case Node.Kind is when N_NOT => Destroy (Node.Expr); when N_AND | N_OR => Destroy (Node.Left); Destroy (Node.Right); when others => null; end case; Free (Node); else Node := null; end if; end if; end Destroy; -- ------------------------------ -- Release the reference and destroy the expression tree if it was the last reference. -- ------------------------------ overriding procedure Finalize (Obj : in out Expression_Type) is begin if Obj.Node /= null then Destroy (Obj.Node); end if; end Finalize; -- ------------------------------ -- Update the reference after an assignment. -- ------------------------------ overriding procedure Adjust (Obj : in out Expression_Type) is begin if Obj.Node /= null then Util.Concurrent.Counters.Increment (Obj.Node.Ref_Counter); end if; end Adjust; end MAT.Expressions;
Implement N_HAS_ADDR to check for an allocation event that returns a memory slot that contains a given address
Implement N_HAS_ADDR to check for an allocation event that returns a memory slot that contains a given address
Ada
apache-2.0
stcarrez/mat,stcarrez/mat,stcarrez/mat