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
a20ec1c7146b1e9aa8b5a25fa484b0209eb5eae5
src/gen-model-packages.ads
src/gen-model-packages.ads
----------------------------------------------------------------------- -- gen-model-packages -- Packages holding model, query representation -- Copyright (C) 2009, 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.Containers.Hashed_Maps; with Ada.Strings.Unbounded; with Ada.Strings.Unbounded.Hash; with Util.Beans.Objects; with Util.Beans.Objects.Vectors; 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; -- ------------------------------ -- 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); -- 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; -- ------------------------------ -- 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; -- 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_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; -- 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); 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_Types : aliased List_Object; Used : Util.Beans.Objects.Object; -- A map of all types defined in this package. Types : Gen.Model.Mappings.Mapping_Maps.Map; -- The package Ada name Pkg_Name : Unbounded_String; -- The base name for the package (ex: gen-model-users) Base_Name : Unbounded_String; -- True if the package uses Ada.Calendar.Time Uses_Calendar_Time : Boolean := False; -- The global model (used to resolve types from other packages). Model : Model_Definition_Access; 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; end record; end Gen.Model.Packages;
----------------------------------------------------------------------- -- gen-model-packages -- Packages holding model, query representation -- Copyright (C) 2009, 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.Containers.Hashed_Maps; with Ada.Strings.Unbounded; with Ada.Strings.Unbounded.Hash; with Util.Beans.Objects; with Util.Beans.Objects.Vectors; 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; -- ------------------------------ -- 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); -- 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; -- 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_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; -- 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); 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_Types : aliased List_Object; Used : Util.Beans.Objects.Object; -- A map of all types defined in this package. Types : Gen.Model.Mappings.Mapping_Maps.Map; -- The package Ada name Pkg_Name : Unbounded_String; -- The base name for the package (ex: gen-model-users) Base_Name : Unbounded_String; -- True if the package uses Ada.Calendar.Time Uses_Calendar_Time : Boolean := False; -- The global model (used to resolve types from other packages). Model : Model_Definition_Access; 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; end record; end Gen.Model.Packages;
Define new function Get_Model
Define new function Get_Model
Ada
apache-2.0
Letractively/ada-gen,Letractively/ada-gen,Letractively/ada-gen,Letractively/ada-gen
a5ba0f4ba9dc8093d47fd955ac9da8a37433d5eb
src/sys/http/util-http-headers.ads
src/sys/http/util-http-headers.ads
----------------------------------------------------------------------- -- util-http-headers -- HTTP Headers -- 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. ----------------------------------------------------------------------- package Util.Http.Headers is -- Some header names. Content_Type : constant String := "Content-Type"; Content_Length : constant String := "Content-Length"; Accept_Header : constant String := "Accept"; Accept_Language : constant String := "Accept-Language"; Location : constant String := "Location"; Cookie : constant String := "Cookie"; Cache_Control : constant String := "Cache-Control"; function To_Header (Date : in Ada.Calendar.Time) return String renames Util.Dates.RFC7231.Image; type Quality_Type is digits 4 range 0.0 .. 1.0; -- Split an accept like header into multiple tokens and a quality value. -- Invoke the `Process` procedure for each token. Example: -- -- Accept-Language: de, en;q=0.7, jp, fr;q=0.8, ru -- -- The `Process` will be called for "de", "en" with quality 0.7, -- and "jp", "fr" with quality 0.8 and then "ru" with quality 1.0. procedure Split_Header (Header : in String; Process : access procedure (Item : in String; Quality : in Quality_Type)); end Util.Http.Headers;
----------------------------------------------------------------------- -- util-http-headers -- HTTP Headers -- 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.Dates.RFC7231; package Util.Http.Headers is -- Some header names. Content_Type : constant String := "Content-Type"; Content_Length : constant String := "Content-Length"; Accept_Header : constant String := "Accept"; Accept_Language : constant String := "Accept-Language"; Location : constant String := "Location"; Cookie : constant String := "Cookie"; Cache_Control : constant String := "Cache-Control"; function To_Header (Date : in Ada.Calendar.Time) return String renames Util.Dates.RFC7231.Image; type Quality_Type is digits 4 range 0.0 .. 1.0; -- Split an accept like header into multiple tokens and a quality value. -- Invoke the `Process` procedure for each token. Example: -- -- Accept-Language: de, en;q=0.7, jp, fr;q=0.8, ru -- -- The `Process` will be called for "de", "en" with quality 0.7, -- and "jp", "fr" with quality 0.8 and then "ru" with quality 1.0. procedure Split_Header (Header : in String; Process : access procedure (Item : in String; Quality : in Quality_Type)); end Util.Http.Headers;
Update missing with clause
Update missing with clause
Ada
apache-2.0
stcarrez/ada-util,stcarrez/ada-util
1617234589c5cd7d283ea22af17f93fecd05acff
src/natools-web-acl-sx_backends.adb
src/natools-web-acl-sx_backends.adb
------------------------------------------------------------------------------ -- Copyright (c) 2017-2019, 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; package body Natools.Web.ACL.Sx_Backends is type User_Builder is record Tokens, Groups : Containers.Unsafe_Atom_Lists.List; end record; Cookie_Name : constant String := "User-Token"; procedure Process_User (Builder : in out Token_Maps.Unsafe_Maps.Map; Context : in Meaningless_Type; Name : in S_Expressions.Atom; Arguments : in out Natools.S_Expressions.Lockable.Descriptor'Class); procedure Process_User_Element (Builder : in out User_Builder; Context : in Meaningless_Type; Name : in S_Expressions.Atom; Arguments : in out Natools.S_Expressions.Lockable.Descriptor'Class); procedure Read_DB is new S_Expressions.Interpreter_Loop (Token_Maps.Unsafe_Maps.Map, Meaningless_Type, Process_User); procedure Read_User is new S_Expressions.Interpreter_Loop (User_Builder, Meaningless_Type, Process_User_Element); -------------------------- -- Constructor Elements -- -------------------------- procedure Process_User (Builder : in out Token_Maps.Unsafe_Maps.Map; Context : in Meaningless_Type; Name : in S_Expressions.Atom; Arguments : in out Natools.S_Expressions.Lockable.Descriptor'Class) is pragma Unreferenced (Context); User : User_Builder; Identity : Containers.Identity; begin Read_User (Arguments, User, Meaningless_Value); Identity := (User => S_Expressions.Atom_Ref_Constructors.Create (Name), Groups => Containers.Create (User.Groups)); for Token of User.Tokens loop Builder.Include (Token, Identity); end loop; end Process_User; procedure Process_User_Element (Builder : in out User_Builder; Context : in Meaningless_Type; Name : in S_Expressions.Atom; Arguments : in out Natools.S_Expressions.Lockable.Descriptor'Class) is pragma Unreferenced (Context); S_Name : constant String := S_Expressions.To_String (Name); begin if S_Name = "tokens" or else S_Name = "token" then Containers.Append_Atoms (Builder.Tokens, Arguments); elsif S_Name = "groups" or else S_Name = "group" then Containers.Append_Atoms (Builder.Groups, Arguments); else Log (Severities.Error, "Unknown user element """ & S_Name & '"'); end if; end Process_User_Element; ---------------------- -- Public Interface -- ---------------------- overriding procedure Authenticate (Self : in Backend; Exchange : in out Exchanges.Exchange) is Cursor : constant Token_Maps.Cursor := Self.Map.Find (S_Expressions.To_Atom (Exchange.Cookie (Cookie_Name))); Identity : Containers.Identity; begin if Token_Maps.Has_Element (Cursor) then Identity := Token_Maps.Element (Cursor); end if; Exchange.Set_Identity (Identity); end Authenticate; function Create (Arguments : in out S_Expressions.Lockable.Descriptor'Class) return ACL.Backend'Class is Map : Token_Maps.Unsafe_Maps.Map; begin case Arguments.Current_Event is when S_Expressions.Events.Open_List => Read_DB (Arguments, Map, Meaningless_Value); when S_Expressions.Events.Add_Atom => declare Reader : S_Expressions.File_Readers.S_Reader := S_Expressions.File_Readers.Reader (S_Expressions.To_String (Arguments.Current_Atom)); begin Read_DB (Reader, Map, Meaningless_Value); end; when others => Log (Severities.Error, "Unable to create ACL from S-expression" & " starting with " & Arguments.Current_Event'Img); end case; return Backend'(Map => Token_Maps.Create (Map)); end Create; procedure Register (Id : in Character; Fn : in Hash_Function) is begin if Fn = null then null; elsif Hash_Function_DB.Is_Empty then Hash_Function_DB.Replace (new Hash_Function_Array'(Id => Fn)); elsif Id in Hash_Function_DB.Query.Data.all'Range then Hash_Function_DB.Update.Data.all (Id) := Fn; else declare New_First : constant Hash_Id := Hash_Id'Min (Id, Hash_Function_DB.Query.Data.all'First); New_Last : constant Hash_Id := Hash_Id'Max (Id, Hash_Function_DB.Query.Data.all'Last); New_Data : constant Hash_Function_Array_Refs.Data_Access := new Hash_Function_Array'(New_First .. New_Last => null); begin New_Data (Hash_Function_DB.Query.Data.all'First .. Hash_Function_DB.Query.Data.all'Last) := Hash_Function_DB.Query.Data.all; Hash_Function_DB.Replace (New_Data); end; end if; end Register; end Natools.Web.ACL.Sx_Backends;
------------------------------------------------------------------------------ -- Copyright (c) 2017-2019, 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; package body Natools.Web.ACL.Sx_Backends is type User_Builder is record Tokens, Groups : Containers.Unsafe_Atom_Lists.List; end record; type Backend_Builder is record Map : Token_Maps.Unsafe_Maps.Map; end record; Cookie_Name : constant String := "User-Token"; procedure Process_User (Builder : in out Backend_Builder; Context : in Meaningless_Type; Name : in S_Expressions.Atom; Arguments : in out Natools.S_Expressions.Lockable.Descriptor'Class); procedure Process_User_Element (Builder : in out User_Builder; Context : in Meaningless_Type; Name : in S_Expressions.Atom; Arguments : in out Natools.S_Expressions.Lockable.Descriptor'Class); procedure Read_DB is new S_Expressions.Interpreter_Loop (Backend_Builder, Meaningless_Type, Process_User); procedure Read_User is new S_Expressions.Interpreter_Loop (User_Builder, Meaningless_Type, Process_User_Element); -------------------------- -- Constructor Elements -- -------------------------- procedure Process_User (Builder : in out Backend_Builder; Context : in Meaningless_Type; Name : in S_Expressions.Atom; Arguments : in out Natools.S_Expressions.Lockable.Descriptor'Class) is pragma Unreferenced (Context); User : User_Builder; Identity : Containers.Identity; begin Read_User (Arguments, User, Meaningless_Value); Identity := (User => S_Expressions.Atom_Ref_Constructors.Create (Name), Groups => Containers.Create (User.Groups)); for Token of User.Tokens loop Builder.Map.Include (Token, Identity); end loop; end Process_User; procedure Process_User_Element (Builder : in out User_Builder; Context : in Meaningless_Type; Name : in S_Expressions.Atom; Arguments : in out Natools.S_Expressions.Lockable.Descriptor'Class) is pragma Unreferenced (Context); S_Name : constant String := S_Expressions.To_String (Name); begin if S_Name = "tokens" or else S_Name = "token" then Containers.Append_Atoms (Builder.Tokens, Arguments); elsif S_Name = "groups" or else S_Name = "group" then Containers.Append_Atoms (Builder.Groups, Arguments); else Log (Severities.Error, "Unknown user element """ & S_Name & '"'); end if; end Process_User_Element; ---------------------- -- Public Interface -- ---------------------- overriding procedure Authenticate (Self : in Backend; Exchange : in out Exchanges.Exchange) is Cursor : constant Token_Maps.Cursor := Self.Map.Find (S_Expressions.To_Atom (Exchange.Cookie (Cookie_Name))); Identity : Containers.Identity; begin if Token_Maps.Has_Element (Cursor) then Identity := Token_Maps.Element (Cursor); end if; Exchange.Set_Identity (Identity); end Authenticate; function Create (Arguments : in out S_Expressions.Lockable.Descriptor'Class) return ACL.Backend'Class is Builder : Backend_Builder; begin case Arguments.Current_Event is when S_Expressions.Events.Open_List => Read_DB (Arguments, Builder, Meaningless_Value); when S_Expressions.Events.Add_Atom => declare Reader : S_Expressions.File_Readers.S_Reader := S_Expressions.File_Readers.Reader (S_Expressions.To_String (Arguments.Current_Atom)); begin Read_DB (Reader, Builder, Meaningless_Value); end; when others => Log (Severities.Error, "Unable to create ACL from S-expression" & " starting with " & Arguments.Current_Event'Img); end case; return Backend'(Map => Token_Maps.Create (Builder.Map)); end Create; procedure Register (Id : in Character; Fn : in Hash_Function) is begin if Fn = null then null; elsif Hash_Function_DB.Is_Empty then Hash_Function_DB.Replace (new Hash_Function_Array'(Id => Fn)); elsif Id in Hash_Function_DB.Query.Data.all'Range then Hash_Function_DB.Update.Data.all (Id) := Fn; else declare New_First : constant Hash_Id := Hash_Id'Min (Id, Hash_Function_DB.Query.Data.all'First); New_Last : constant Hash_Id := Hash_Id'Max (Id, Hash_Function_DB.Query.Data.all'Last); New_Data : constant Hash_Function_Array_Refs.Data_Access := new Hash_Function_Array'(New_First .. New_Last => null); begin New_Data (Hash_Function_DB.Query.Data.all'First .. Hash_Function_DB.Query.Data.all'Last) := Hash_Function_DB.Query.Data.all; Hash_Function_DB.Replace (New_Data); end; end if; end Register; end Natools.Web.ACL.Sx_Backends;
add a backend-builder type, to prepare for future complexity
acl-sx_backends: add a backend-builder type, to prepare for future complexity
Ada
isc
faelys/natools-web,faelys/natools-web
8593391bf0706a569ba5758c1185255f897307f6
src/wiki-buffers.adb
src/wiki-buffers.adb
----------------------------------------------------------------------- -- util-texts-builders -- Text builder -- Copyright (C) 2013, 2016, 2017, 2021, 2022 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Unchecked_Deallocation; package body Wiki.Buffers is subtype Input is Wiki.Strings.WString; subtype Block_Access is Buffer_Access; procedure Next (Content : in out Buffer_Access; Pos : in out Positive) is begin if Pos + 1 > Content.Last then Content := Content.Next_Block; Pos := 1; else Pos := Pos + 1; end if; end Next; -- ------------------------------ -- Get the length of the item builder. -- ------------------------------ function Length (Source : in Builder) return Natural is begin return Source.Length; end Length; -- ------------------------------ -- Get the capacity of the builder. -- ------------------------------ function Capacity (Source : in Builder) return Natural is B : constant Block_Access := Source.Current; begin return Source.Length + B.Len - B.Last; end Capacity; -- ------------------------------ -- Get the builder block size. -- ------------------------------ function Block_Size (Source : in Builder) return Positive is begin return Source.Block_Size; end Block_Size; -- ------------------------------ -- Set the block size for the allocation of next chunks. -- ------------------------------ procedure Set_Block_Size (Source : in out Builder; Size : in Positive) is begin Source.Block_Size := Size; end Set_Block_Size; -- ------------------------------ -- Append the <tt>New_Item</tt> at the end of the source growing the buffer if necessary. -- ------------------------------ procedure Append (Source : in out Builder; New_Item : in Input) is B : Block_Access := Source.Current; Start : Natural := New_Item'First; Last : constant Natural := New_Item'Last; begin while Start <= Last loop declare Space : Natural := B.Len - B.Last; Size : constant Natural := Last - Start + 1; begin if Space > Size then Space := Size; elsif Space = 0 then if Size > Source.Block_Size then B.Next_Block := new Buffer (Size); else B.Next_Block := new Buffer (Source.Block_Size); end if; B := B.Next_Block; Source.Current := B; if B.Len > Size then Space := Size; else Space := B.Len; end if; end if; B.Content (B.Last + 1 .. B.Last + Space) := New_Item (Start .. Start + Space - 1); Source.Length := Source.Length + Space; B.Last := B.Last + Space; Start := Start + Space; end; end loop; end Append; -- ------------------------------ -- Append the <tt>New_Item</tt> at the end of the source growing the buffer if necessary. -- ------------------------------ procedure Append (Source : in out Builder; New_Item : in Wiki.Strings.WChar) is B : Block_Access := Source.Current; begin if B.Len = B.Last then B.Next_Block := new Buffer (Source.Block_Size); B := B.Next_Block; Source.Current := B; end if; Source.Length := Source.Length + 1; B.Last := B.Last + 1; B.Content (B.Last) := New_Item; end Append; procedure Inline_Append (Source : in out Builder) is B : Block_Access := Source.Current; Last : Natural; begin loop if B.Len = B.Last then B.Next_Block := new Buffer (Source.Block_Size); B := B.Next_Block; Source.Current := B; end if; Process (B.Content (B.Last + 1 .. B.Len), Last); exit when Last > B.Len or Last <= B.Last; Source.Length := Source.Length + Last - B.Last; B.Last := Last; exit when Last < B.Len; end loop; end Inline_Append; -- ------------------------------ -- Append in `Into` builder the `Content` builder starting at `From` position -- and the up to and including the `To` position. -- ------------------------------ procedure Append (Into : in out Builder; Content : in Builder; From : in Positive; To : in Positive) is begin if From <= Content.First.Last then if To <= Content.First.Last then Append (Into, Content.First.Content (From .. To)); return; end if; Append (Into, Content.First.Content (From .. Content.First.Last)); end if; declare Pos : Integer := From - Into.First.Last; Last : Integer := To - Into.First.Last; B : Block_Access := Into.First.Next_Block; begin loop if B = null then return; end if; if Pos <= B.Last then if Last <= B.Last then Append (Into, B.Content (1 .. Last)); return; end if; Append (Into, B.Content (1 .. B.Last)); end if; Pos := Pos - B.Last; Last := Last - B.Last; B := B.Next_Block; end loop; end; end Append; procedure Append (Into : in out Builder; Buffer : in Buffer_Access; From : in Positive) is Block : Buffer_Access := Buffer; Pos : Positive := From; First : Positive := From; begin while Block /= null loop Append (Into, Block.Content (First .. Block.Last)); Block := Block.Next_Block; Pos := 1; First := 1; end loop; end Append; -- ------------------------------ -- Clear the source freeing any storage allocated for the buffer. -- ------------------------------ procedure Clear (Source : in out Builder) is procedure Free is new Ada.Unchecked_Deallocation (Object => Buffer, Name => Buffer_Access); Current, Next : Block_Access; begin Next := Source.First.Next_Block; while Next /= null loop Current := Next; Next := Current.Next_Block; Free (Current); end loop; Source.First.Next_Block := null; Source.First.Last := 0; Source.Current := Source.First'Unchecked_Access; Source.Length := 0; end Clear; -- ------------------------------ -- Iterate over the buffer content calling the <tt>Process</tt> procedure with each -- chunk. -- ------------------------------ procedure Iterate (Source : in Builder; Process : not null access procedure (Chunk : in Input)) is begin if Source.First.Last > 0 then Process (Source.First.Content (1 .. Source.First.Last)); declare B : Block_Access := Source.First.Next_Block; begin while B /= null loop Process (B.Content (1 .. B.Last)); B := B.Next_Block; end loop; end; end if; end Iterate; procedure Inline_Iterate (Source : in Builder) is begin if Source.First.Last > 0 then Process (Source.First.Content (1 .. Source.First.Last)); declare B : Block_Access := Source.First.Next_Block; begin while B /= null loop Process (B.Content (1 .. B.Last)); B := B.Next_Block; end loop; end; end if; end Inline_Iterate; procedure Inline_Update (Source : in out Builder) is begin if Source.First.Last > 0 then Process (Source.First.Content (1 .. Source.First.Last)); declare B : Block_Access := Source.First.Next_Block; begin while B /= null loop Process (B.Content (1 .. B.Last)); B := B.Next_Block; end loop; end; end if; end Inline_Update; -- ------------------------------ -- Return the content starting from the tail and up to <tt>Length</tt> items. -- ------------------------------ function Tail (Source : in Builder; Length : in Natural) return Input is Last : constant Natural := Source.Current.Last; begin if Last >= Length then return Source.Current.Content (Last - Length + 1 .. Last); elsif Length >= Source.Length then return To_Array (Source); else declare Result : Input (1 .. Length); Offset : Natural := Source.Length - Length; B : access constant Buffer := Source.First'Access; Src_Pos : Positive := 1; Dst_Pos : Positive := 1; Len : Natural; begin -- Skip the data moving to next blocks as needed. while Offset /= 0 loop if Offset < B.Last then Src_Pos := Offset + 1; Offset := 0; else Offset := Offset - B.Last + 1; B := B.Next_Block; end if; end loop; -- Copy what remains until we reach the length. while Dst_Pos <= Length loop Len := B.Last - Src_Pos + 1; Result (Dst_Pos .. Dst_Pos + Len - 1) := B.Content (Src_Pos .. B.Last); Src_Pos := 1; Dst_Pos := Dst_Pos + Len; B := B.Next_Block; end loop; return Result; end; end if; end Tail; -- ------------------------------ -- Get the buffer content as an array. -- ------------------------------ function To_Array (Source : in Builder) return Input is Result : Input (1 .. Source.Length); begin if Source.First.Last > 0 then declare Pos : Positive := Source.First.Last; B : Block_Access := Source.First.Next_Block; begin Result (1 .. Pos) := Source.First.Content (1 .. Pos); while B /= null loop Result (Pos + 1 .. Pos + B.Last) := B.Content (1 .. B.Last); Pos := Pos + B.Last; B := B.Next_Block; end loop; end; end if; return Result; end To_Array; -- ------------------------------ -- Get the element at the given position. -- ------------------------------ function Element (Source : in Builder; Position : in Positive) return Wiki.Strings.WChar is begin if Position <= Source.First.Last then return Source.First.Content (Position); else declare Pos : Positive := Position - Source.First.Last; B : Block_Access := Source.First.Next_Block; begin loop if Pos <= B.Last then return B.Content (Pos); end if; Pos := Pos - B.Last; B := B.Next_Block; end loop; end; end if; end Element; -- ------------------------------ -- Call the <tt>Process</tt> procedure with the full buffer content, trying to avoid -- secondary stack copies as much as possible. -- ------------------------------ procedure Get (Source : in Builder) is begin if Source.Length < Source.First.Len then Process (Source.First.Content (1 .. Source.Length)); else declare Content : constant Input := To_Array (Source); begin Process (Content); end; end if; end Get; -- ------------------------------ -- Setup the builder. -- ------------------------------ overriding procedure Initialize (Source : in out Builder) is begin Source.Current := Source.First'Unchecked_Access; end Initialize; -- ------------------------------ -- Finalize the builder releasing the storage. -- ------------------------------ overriding procedure Finalize (Source : in out Builder) is begin Clear (Source); end Finalize; function Count_Occurence (Buffer : in Buffer_Access; From : in Positive; Item : in Wiki.Strings.WChar) return Natural is Count : Natural := 0; Current : Buffer_Access := Buffer; Pos : Positive := From; begin while Current /= null loop declare First : Positive := Pos; Last : Natural := Current.Last; begin while Pos <= Last and then Current.Content (Pos) = Item loop Pos := Pos + 1; end loop; if Pos > First then Count := Count + Pos - First; end if; exit when Pos <= Last; end; Current := Current.Next_Block; Pos := 1; end loop; return Count; end Count_Occurence; procedure Count_Occurence (Buffer : in out Buffer_Access; From : in out Positive; Item : in Wiki.Strings.WChar; Count : out Natural) is Current : Buffer_Access := Buffer; Pos : Positive := From; begin Count := 0; while Current /= null loop declare First : Positive := From; Last : Natural := Current.Last; begin while Pos <= Last and then Current.Content (Pos) = Item loop Pos := Pos + 1; end loop; if Pos > First then Count := Count + Pos - First; end if; exit when Pos <= Last; end; Current := Current.Next_Block; Pos := 1; end loop; Buffer := Current; From := Pos; end Count_Occurence; procedure Find (Buffer : in out Buffer_Access; From : in out Positive; Item : in Wiki.Strings.WChar) is Pos : Positive := From; begin while Buffer /= null loop declare Last : constant Natural := Buffer.Last; begin while Pos <= Last loop if Buffer.Content (Pos) = Item then From := Pos; return; end if; Pos := Pos + 1; end loop; end; Buffer := Buffer.Next_Block; Pos := 1; end loop; end Find; end Wiki.Buffers;
----------------------------------------------------------------------- -- util-texts-builders -- Text builder -- Copyright (C) 2013, 2016, 2017, 2021, 2022 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Unchecked_Deallocation; package body Wiki.Buffers is subtype Input is Wiki.Strings.WString; subtype Block_Access is Buffer_Access; -- ------------------------------ -- Move forward to skip a number of items. -- ------------------------------ procedure Next (Content : in out Buffer_Access; Pos : in out Positive) is begin if Pos + 1 > Content.Last then Content := Content.Next_Block; Pos := 1; else Pos := Pos + 1; end if; end Next; procedure Next (Content : in out Buffer_Access; Pos : in out Positive; Count : in Natural) is begin for I in 1 .. Count loop if Pos + 1 > Content.Last then Content := Content.Next_Block; Pos := 1; else Pos := Pos + 1; end if; end loop; end Next; -- ------------------------------ -- Get the length of the item builder. -- ------------------------------ function Length (Source : in Builder) return Natural is begin return Source.Length; end Length; -- ------------------------------ -- Get the capacity of the builder. -- ------------------------------ function Capacity (Source : in Builder) return Natural is B : constant Block_Access := Source.Current; begin return Source.Length + B.Len - B.Last; end Capacity; -- ------------------------------ -- Get the builder block size. -- ------------------------------ function Block_Size (Source : in Builder) return Positive is begin return Source.Block_Size; end Block_Size; -- ------------------------------ -- Set the block size for the allocation of next chunks. -- ------------------------------ procedure Set_Block_Size (Source : in out Builder; Size : in Positive) is begin Source.Block_Size := Size; end Set_Block_Size; -- ------------------------------ -- Append the <tt>New_Item</tt> at the end of the source growing the buffer if necessary. -- ------------------------------ procedure Append (Source : in out Builder; New_Item : in Input) is B : Block_Access := Source.Current; Start : Natural := New_Item'First; Last : constant Natural := New_Item'Last; begin while Start <= Last loop declare Space : Natural := B.Len - B.Last; Size : constant Natural := Last - Start + 1; begin if Space > Size then Space := Size; elsif Space = 0 then if Size > Source.Block_Size then B.Next_Block := new Buffer (Size); else B.Next_Block := new Buffer (Source.Block_Size); end if; B.Next_Block.Offset := B.Offset + B.Len; B := B.Next_Block; Source.Current := B; if B.Len > Size then Space := Size; else Space := B.Len; end if; end if; B.Content (B.Last + 1 .. B.Last + Space) := New_Item (Start .. Start + Space - 1); Source.Length := Source.Length + Space; B.Last := B.Last + Space; Start := Start + Space; end; end loop; end Append; -- ------------------------------ -- Append the <tt>New_Item</tt> at the end of the source growing the buffer if necessary. -- ------------------------------ procedure Append (Source : in out Builder; New_Item : in Wiki.Strings.WChar) is B : Block_Access := Source.Current; begin if B.Len = B.Last then B.Next_Block := new Buffer (Source.Block_Size); B.Next_Block.Offset := B.Offset + B.Len; B := B.Next_Block; Source.Current := B; end if; Source.Length := Source.Length + 1; B.Last := B.Last + 1; B.Content (B.Last) := New_Item; end Append; procedure Inline_Append (Source : in out Builder) is B : Block_Access := Source.Current; Last : Natural; begin loop if B.Len = B.Last then B.Next_Block := new Buffer (Source.Block_Size); B.Next_Block.Offset := B.Offset + B.Len; B := B.Next_Block; Source.Current := B; end if; Process (B.Content (B.Last + 1 .. B.Len), Last); exit when Last > B.Len or Last <= B.Last; Source.Length := Source.Length + Last - B.Last; B.Last := Last; exit when Last < B.Len; end loop; end Inline_Append; -- ------------------------------ -- Append in `Into` builder the `Content` builder starting at `From` position -- and the up to and including the `To` position. -- ------------------------------ procedure Append (Into : in out Builder; Content : in Builder; From : in Positive; To : in Positive) is begin if From <= Content.First.Last then if To <= Content.First.Last then Append (Into, Content.First.Content (From .. To)); return; end if; Append (Into, Content.First.Content (From .. Content.First.Last)); end if; declare Pos : Integer := From - Into.First.Last; Last : Integer := To - Into.First.Last; B : Block_Access := Into.First.Next_Block; begin loop if B = null then return; end if; if Pos <= B.Last then if Last <= B.Last then Append (Into, B.Content (1 .. Last)); return; end if; Append (Into, B.Content (1 .. B.Last)); end if; Pos := Pos - B.Last; Last := Last - B.Last; B := B.Next_Block; end loop; end; end Append; procedure Append (Into : in out Builder; Buffer : in Buffer_Access; From : in Positive) is Block : Buffer_Access := Buffer; Pos : Positive := From; First : Positive := From; begin while Block /= null loop Append (Into, Block.Content (First .. Block.Last)); Block := Block.Next_Block; Pos := 1; First := 1; end loop; end Append; -- ------------------------------ -- Clear the source freeing any storage allocated for the buffer. -- ------------------------------ procedure Clear (Source : in out Builder) is procedure Free is new Ada.Unchecked_Deallocation (Object => Buffer, Name => Buffer_Access); Current, Next : Block_Access; begin Next := Source.First.Next_Block; while Next /= null loop Current := Next; Next := Current.Next_Block; Free (Current); end loop; Source.First.Next_Block := null; Source.First.Last := 0; Source.Current := Source.First'Unchecked_Access; Source.Length := 0; end Clear; -- ------------------------------ -- Iterate over the buffer content calling the <tt>Process</tt> procedure with each -- chunk. -- ------------------------------ procedure Iterate (Source : in Builder; Process : not null access procedure (Chunk : in Input)) is begin if Source.First.Last > 0 then Process (Source.First.Content (1 .. Source.First.Last)); declare B : Block_Access := Source.First.Next_Block; begin while B /= null loop Process (B.Content (1 .. B.Last)); B := B.Next_Block; end loop; end; end if; end Iterate; procedure Inline_Iterate (Source : in Builder) is begin if Source.First.Last > 0 then Process (Source.First.Content (1 .. Source.First.Last)); declare B : Block_Access := Source.First.Next_Block; begin while B /= null loop Process (B.Content (1 .. B.Last)); B := B.Next_Block; end loop; end; end if; end Inline_Iterate; procedure Inline_Update (Source : in out Builder) is begin if Source.First.Last > 0 then Process (Source.First.Content (1 .. Source.First.Last)); declare B : Block_Access := Source.First.Next_Block; begin while B /= null loop Process (B.Content (1 .. B.Last)); B := B.Next_Block; end loop; end; end if; end Inline_Update; -- ------------------------------ -- Return the content starting from the tail and up to <tt>Length</tt> items. -- ------------------------------ function Tail (Source : in Builder; Length : in Natural) return Input is Last : constant Natural := Source.Current.Last; begin if Last >= Length then return Source.Current.Content (Last - Length + 1 .. Last); elsif Length >= Source.Length then return To_Array (Source); else declare Result : Input (1 .. Length); Offset : Natural := Source.Length - Length; B : access constant Buffer := Source.First'Access; Src_Pos : Positive := 1; Dst_Pos : Positive := 1; Len : Natural; begin -- Skip the data moving to next blocks as needed. while Offset /= 0 loop if Offset < B.Last then Src_Pos := Offset + 1; Offset := 0; else Offset := Offset - B.Last + 1; B := B.Next_Block; end if; end loop; -- Copy what remains until we reach the length. while Dst_Pos <= Length loop Len := B.Last - Src_Pos + 1; Result (Dst_Pos .. Dst_Pos + Len - 1) := B.Content (Src_Pos .. B.Last); Src_Pos := 1; Dst_Pos := Dst_Pos + Len; B := B.Next_Block; end loop; return Result; end; end if; end Tail; -- ------------------------------ -- Get the buffer content as an array. -- ------------------------------ function To_Array (Source : in Builder) return Input is Result : Input (1 .. Source.Length); begin if Source.First.Last > 0 then declare Pos : Positive := Source.First.Last; B : Block_Access := Source.First.Next_Block; begin Result (1 .. Pos) := Source.First.Content (1 .. Pos); while B /= null loop Result (Pos + 1 .. Pos + B.Last) := B.Content (1 .. B.Last); Pos := Pos + B.Last; B := B.Next_Block; end loop; end; end if; return Result; end To_Array; -- ------------------------------ -- Get the element at the given position. -- ------------------------------ function Element (Source : in Builder; Position : in Positive) return Wiki.Strings.WChar is begin if Position <= Source.First.Last then return Source.First.Content (Position); else declare Pos : Positive := Position - Source.First.Last; B : Block_Access := Source.First.Next_Block; begin loop if Pos <= B.Last then return B.Content (Pos); end if; Pos := Pos - B.Last; B := B.Next_Block; end loop; end; end if; end Element; -- ------------------------------ -- Call the <tt>Process</tt> procedure with the full buffer content, trying to avoid -- secondary stack copies as much as possible. -- ------------------------------ procedure Get (Source : in Builder) is begin if Source.Length < Source.First.Len then Process (Source.First.Content (1 .. Source.Length)); else declare Content : constant Input := To_Array (Source); begin Process (Content); end; end if; end Get; -- ------------------------------ -- Setup the builder. -- ------------------------------ overriding procedure Initialize (Source : in out Builder) is begin Source.Current := Source.First'Unchecked_Access; end Initialize; -- ------------------------------ -- Finalize the builder releasing the storage. -- ------------------------------ overriding procedure Finalize (Source : in out Builder) is begin Clear (Source); end Finalize; function Count_Occurence (Buffer : in Buffer_Access; From : in Positive; Item : in Wiki.Strings.WChar) return Natural is Count : Natural := 0; Current : Buffer_Access := Buffer; Pos : Positive := From; begin while Current /= null loop declare First : Positive := Pos; Last : Natural := Current.Last; begin while Pos <= Last and then Current.Content (Pos) = Item loop Pos := Pos + 1; end loop; if Pos > First then Count := Count + Pos - First; end if; exit when Pos <= Last; end; Current := Current.Next_Block; Pos := 1; end loop; return Count; end Count_Occurence; procedure Count_Occurence (Buffer : in out Buffer_Access; From : in out Positive; Item : in Wiki.Strings.WChar; Count : out Natural) is Current : Buffer_Access := Buffer; Pos : Positive := From; begin Count := 0; while Current /= null loop declare First : Positive := From; Last : Natural := Current.Last; begin while Pos <= Last and then Current.Content (Pos) = Item loop Pos := Pos + 1; end loop; if Pos > First then Count := Count + Pos - First; end if; exit when Pos <= Last; end; Current := Current.Next_Block; Pos := 1; end loop; Buffer := Current; From := Pos; end Count_Occurence; procedure Find (Buffer : in out Buffer_Access; From : in out Positive; Item : in Wiki.Strings.WChar) is Pos : Positive := From; begin while Buffer /= null loop declare Last : constant Natural := Buffer.Last; begin while Pos <= Last loop if Buffer.Content (Pos) = Item then From := Pos; return; end if; Pos := Pos + 1; end loop; end; Buffer := Buffer.Next_Block; Pos := 1; end loop; end Find; end Wiki.Buffers;
Add Next procedure
Add Next procedure
Ada
apache-2.0
stcarrez/ada-wiki,stcarrez/ada-wiki
cdb181cb855dd8069dd9078eadd79d3c5d8381fa
src/wiki-parsers.ads
src/wiki-parsers.ads
----------------------------------------------------------------------- -- wiki-parsers -- Wiki parser -- Copyright (C) 2011, 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.Attributes; with Wiki.Plugins; with Wiki.Filters; with Wiki.Strings; with Wiki.Documents; with Wiki.Streams; -- == Wiki Parsers == -- The <b>Wikis.Parsers</b> package implements a parser for several well known wiki formats. -- The parser works with the <b>Document_Reader</b> interface type which defines several -- procedures that are called by the parser when the wiki text is scanned. package Wiki.Parsers is pragma Preelaborate; type Parser is tagged limited private; -- Add the plugin to the wiki engine. procedure Add_Plugin (Engine : in out Parser; Name : in String; Plugin : in Wiki.Plugins.Wiki_Plugin_Access); -- Set the wiki syntax that the wiki engine must use. procedure Set_Syntax (Engine : in out Parser; Syntax : in Wiki_Syntax := SYNTAX_MIX); -- Add a filter in the wiki engine. procedure Add_Filter (Engine : in out Parser; Filter : in Wiki.Filters.Filter_Type_Access); -- Parse the wiki text contained in <b>Text</b> according to the wiki syntax -- defined on the parser. procedure Parse (Engine : in out Parser; Text : in Wide_Wide_String; Doc : in out Wiki.Documents.Document); -- Parse the wiki stream managed by <tt>Stream</tt> according to the wiki syntax configured -- on the wiki engine. procedure Parse (Engine : in out Parser; Stream : in Wiki.Streams.Input_Stream_Access; Doc : in out Wiki.Documents.Document); private type Parser is tagged limited record Pending : Wide_Wide_Character; Has_Pending : Boolean; Syntax : Wiki_Syntax; Document : Wiki.Documents.Document; Filters : Wiki.Filters.Filter_Chain; Format : Wiki.Format_Map; Text : Wiki.Strings.BString (512); Token : Wiki.Strings.BString (512); Empty_Line : Boolean := True; Is_Eof : Boolean := False; In_Paragraph : Boolean := False; In_List : Boolean := False; Need_Paragraph : Boolean := True; Link_Double_Bracket : Boolean := False; Is_Dotclear : Boolean := False; Link_Title_First : Boolean := False; Check_Image_Link : Boolean := False; Header_Offset : Integer := 0; Quote_Level : Natural := 0; Escape_Char : Wide_Wide_Character; List_Level : Natural := 0; Reader : Wiki.Streams.Input_Stream_Access := null; Attributes : Wiki.Attributes.Attribute_List; end record; type Parser_Handler is access procedure (P : in out Parser; Token : in Wide_Wide_Character); type Parser_Table is array (0 .. 127) of Parser_Handler; type Parser_Table_Access is access Parser_Table; -- Peek the next character from the wiki text buffer. procedure Peek (P : in out Parser; Token : out Wide_Wide_Character); -- Put back the character so that it will be returned by the next call to Peek. procedure Put_Back (P : in out Parser; Token : in Wide_Wide_Character); -- Skip all the spaces and tabs as well as end of the current line (CR+LF). procedure Skip_End_Of_Line (P : in out Parser); -- Skip white spaces and tabs. procedure Skip_Spaces (P : in out Parser); -- Flush the wiki text that was collected in the text buffer. procedure Flush_Text (P : in out Parser); -- Flush the wiki dl/dt/dd definition list. procedure Flush_List (P : in out Parser); -- Append a character to the wiki text buffer. procedure Parse_Text (P : in out Parser; Token : in Wide_Wide_Character); -- Check if the link refers to an image and must be rendered as an image. function Is_Image (P : in Parser; Link : in Wide_Wide_String) return Boolean; procedure Start_Element (P : in out Parser; Tag : in Wiki.Html_Tag; Attributes : in out Wiki.Attributes.Attribute_List); procedure End_Element (P : in out Parser; Tag : in Wiki.Html_Tag); end Wiki.Parsers;
----------------------------------------------------------------------- -- wiki-parsers -- Wiki parser -- Copyright (C) 2011, 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.Attributes; with Wiki.Plugins; with Wiki.Filters; with Wiki.Strings; with Wiki.Documents; with Wiki.Streams; -- === Wiki Parsers === -- The <b>Wikis.Parsers</b> package implements a parser for several well known wiki formats -- but also for HTML. While reading the input, the parser populates a wiki <tt>Document</tt> -- instance with headers, paragraphs, links, and other elements. -- -- Doc : Wiki.Documents.Document; -- Engine : Wiki.Parsers.Parser; -- -- Before using the parser, it must be configured to choose the syntax by using the -- <tt>Set_Syntax</tt> procedure: -- -- Engine.Set_Syntax (Wiki.SYNTAX_HTML); -- -- The parser can be configured to use filters. A filter is added by using the -- <tt>Add_Filter</tt> procedure. A filter is added at begining of the chain so that -- the filter added last is called first. -- -- The <tt>Parse</tt> procedure is then used to parse either a string content or some stream -- represented by the <tt>Input_Stream</tt> interface. After the <tt>Parse</tt> procedure -- completes, the <tt>Document</tt> instance holds the wiki document. -- -- Engine.Parse (Some_Text, Doc); -- package Wiki.Parsers is pragma Preelaborate; type Parser is tagged limited private; -- Add the plugin to the wiki engine. procedure Add_Plugin (Engine : in out Parser; Name : in String; Plugin : in Wiki.Plugins.Wiki_Plugin_Access); -- Set the wiki syntax that the wiki engine must use. procedure Set_Syntax (Engine : in out Parser; Syntax : in Wiki_Syntax := SYNTAX_MIX); -- Add a filter in the wiki engine. procedure Add_Filter (Engine : in out Parser; Filter : in Wiki.Filters.Filter_Type_Access); -- Parse the wiki text contained in <b>Text</b> according to the wiki syntax -- defined on the parser. procedure Parse (Engine : in out Parser; Text : in Wiki.Strings.WString; Doc : in out Wiki.Documents.Document); -- Parse the wiki stream managed by <tt>Stream</tt> according to the wiki syntax configured -- on the wiki engine. procedure Parse (Engine : in out Parser; Stream : in Wiki.Streams.Input_Stream_Access; Doc : in out Wiki.Documents.Document); private type Parser is tagged limited record Pending : Wiki.Strings.WChar; Has_Pending : Boolean; Syntax : Wiki_Syntax; Document : Wiki.Documents.Document; Filters : Wiki.Filters.Filter_Chain; Format : Wiki.Format_Map; Text : Wiki.Strings.BString (512); Token : Wiki.Strings.BString (512); Empty_Line : Boolean := True; Is_Eof : Boolean := False; In_Paragraph : Boolean := False; In_List : Boolean := False; Need_Paragraph : Boolean := True; Link_Double_Bracket : Boolean := False; Is_Dotclear : Boolean := False; Link_Title_First : Boolean := False; Check_Image_Link : Boolean := False; Header_Offset : Integer := 0; Quote_Level : Natural := 0; Escape_Char : Wiki.Strings.WChar; List_Level : Natural := 0; Reader : Wiki.Streams.Input_Stream_Access := null; Attributes : Wiki.Attributes.Attribute_List; end record; type Parser_Handler is access procedure (P : in out Parser; Token : in Wiki.Strings.WChar); type Parser_Table is array (0 .. 127) of Parser_Handler; type Parser_Table_Access is access Parser_Table; -- Peek the next character from the wiki text buffer. procedure Peek (P : in out Parser; Token : out Wiki.Strings.WChar); -- Put back the character so that it will be returned by the next call to Peek. procedure Put_Back (P : in out Parser; Token : in Wiki.Strings.WChar); -- Skip all the spaces and tabs as well as end of the current line (CR+LF). procedure Skip_End_Of_Line (P : in out Parser); -- Skip white spaces and tabs. procedure Skip_Spaces (P : in out Parser); -- Flush the wiki text that was collected in the text buffer. procedure Flush_Text (P : in out Parser); -- Flush the wiki dl/dt/dd definition list. procedure Flush_List (P : in out Parser); -- Append a character to the wiki text buffer. procedure Parse_Text (P : in out Parser; Token : in Wiki.Strings.WChar); -- Check if the link refers to an image and must be rendered as an image. function Is_Image (P : in Parser; Link : in Wiki.Strings.WString) return Boolean; procedure Start_Element (P : in out Parser; Tag : in Wiki.Html_Tag; Attributes : in out Wiki.Attributes.Attribute_List); procedure End_Element (P : in out Parser; Tag : in Wiki.Html_Tag); end Wiki.Parsers;
Add some documentation
Add some documentation
Ada
apache-2.0
stcarrez/ada-wiki,stcarrez/ada-wiki
ffc287b77140d15c9083c3968f779b541aeeb3d1
src/util-log-locations.adb
src/util-log-locations.adb
----------------------------------------------------------------------- -- util-log-locations -- General purpose source file location -- Copyright (C) 2009, 2010, 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.Strings; package body Util.Log.Locations is -- ------------------------------ -- Create a <b>File_Info</b> record to identify the file whose path is <b>Path</b> -- and whose relative path portion starts at <b>Relative_Position</b>. -- ------------------------------ function Create_File_Info (Path : in String; Relative_Position : in Natural) return File_Info_Access is begin return new File_Info '(Length => Path'Length, Path => Path, Relative_Pos => Relative_Position); end Create_File_Info; -- ------------------------------ -- Get the relative path name -- ------------------------------ function Relative_Path (File : in File_Info) return String is begin return File.Path (File.Relative_Pos .. File.Path'Last); end Relative_Path; -- ------------------------------ -- Get the line number -- ------------------------------ function Line (Info : Line_Info) return Natural is begin return Info.Line; end Line; -- ------------------------------ -- Get the column number -- ------------------------------ function Column (Info : Line_Info) return Natural is begin return Info.Column; end Column; -- ------------------------------ -- Get the source file -- ------------------------------ function File (Info : Line_Info) return String is begin return Info.File.Path; end File; -- ------------------------------ -- Create a source line information. -- ------------------------------ function Create_Line_Info (File : in File_Info_Access; Line : in Natural; Column : in Natural := 0) return Line_Info is Result : Line_Info; begin Result.Line := Line; Result.Column := Column; if File = null then Result.File := NO_FILE'Access; else Result.File := File; end if; return Result; end Create_Line_Info; -- ------------------------------ -- Get a printable representation of the line information using -- the format: -- <path>:<line>[:<column>] -- The path can be reported as relative or absolute path. -- The column is optional and reported by default. -- ------------------------------ function To_String (Info : in Line_Info; Relative : in Boolean := True; Column : in Boolean := True) return String is begin if Relative then if Column then return Relative_Path (Info.File.all) & ":" & Util.Strings.Image (Info.Line) & ":" & Util.Strings.Image (Info.Column); else return Relative_Path (Info.File.all) & ":" & Util.Strings.Image (Info.Line); end if; else if Column then return Info.File.Path & ":" & Util.Strings.Image (Info.Line) & ":" & Util.Strings.Image (Info.Column); else return Info.File.Path & ":" & Util.Strings.Image (Info.Line); end if; end if; end To_String; end Util.Log.Locations;
----------------------------------------------------------------------- -- util-log-locations -- General purpose source file location -- Copyright (C) 2009, 2010, 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.Strings; package body Util.Log.Locations is -- ------------------------------ -- Create a <b>File_Info</b> record to identify the file whose path is <b>Path</b> -- and whose relative path portion starts at <b>Relative_Position</b>. -- ------------------------------ function Create_File_Info (Path : in String; Relative_Position : in Natural) return File_Info_Access is begin return new File_Info '(Length => Path'Length, Path => Path, Relative_Pos => Relative_Position); end Create_File_Info; -- ------------------------------ -- Get the relative path name -- ------------------------------ function Relative_Path (File : in File_Info) return String is begin return File.Path (File.Relative_Pos .. File.Path'Last); end Relative_Path; -- ------------------------------ -- Get the line number -- ------------------------------ function Line (Info : Line_Info) return Natural is begin return Info.Line; end Line; -- ------------------------------ -- Get the column number -- ------------------------------ function Column (Info : Line_Info) return Natural is begin return Info.Column; end Column; -- ------------------------------ -- Get the source file -- ------------------------------ function File (Info : Line_Info) return String is begin return Info.File.Path; end File; -- ------------------------------ -- Compare the two source location. The comparison is made on: -- o the source file, -- o the line number, -- o the column. -- ------------------------------ function "<" (Left, Right : in Line_Info) return Boolean is begin if Left.File.Path < Right.File.Path then return True; elsif Left.File.Path > Right.File.Path then return False; elsif Left.Line < Right.Line then return True; elsif Left.Line > Right.Line then return False; else return Left.Column < Right.Column; end if; end "<"; -- ------------------------------ -- Create a source line information. -- ------------------------------ function Create_Line_Info (File : in File_Info_Access; Line : in Natural; Column : in Natural := 0) return Line_Info is Result : Line_Info; begin Result.Line := Line; Result.Column := Column; if File = null then Result.File := NO_FILE'Access; else Result.File := File; end if; return Result; end Create_Line_Info; -- ------------------------------ -- Get a printable representation of the line information using -- the format: -- <path>:<line>[:<column>] -- The path can be reported as relative or absolute path. -- The column is optional and reported by default. -- ------------------------------ function To_String (Info : in Line_Info; Relative : in Boolean := True; Column : in Boolean := True) return String is begin if Relative then if Column then return Relative_Path (Info.File.all) & ":" & Util.Strings.Image (Info.Line) & ":" & Util.Strings.Image (Info.Column); else return Relative_Path (Info.File.all) & ":" & Util.Strings.Image (Info.Line); end if; else if Column then return Info.File.Path & ":" & Util.Strings.Image (Info.Line) & ":" & Util.Strings.Image (Info.Column); else return Info.File.Path & ":" & Util.Strings.Image (Info.Line); end if; end if; end To_String; end Util.Log.Locations;
Implement the "<" function to compare two source locations
Implement the "<" function to compare two source locations
Ada
apache-2.0
stcarrez/ada-util,stcarrez/ada-util
0d711814224a73bee699f3b10620714f090395aa
src/bare_bones.adb
src/bare_bones.adb
-- -*- Mode: Ada -*- -- Filename : bare_bones.adb -- Description : A "hello world" style OS kernel written in Ada. -- Author : Luke A. Guest -- Created On : Thu Jun 14 11:59:53 2012 -- Licence : See LICENCE in the root directory. with Console; use Console; with Multiboot; use Multiboot; with System.Address_To_Access_Conversions; with Ada.Unchecked_Conversion; use type Multiboot.Magic_Values; procedure Bare_Bones is Line : Screen_Height_Range := Screen_Height_Range'First; begin Clear; Put ("Hello, bare bones in Ada", Screen_Width_Range'First, Line); Line := Line + 1; if Magic = Magic_Value then Put ("Magic numbers match!", Screen_Width_Range'First, Line); else Put ("Magic numbers don't match!", Screen_Width_Range'First, Line); raise Program_Error; end if; Line := Line + 1; if Info.Flags.Memory then Put ("Memory info present", Screen_Width_Range'First, Line); Line := Line + 1; end if; if Info.Flags.Boot_Device then Put ("Boot device info present", Screen_Width_Range'First, Line); Line := Line + 1; end if; if Info.Flags.Command_Line then Put ("Command line info present", Screen_Width_Range'First, Line); Line := Line + 1; end if; if Info.Flags.Modules then Put ("Modules info present", Screen_Width_Range'First, Line); Line := Line + 1; if Info.Modules.Count = 2 then declare type My_Modules_Array is new Modules_Array (1 .. Natural (Info.Modules.Count)); type My_Modules_Array_Access is access all My_Modules_Array; -- My_Modules : aliased Modules_Array -- (1 .. Natural (Info.Modules.Count)); -- pragma Unreferenced (My_Modules); package To_Modules is new System.Address_To_Access_Conversions (Object => My_Modules_Array_Access); function Conv is new Ada.Unchecked_Conversion (Source => To_Modules.Object_Pointer, Target => My_Modules_Array_Access); Modules : constant My_Modules_Array_Access := Conv (To_Modules.To_Pointer (Info.Modules.First)); M : Multiboot.Modules; pragma Unreferenced (M); begin Put ("2 modules loaded is correct", Screen_Width_Range'First, Line); for I in 1 .. Info.Modules.Count loop M := Modules (Natural (I)); end loop; Line := Line + 1; end; end if; end if; if Info.Flags.Symbol_Table then Put ("Symbol table info present", Screen_Width_Range'First, Line); Line := Line + 1; end if; if Info.Flags.Section_Header_Table then Put ("Section header table info present", Screen_Width_Range'First, Line); Line := Line + 1; end if; if Info.Flags.BIOS_Memory_Map then Put ("BIOS memory map info present", Screen_Width_Range'First, Line); Line := Line + 1; declare Map : Memory_Map_Entry_Access := Multiboot.First_Memory_Map_Entry; begin while Map /= null loop Map := Multiboot.Next_Memory_Map_Entry (Map); end loop; end; end if; if Info.Flags.Drives then Put ("Drives info present", Screen_Width_Range'First, Line); Line := Line + 1; end if; if Info.Flags.ROM_Configuration then Put ("ROM configuration info present", Screen_Width_Range'First, Line); Line := Line + 1; end if; if Info.Flags.Boot_Loader then Put ("Boot loader info present", Screen_Width_Range'First, Line); Line := Line + 1; end if; if Info.Flags.APM_Table then Put ("APM table info present", Screen_Width_Range'First, Line); Line := Line + 1; end if; if Info.Flags.Graphics_Table then Put ("Graphics table info present", Screen_Width_Range'First, Line); Line := Line + 1; end if; -- raise Console.TE; -- raise Constraint_Error; -- Put (Natural 'Image (54), -- Screen_Width_Range'First, -- Screen_Height_Range'First + 1); -- exception -- when Constraint_Error => -- Put ("Constraint Error caught", 1, 2); -- when Console.TE => -- Put ("TE caught", 1, 2); end Bare_Bones; pragma No_Return (Bare_Bones);
-- -*- Mode: Ada -*- -- Filename : bare_bones.adb -- Description : A "hello world" style OS kernel written in Ada. -- Author : Luke A. Guest -- Created On : Thu Jun 14 11:59:53 2012 -- Licence : See LICENCE in the root directory. pragma Restrictions (No_Obsolescent_Features); -- with Console; use Console; -- with Multiboot; use Multiboot; -- with System.Address_To_Access_Conversions; -- with Ada.Unchecked_Conversion; -- use type Multiboot.Magic_Values; procedure Bare_Bones is -- Line : Screen_Height_Range := Screen_Height_Range'First; begin null; -- Clear; -- Put ("Hello, bare bones in Ada", -- Screen_Width_Range'First, -- Line); -- Line := Line + 1; -- if Magic = Magic_Value then -- Put ("Magic numbers match!", Screen_Width_Range'First, Line); -- else -- Put ("Magic numbers don't match!", Screen_Width_Range'First, Line); -- raise Program_Error; -- end if; -- Line := Line + 1; -- if Info.Flags.Memory then -- Put ("Memory info present", Screen_Width_Range'First, Line); -- Line := Line + 1; -- end if; -- if Info.Flags.Boot_Device then -- Put ("Boot device info present", Screen_Width_Range'First, Line); -- Line := Line + 1; -- end if; -- if Info.Flags.Command_Line then -- Put ("Command line info present", Screen_Width_Range'First, Line); -- Line := Line + 1; -- end if; -- if Info.Flags.Modules then -- Put ("Modules info present", Screen_Width_Range'First, Line); -- Line := Line + 1; -- if Info.Modules.Count = 2 then -- declare -- type My_Modules_Array is new Modules_Array -- (1 .. Natural (Info.Modules.Count)); -- type My_Modules_Array_Access is access all My_Modules_Array; -- -- My_Modules : aliased Modules_Array -- -- (1 .. Natural (Info.Modules.Count)); -- -- pragma Unreferenced (My_Modules); -- package To_Modules is new System.Address_To_Access_Conversions -- (Object => My_Modules_Array_Access); -- function Conv is new Ada.Unchecked_Conversion -- (Source => To_Modules.Object_Pointer, -- Target => My_Modules_Array_Access); -- Modules : constant My_Modules_Array_Access := -- Conv (To_Modules.To_Pointer -- (Info.Modules.First)); -- M : Multiboot.Modules; -- pragma Unreferenced (M); -- begin -- Put ("2 modules loaded is correct", -- Screen_Width_Range'First, Line); -- for I in 1 .. Info.Modules.Count loop -- M := Modules (Natural (I)); -- end loop; -- Line := Line + 1; -- end; -- end if; -- end if; -- if Info.Flags.Symbol_Table then -- Put ("Symbol table info present", Screen_Width_Range'First, Line); -- Line := Line + 1; -- end if; -- if Info.Flags.Section_Header_Table then -- Put ("Section header table info present", -- Screen_Width_Range'First, Line); -- Line := Line + 1; -- end if; -- if Info.Flags.BIOS_Memory_Map then -- Put ("BIOS memory map info present", Screen_Width_Range'First, Line); -- Line := Line + 1; -- declare -- Map : Memory_Map_Entry_Access := Multiboot.First_Memory_Map_Entry; -- begin -- while Map /= null loop -- Map := Multiboot.Next_Memory_Map_Entry (Map); -- end loop; -- end; -- end if; -- if Info.Flags.Drives then -- Put ("Drives info present", Screen_Width_Range'First, Line); -- Line := Line + 1; -- end if; -- if Info.Flags.ROM_Configuration then -- Put ("ROM configuration info present", -- Screen_Width_Range'First, Line); -- Line := Line + 1; -- end if; -- if Info.Flags.Boot_Loader then -- Put ("Boot loader info present", Screen_Width_Range'First, Line); -- Line := Line + 1; -- end if; -- if Info.Flags.APM_Table then -- Put ("APM table info present", Screen_Width_Range'First, Line); -- Line := Line + 1; -- end if; -- if Info.Flags.Graphics_Table then -- Put ("Graphics table info present", Screen_Width_Range'First, Line); -- Line := Line + 1; -- end if; -- raise Constraint_Error; -- raise Console.TE; -- raise Constraint_Error; -- Put (Natural 'Image (54), -- Screen_Width_Range'First, -- Screen_Height_Range'First + 1); -- exception -- when Constraint_Error => -- Put ("Constraint Error caught", 1, 15); -- when Program_Error => -- null; -- when Console.TE => -- Put ("TE caught", 1, 2); end Bare_Bones; pragma No_Return (Bare_Bones);
Comment out the PC stuff.
Comment out the PC stuff.
Ada
bsd-2-clause
Lucretia/tamp2,Lucretia/bare_bones,robdaemon/bare_bones
a667375bdaecada0e350a5a935d23bf45e206d78
src/ado-sessions-factory.adb
src/ado-sessions-factory.adb
----------------------------------------------------------------------- -- factory -- Session Factory -- Copyright (C) 2009, 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 ADO.Sequences.Hilo; with Ada.Unchecked_Deallocation; -- The <b>ADO.Sessions.Factory</b> package defines the factory for creating -- sessions. package body ADO.Sessions.Factory is use ADO.Databases; -- ------------------------------ -- Open a session -- ------------------------------ procedure Open_Session (Factory : in out Session_Factory; Database : out Session) is S : constant Session_Record_Access := new Session_Record; DB : constant Master_Connection'Class := Factory.Source.Get_Connection; begin S.Database := Master_Connection (DB); S.Entities := Factory.Entities; Database.Impl := S; end Open_Session; -- ------------------------------ -- Get a read-only session from the factory. -- ------------------------------ function Get_Session (Factory : in Session_Factory) return Session is R : Session; S : constant Session_Record_Access := new Session_Record; DB : constant Master_Connection'Class := Factory.Source.Get_Connection; begin S.Database := Master_Connection (DB); S.Entities := Factory.Entities; R.Impl := S; return R; end Get_Session; -- ------------------------------ -- Get a read-only session from the session proxy. -- If the session has been invalidated, raise the SESSION_EXPIRED exception. -- ------------------------------ function Get_Session (Proxy : in Session_Proxy_Access) return Session is R : Session; begin if Proxy = null then raise ADO.Objects.SESSION_EXPIRED; end if; if Proxy.Session = null then raise ADO.Objects.SESSION_EXPIRED; end if; R.Impl := Proxy.Session; R.Impl.Counter := R.Impl.Counter + 1; return R; end Get_Session; -- ------------------------------ -- Get a read-only session from the session proxy. -- If the session has been invalidated, raise the SESSION_EXPIRED exception. -- ------------------------------ function Get_Session (Proxy : in Session_Record_Access) return Session is R : Session; begin if Proxy = null then raise ADO.Objects.SESSION_EXPIRED; end if; -- if Proxy.Session = null then -- raise ADO.Objects.SESSION_EXPIRED; -- end if; R.Impl := Proxy; R.Impl.Counter := R.Impl.Counter + 1; return R; end Get_Session; -- ------------------------------ -- Get a read-write session from the factory. -- ------------------------------ function Get_Master_Session (Factory : in Session_Factory) return Master_Session is R : Master_Session; S : constant Session_Record_Access := new Session_Record; DB : constant Master_Connection'Class := Factory.Source.Get_Connection; begin S.Database := Master_Connection (DB); S.Entities := Factory.Entities; R.Impl := S; R.Sequences := Factory.Sequences; return R; end Get_Master_Session; -- ------------------------------ -- Open a session -- ------------------------------ procedure Open_Session (Factory : in Session_Factory; Database : out Master_Session) is begin null; end Open_Session; -- ------------------------------ -- Initialize the sequence factory associated with the session factory. -- ------------------------------ procedure Initialize_Sequences (Factory : in out Session_Factory) is use ADO.Sequences; begin Factory.Sequences := Factory.Seq_Factory'Unchecked_Access; Set_Default_Generator (Factory.Seq_Factory, ADO.Sequences.Hilo.Create_HiLo_Generator'Access, Factory'Unchecked_Access); end Initialize_Sequences; -- ------------------------------ -- Create the session factory to connect to the database represented -- by the data source. -- ------------------------------ procedure Create (Factory : out Session_Factory; Source : in ADO.Databases.DataSource) is begin Factory.Source := Source; Factory.Entities := Factory.Entity_Cache'Unchecked_Access; Initialize_Sequences (Factory); if Factory.Source.Get_Database /= "" then declare S : Session := Factory.Get_Session; begin ADO.Schemas.Entities.Initialize (Factory.Entity_Cache, S); end; end if; end Create; -- ------------------------------ -- Create the session factory to connect to the database identified -- by the URI. -- ------------------------------ procedure Create (Factory : out Session_Factory; URI : in String) is begin Factory.Source.Set_Connection (URI); Factory.Entities := Factory.Entity_Cache'Unchecked_Access; Initialize_Sequences (Factory); if Factory.Source.Get_Database /= "" then declare S : Session := Factory.Get_Session; begin ADO.Schemas.Entities.Initialize (Factory.Entity_Cache, S); end; end if; end Create; end ADO.Sessions.Factory;
----------------------------------------------------------------------- -- factory -- Session Factory -- Copyright (C) 2009, 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 ADO.Sequences.Hilo; with Ada.Unchecked_Deallocation; -- The <b>ADO.Sessions.Factory</b> package defines the factory for creating -- sessions. package body ADO.Sessions.Factory is use ADO.Databases; -- ------------------------------ -- Open a session -- ------------------------------ procedure Open_Session (Factory : in out Session_Factory; Database : out Session) is S : constant Session_Record_Access := new Session_Record; DB : constant Master_Connection'Class := Factory.Source.Get_Connection; begin S.Database := Master_Connection (DB); S.Entities := Factory.Entities; Database.Impl := S; end Open_Session; -- ------------------------------ -- Get a read-only session from the factory. -- ------------------------------ function Get_Session (Factory : in Session_Factory) return Session is R : Session; S : constant Session_Record_Access := new Session_Record; DB : constant Master_Connection'Class := Factory.Source.Get_Connection; begin S.Database := Master_Connection (DB); S.Entities := Factory.Entities; R.Impl := S; return R; end Get_Session; -- ------------------------------ -- Get a read-only session from the session proxy. -- If the session has been invalidated, raise the SESSION_EXPIRED exception. -- ------------------------------ function Get_Session (Proxy : in Session_Proxy_Access) return Session is R : Session; begin if Proxy = null then raise ADO.Objects.SESSION_EXPIRED; end if; if Proxy.Session = null then raise ADO.Objects.SESSION_EXPIRED; end if; R.Impl := Proxy.Session; R.Impl.Counter := R.Impl.Counter + 1; return R; end Get_Session; -- ------------------------------ -- Get a read-only session from the session proxy. -- If the session has been invalidated, raise the SESSION_EXPIRED exception. -- ------------------------------ function Get_Session (Proxy : in Session_Record_Access) return Session is R : Session; begin if Proxy = null then raise ADO.Objects.SESSION_EXPIRED; end if; -- if Proxy.Session = null then -- raise ADO.Objects.SESSION_EXPIRED; -- end if; R.Impl := Proxy; R.Impl.Counter := R.Impl.Counter + 1; return R; end Get_Session; -- ------------------------------ -- Get a read-write session from the factory. -- ------------------------------ function Get_Master_Session (Factory : in Session_Factory) return Master_Session is R : Master_Session; DB : constant Master_Connection'Class := Factory.Source.Get_Connection; S : constant Session_Record_Access := new Session_Record; begin R.Impl := S; R.Sequences := Factory.Sequences; S.Database := Master_Connection (DB); S.Entities := Factory.Entities; return R; end Get_Master_Session; -- ------------------------------ -- Open a session -- ------------------------------ procedure Open_Session (Factory : in Session_Factory; Database : out Master_Session) is begin null; end Open_Session; -- ------------------------------ -- Initialize the sequence factory associated with the session factory. -- ------------------------------ procedure Initialize_Sequences (Factory : in out Session_Factory) is use ADO.Sequences; begin Factory.Sequences := Factory.Seq_Factory'Unchecked_Access; Set_Default_Generator (Factory.Seq_Factory, ADO.Sequences.Hilo.Create_HiLo_Generator'Access, Factory'Unchecked_Access); end Initialize_Sequences; -- ------------------------------ -- Create the session factory to connect to the database represented -- by the data source. -- ------------------------------ procedure Create (Factory : out Session_Factory; Source : in ADO.Databases.DataSource) is begin Factory.Source := Source; Factory.Entities := Factory.Entity_Cache'Unchecked_Access; Initialize_Sequences (Factory); if Factory.Source.Get_Database /= "" then declare S : Session := Factory.Get_Session; begin ADO.Schemas.Entities.Initialize (Factory.Entity_Cache, S); end; end if; end Create; -- ------------------------------ -- Create the session factory to connect to the database identified -- by the URI. -- ------------------------------ procedure Create (Factory : out Session_Factory; URI : in String) is begin Factory.Source.Set_Connection (URI); Factory.Entities := Factory.Entity_Cache'Unchecked_Access; Initialize_Sequences (Factory); if Factory.Source.Get_Database /= "" then declare S : Session := Factory.Get_Session; begin ADO.Schemas.Entities.Initialize (Factory.Entity_Cache, S); end; end if; end Create; end ADO.Sessions.Factory;
Fix possible memory leak if the connection cannot be obtained: create the Session_Record only after having created the database connection.
Fix possible memory leak if the connection cannot be obtained: create the Session_Record only after having created the database connection.
Ada
apache-2.0
stcarrez/ada-ado
be033632c13720576f95913a73f79a6687ce8a89
src/gen-commands-plugins.ads
src/gen-commands-plugins.ads
----------------------------------------------------------------------- -- gen-commands-plugins -- Plugin creation and management commands for dynamo -- Copyright (C) 2012 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- package Gen.Commands.Plugins is -- ------------------------------ -- Generator Command -- ------------------------------ type Command is new Gen.Commands.Command with null record; -- Execute the command with the arguments. procedure Execute (Cmd : in Command; Generator : in out Gen.Generator.Handler); -- Write the help associated with the command. procedure Help (Cmd : in Command; Generator : in out Gen.Generator.Handler); end Gen.Commands.Plugins;
----------------------------------------------------------------------- -- gen-commands-plugins -- Plugin creation and management commands for dynamo -- Copyright (C) 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. ----------------------------------------------------------------------- package Gen.Commands.Plugins is -- ------------------------------ -- Generator Command -- ------------------------------ type Command is new Gen.Commands.Command with null record; -- Execute the command with the arguments. overriding procedure Execute (Cmd : in Command; Name : in String; Args : in Argument_List'Class; Generator : in out Gen.Generator.Handler); -- Write the help associated with the command. overriding procedure Help (Cmd : in Command; Generator : in out Gen.Generator.Handler); end Gen.Commands.Plugins;
Update to use the new command implementation
Update to use the new command implementation
Ada
apache-2.0
stcarrez/dynamo,stcarrez/dynamo,stcarrez/dynamo
a37e9d6e7f2df1192ff051e68e5e9ccf17f28bbd
src/ado-drivers-connections.adb
src/ado-drivers-connections.adb
----------------------------------------------------------------------- -- ADO Drivers -- Database Drivers -- Copyright (C) 2010, 2011, 2012, 2013, 2015, 2016 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Log.Loggers; with Util.Systems.DLLs; with System; with Ada.Strings.Fixed; with Ada.Containers.Doubly_Linked_Lists; with Ada.Exceptions; package body ADO.Drivers.Connections is use Ada.Strings.Fixed; Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("ADO.Drivers.Connections"); -- Load the database driver. procedure Load_Driver (Name : in String); -- ------------------------------ -- 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) is Pos, Pos2, Slash_Pos, Next : Natural; begin Log.Info ("Set connection URI: {0}", URI); Controller.URI := To_Unbounded_String (URI); Pos := Index (URI, "://"); if Pos <= 1 then Log.Error ("Invalid connection URI: {0}", URI); raise Connection_Error with "Invalid URI: '" & URI & "'"; end if; Controller.Driver := Get_Driver (URI (URI'First .. Pos - 1)); if Controller.Driver = null then Log.Error ("No driver found for connection URI: {0}", URI); raise Connection_Error with "Driver '" & URI (URI'First .. Pos - 1) & "' not found"; end if; Pos := Pos + 3; Slash_Pos := Index (URI, "/", Pos); if Slash_Pos < Pos then Log.Error ("Invalid connection URI: {0}", URI); raise Connection_Error with "Invalid connection URI: '" & URI & "'"; end if; -- Extract the server and port. Pos2 := Index (URI, ":", Pos); if Pos2 >= Pos then Controller.Server := To_Unbounded_String (URI (Pos .. Pos2 - 1)); begin Controller.Port := Natural'Value (URI (Pos2 + 1 .. Slash_Pos - 1)); exception when Constraint_Error => Log.Error ("Invalid port in connection URI: {0}", URI); raise Connection_Error with "Invalid port in connection URI: '" & URI & "'"; end; else Controller.Port := 0; Controller.Server := To_Unbounded_String (URI (Pos .. Slash_Pos - 1)); end if; -- Extract the database name. Pos := Index (URI, "?", Slash_Pos); if Pos - 1 > Slash_Pos + 1 then Controller.Database := To_Unbounded_String (URI (Slash_Pos + 1 .. Pos - 1)); elsif Pos = 0 and Slash_Pos + 1 < URI'Last then Controller.Database := To_Unbounded_String (URI (Slash_Pos + 1 .. URI'Last)); else Controller.Database := Null_Unbounded_String; end if; -- Parse the optional properties if Pos > Slash_Pos then while Pos < URI'Last loop Pos2 := Index (URI, "=", Pos + 1); if Pos2 > Pos then Next := Index (URI, "&", Pos2 + 1); if Next > 0 then Controller.Properties.Set (URI (Pos + 1 .. Pos2 - 1), URI (Pos2 + 1 .. Next - 1)); Pos := Next; else Controller.Properties.Set (URI (Pos + 1 .. Pos2 - 1), URI (Pos2 + 1 .. URI'Last)); Pos := URI'Last; end if; else Controller.Properties.Set (URI (Pos + 1 .. URI'Last), ""); Pos := URI'Last; end if; end loop; end if; end Set_Connection; -- ------------------------------ -- 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) is begin Controller.Properties.Set (Name, Value); end Set_Property; -- ------------------------------ -- Get a property from the datasource configuration. -- If the property does not exist, an empty string is returned. -- ------------------------------ function Get_Property (Controller : in Configuration; Name : in String) return String is begin return Controller.Properties.Get (Name, ""); end Get_Property; -- ------------------------------ -- Get the server hostname. -- ------------------------------ function Get_Server (Controller : in Configuration) return String is begin return To_String (Controller.Server); end Get_Server; -- ------------------------------ -- Set the server hostname. -- ------------------------------ procedure Set_Server (Controller : in out Configuration; Server : in String) is begin Controller.Server := To_Unbounded_String (Server); end Set_Server; -- ------------------------------ -- Set the server port. -- ------------------------------ procedure Set_Port (Controller : in out Configuration; Port : in Natural) is begin Controller.Port := Port; end Set_Port; -- ------------------------------ -- Get the server port. -- ------------------------------ function Get_Port (Controller : in Configuration) return Natural is begin return Controller.Port; end Get_Port; -- ------------------------------ -- Set the database name. -- ------------------------------ procedure Set_Database (Controller : in out Configuration; Database : in String) is begin Controller.Database := To_Unbounded_String (Database); end Set_Database; -- ------------------------------ -- Get the database name. -- ------------------------------ function Get_Database (Controller : in Configuration) return String is begin return To_String (Controller.Database); end Get_Database; -- ------------------------------ -- Get the database driver name. -- ------------------------------ function Get_Driver (Controller : in Configuration) return String is begin if Controller.Driver /= null then return Get_Driver_Name (Controller.Driver.all); else return ""; end if; end Get_Driver; -- ------------------------------ -- Create a new connection using the configuration parameters. -- ------------------------------ procedure Create_Connection (Config : in Configuration'Class; Result : out Database_Connection_Access) is begin if Config.Driver = null then Log.Error ("No driver found for connection {0}", To_String (Config.URI)); raise Connection_Error with "Data source is not initialized: driver not found"; end if; Config.Driver.Create_Connection (Config, Result); Log.Info ("Created connection to '{0}' -> {1}", Config.URI, Result.Ident); exception when others => Log.Info ("Failed to create connection to '{0}'", Config.URI); raise; end Create_Connection; package Driver_List is new Ada.Containers.Doubly_Linked_Lists (Element_Type => Driver_Access); Next_Index : Driver_Index := 1; Drivers : Driver_List.List; -- ------------------------------ -- Get the driver unique index. -- ------------------------------ function Get_Driver_Index (D : in Driver) return Driver_Index is begin return D.Index; end Get_Driver_Index; -- ------------------------------ -- Get the driver name. -- ------------------------------ function Get_Driver_Name (D : in Driver) return String is begin return D.Name.all; end Get_Driver_Name; -- ------------------------------ -- Register a database driver. -- ------------------------------ procedure Register (Driver : in Driver_Access) is begin Log.Info ("Register driver {0}", Driver.Name.all); Driver_List.Prepend (Container => Drivers, New_Item => Driver); Driver.Index := Next_Index; Next_Index := Next_Index + 1; end Register; -- ------------------------------ -- Load the database driver. -- ------------------------------ procedure Load_Driver (Name : in String) is Lib : constant String := "libada_ado_" & Name & Util.Systems.DLLs.Extension; Symbol : constant String := "ado__drivers__connections__" & Name & "__initialize"; Handle : Util.Systems.DLLs.Handle; Addr : System.Address; begin Log.Info ("Loading driver {0}", Lib); Handle := Util.Systems.DLLs.Load (Lib); Addr := Util.Systems.DLLs.Get_Symbol (Handle, Symbol); declare procedure Init; pragma Import (C, Init); for Init'Address use Addr; begin Init; end; exception when Util.Systems.DLLs.Not_Found => Log.Error ("Driver for {0} was loaded but does not define the initialization symbol", Name); when E : Util.Systems.DLLs.Load_Error => Log.Error ("Driver for {0} was not found: {1}", Name, Ada.Exceptions.Exception_Message (E)); end Load_Driver; -- ------------------------------ -- Get a database driver given its name. -- ------------------------------ function Get_Driver (Name : in String) return Driver_Access is begin Log.Info ("Get driver {0}", Name); for Retry in 0 .. 2 loop if Retry = 1 then ADO.Drivers.Initialize; elsif Retry = 2 then Load_Driver (Name); end if; declare Iter : Driver_List.Cursor := Driver_List.First (Drivers); begin while Driver_List.Has_Element (Iter) loop declare D : constant Driver_Access := Driver_List.Element (Iter); begin if Name = D.Name.all then return D; end if; end; Driver_List.Next (Iter); end loop; end; end loop; return null; end Get_Driver; end ADO.Drivers.Connections;
----------------------------------------------------------------------- -- ADO Drivers -- Database Drivers -- Copyright (C) 2010, 2011, 2012, 2013, 2015, 2016, 2017 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Log.Loggers; with Util.Systems.DLLs; with System; with Ada.Strings.Fixed; with Ada.Containers.Doubly_Linked_Lists; with Ada.Exceptions; package body ADO.Drivers.Connections is use Ada.Strings.Fixed; Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("ADO.Drivers.Connections"); -- Load the database driver. procedure Load_Driver (Name : in String); -- ------------------------------ -- 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) is Pos, Pos2, Slash_Pos, Next : Natural; begin Log.Info ("Set connection URI: {0}", URI); Controller.URI := To_Unbounded_String (URI); Pos := Index (URI, "://"); if Pos <= 1 then Log.Error ("Invalid connection URI: {0}", URI); raise Connection_Error with "Invalid URI: '" & URI & "'"; end if; Controller.Driver := Get_Driver (URI (URI'First .. Pos - 1)); if Controller.Driver = null then Log.Error ("No driver found for connection URI: {0}", URI); raise Connection_Error with "Driver '" & URI (URI'First .. Pos - 1) & "' not found"; end if; Pos := Pos + 3; Slash_Pos := Index (URI, "/", Pos); if Slash_Pos < Pos then Log.Error ("Invalid connection URI: {0}", URI); raise Connection_Error with "Invalid connection URI: '" & URI & "'"; end if; -- Extract the server and port. Pos2 := Index (URI, ":", Pos); if Pos2 >= Pos then Controller.Server := To_Unbounded_String (URI (Pos .. Pos2 - 1)); begin Controller.Port := Natural'Value (URI (Pos2 + 1 .. Slash_Pos - 1)); exception when Constraint_Error => Log.Error ("Invalid port in connection URI: {0}", URI); raise Connection_Error with "Invalid port in connection URI: '" & URI & "'"; end; else Controller.Port := 0; Controller.Server := To_Unbounded_String (URI (Pos .. Slash_Pos - 1)); end if; -- Extract the database name. Pos := Index (URI, "?", Slash_Pos); if Pos - 1 > Slash_Pos + 1 then Controller.Database := To_Unbounded_String (URI (Slash_Pos + 1 .. Pos - 1)); elsif Pos = 0 and Slash_Pos + 1 < URI'Last then Controller.Database := To_Unbounded_String (URI (Slash_Pos + 1 .. URI'Last)); else Controller.Database := Null_Unbounded_String; end if; -- Parse the optional properties if Pos > Slash_Pos then while Pos < URI'Last loop Pos2 := Index (URI, "=", Pos + 1); if Pos2 > Pos then Next := Index (URI, "&", Pos2 + 1); if Next > 0 then Controller.Properties.Set (URI (Pos + 1 .. Pos2 - 1), URI (Pos2 + 1 .. Next - 1)); Pos := Next; else Controller.Properties.Set (URI (Pos + 1 .. Pos2 - 1), URI (Pos2 + 1 .. URI'Last)); Pos := URI'Last; end if; else Controller.Properties.Set (URI (Pos + 1 .. URI'Last), ""); Pos := URI'Last; end if; end loop; end if; end Set_Connection; -- ------------------------------ -- 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) is begin Controller.Properties.Set (Name, Value); end Set_Property; -- ------------------------------ -- Get a property from the datasource configuration. -- If the property does not exist, an empty string is returned. -- ------------------------------ function Get_Property (Controller : in Configuration; Name : in String) return String is begin return Controller.Properties.Get (Name, ""); end Get_Property; -- ------------------------------ -- Get the server hostname. -- ------------------------------ function Get_Server (Controller : in Configuration) return String is begin return To_String (Controller.Server); end Get_Server; -- ------------------------------ -- Set the server hostname. -- ------------------------------ procedure Set_Server (Controller : in out Configuration; Server : in String) is begin Controller.Server := To_Unbounded_String (Server); end Set_Server; -- ------------------------------ -- Set the server port. -- ------------------------------ procedure Set_Port (Controller : in out Configuration; Port : in Natural) is begin Controller.Port := Port; end Set_Port; -- ------------------------------ -- Get the server port. -- ------------------------------ function Get_Port (Controller : in Configuration) return Natural is begin return Controller.Port; end Get_Port; -- ------------------------------ -- Set the database name. -- ------------------------------ procedure Set_Database (Controller : in out Configuration; Database : in String) is begin Controller.Database := To_Unbounded_String (Database); end Set_Database; -- ------------------------------ -- Get the database name. -- ------------------------------ function Get_Database (Controller : in Configuration) return String is begin return To_String (Controller.Database); end Get_Database; -- ------------------------------ -- Get the database driver name. -- ------------------------------ function Get_Driver (Controller : in Configuration) return String is begin if Controller.Driver /= null then return Get_Driver_Name (Controller.Driver.all); else return ""; end if; end Get_Driver; -- ------------------------------ -- Create a new connection using the configuration parameters. -- ------------------------------ procedure Create_Connection (Config : in Configuration'Class; Result : in out Ref.Ref'Class) is begin if Config.Driver = null then Log.Error ("No driver found for connection {0}", To_String (Config.URI)); raise Connection_Error with "Data source is not initialized: driver not found"; end if; Config.Driver.Create_Connection (Config, Result); if Result.Is_Null then Log.Error ("Driver {0} failed to create connection {0}", Config.Driver.Name.all, To_String (Config.URI)); raise Connection_Error with "Data source is not initialized: driver error"; end if; Log.Info ("Created connection to '{0}' -> {1}", Config.URI, Result.Value.Ident); exception when others => Log.Info ("Failed to create connection to '{0}'", Config.URI); raise; end Create_Connection; package Driver_List is new Ada.Containers.Doubly_Linked_Lists (Element_Type => Driver_Access); Next_Index : Driver_Index := 1; Drivers : Driver_List.List; -- ------------------------------ -- Get the driver unique index. -- ------------------------------ function Get_Driver_Index (D : in Driver) return Driver_Index is begin return D.Index; end Get_Driver_Index; -- ------------------------------ -- Get the driver name. -- ------------------------------ function Get_Driver_Name (D : in Driver) return String is begin return D.Name.all; end Get_Driver_Name; -- ------------------------------ -- Register a database driver. -- ------------------------------ procedure Register (Driver : in Driver_Access) is begin Log.Info ("Register driver {0}", Driver.Name.all); Driver_List.Prepend (Container => Drivers, New_Item => Driver); Driver.Index := Next_Index; Next_Index := Next_Index + 1; end Register; -- ------------------------------ -- Load the database driver. -- ------------------------------ procedure Load_Driver (Name : in String) is Lib : constant String := "libada_ado_" & Name & Util.Systems.DLLs.Extension; Symbol : constant String := "ado__drivers__connections__" & Name & "__initialize"; Handle : Util.Systems.DLLs.Handle; Addr : System.Address; begin Log.Info ("Loading driver {0}", Lib); Handle := Util.Systems.DLLs.Load (Lib); Addr := Util.Systems.DLLs.Get_Symbol (Handle, Symbol); declare procedure Init; pragma Import (C, Init); for Init'Address use Addr; begin Init; end; exception when Util.Systems.DLLs.Not_Found => Log.Error ("Driver for {0} was loaded but does not define the initialization symbol", Name); when E : Util.Systems.DLLs.Load_Error => Log.Error ("Driver for {0} was not found: {1}", Name, Ada.Exceptions.Exception_Message (E)); end Load_Driver; -- ------------------------------ -- Get a database driver given its name. -- ------------------------------ function Get_Driver (Name : in String) return Driver_Access is begin Log.Info ("Get driver {0}", Name); for Retry in 0 .. 2 loop if Retry = 1 then ADO.Drivers.Initialize; elsif Retry = 2 then Load_Driver (Name); end if; declare Iter : Driver_List.Cursor := Driver_List.First (Drivers); begin while Driver_List.Has_Element (Iter) loop declare D : constant Driver_Access := Driver_List.Element (Iter); begin if Name = D.Name.all then return D; end if; end; Driver_List.Next (Iter); end loop; end; end loop; return null; end Get_Driver; end ADO.Drivers.Connections;
Use the Util.Refs reference counting and report an error if a driver returns a NULL instance
Use the Util.Refs reference counting and report an error if a driver returns a NULL instance
Ada
apache-2.0
stcarrez/ada-ado
535389d1362967196f5e957f375bd7529db81f38
awa/plugins/awa-mail/src/awa-mail-clients.ads
awa/plugins/awa-mail/src/awa-mail-clients.ads
----------------------------------------------------------------------- -- awa-mail-client -- Mail client interface -- Copyright (C) 2012 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Properties; -- The <b>AWA.Mail.Clients</b> package defines a mail client API used by the mail module. -- It defines two interfaces that must be implemented. This allows to have an implementation -- based on an external application such as <tt>sendmail</tt> and other implementation that -- use an SMTP connection. package AWA.Mail.Clients is type Recipient_Type is (TO, CC, BCC); -- ------------------------------ -- Mail Message -- ------------------------------ -- The <b>Mail_Message</b> represents an abstract mail message that can be initialized -- before being sent. type Mail_Message is limited interface; type Mail_Message_Access is access all Mail_Message'Class; -- Set the <tt>From</tt> part of the message. procedure Set_From (Message : in out Mail_Message; Name : in String; Address : in String) is abstract; -- Add a recipient for the message. procedure Add_Recipient (Message : in out Mail_Message; Kind : in Recipient_Type; Name : in String; Address : in String) is abstract; -- Set the subject of the message. procedure Set_Subject (Message : in out Mail_Message; Subject : in String) is abstract; -- Set the body of the message. procedure Set_Body (Message : in out Mail_Message; Content : in String) is abstract; -- Send the email message. procedure Send (Message : in out Mail_Message) is abstract; -- ------------------------------ -- Mail Manager -- ------------------------------ -- The <b>Mail_Manager</b> is the entry point to create a new mail message -- and be able to send it. type Mail_Manager is limited interface; type Mail_Manager_Access is access all Mail_Manager'Class; -- Create a new mail message. function Create_Message (Manager : in Mail_Manager) return Mail_Message_Access is abstract; -- Factory to create the mail manager. The mail manager implementation is identified by -- the <b>Name</b>. It is configured according to the properties defined in <b>Props</b>. -- Returns null if the mail manager identified by the name is not supported. function Factory (Name : in String; Props : in Util.Properties.Manager'Class) return Mail_Manager_Access; end AWA.Mail.Clients;
----------------------------------------------------------------------- -- awa-mail-client -- Mail client interface -- Copyright (C) 2012, 2020 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Strings.Unbounded; with Util.Properties; -- The <b>AWA.Mail.Clients</b> package defines a mail client API used by the mail module. -- It defines two interfaces that must be implemented. This allows to have an implementation -- based on an external application such as <tt>sendmail</tt> and other implementation that -- use an SMTP connection. package AWA.Mail.Clients is use Ada.Strings.Unbounded; type Recipient_Type is (TO, CC, BCC); -- ------------------------------ -- Mail Message -- ------------------------------ -- The <b>Mail_Message</b> represents an abstract mail message that can be initialized -- before being sent. type Mail_Message is limited interface; type Mail_Message_Access is access all Mail_Message'Class; -- Set the <tt>From</tt> part of the message. procedure Set_From (Message : in out Mail_Message; Name : in String; Address : in String) is abstract; -- Add a recipient for the message. procedure Add_Recipient (Message : in out Mail_Message; Kind : in Recipient_Type; Name : in String; Address : in String) is abstract; -- Set the subject of the message. procedure Set_Subject (Message : in out Mail_Message; Subject : in String) is abstract; -- Set the body of the message. procedure Set_Body (Message : in out Mail_Message; Content : in Unbounded_String; Alternative : in Unbounded_String; Content_Type : in String := "") is abstract; -- Add an attachment with the given content. procedure Add_Attachment (Message : in out Mail_Message; Content : in Unbounded_String; Content_Id : in String; Content_Type : in String) is abstract; -- Send the email message. procedure Send (Message : in out Mail_Message) is abstract; -- ------------------------------ -- Mail Manager -- ------------------------------ -- The <b>Mail_Manager</b> is the entry point to create a new mail message -- and be able to send it. type Mail_Manager is limited interface; type Mail_Manager_Access is access all Mail_Manager'Class; -- Create a new mail message. function Create_Message (Manager : in Mail_Manager) return Mail_Message_Access is abstract; -- Factory to create the mail manager. The mail manager implementation is identified by -- the <b>Name</b>. It is configured according to the properties defined in <b>Props</b>. -- Returns null if the mail manager identified by the name is not supported. function Factory (Name : in String; Props : in Util.Properties.Manager'Class) return Mail_Manager_Access; end AWA.Mail.Clients;
Add Add_Attachment procedure and update Set_Body to allow specify the alternative content
Add Add_Attachment procedure and update Set_Body to allow specify the alternative content
Ada
apache-2.0
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
9dbe5233416377bf7fd964c205cbeff4241a4ba2
regtests/asf-contexts-faces-tests.ads
regtests/asf-contexts-faces-tests.ads
----------------------------------------------------------------------- -- Faces Context Tests - Unit tests for ASF.Contexts.Faces -- Copyright (C) 2010, 2011, 2012, 2013 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Tests; with EL.Contexts.Default; with EL.Variables; with ASF.Applications.Tests; with ASF.Helpers.Beans; package ASF.Contexts.Faces.Tests is procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite); function Get_Form_Bean is new ASF.Helpers.Beans.Get_Bean (ASF.Applications.Tests.Form_Bean, ASF.Applications.Tests.Form_Bean_Access); type Test is new Util.Tests.Test with record -- The ELContext, Variables, Resolver, Form area controlled object. -- Due to AUnit implementation, we cannot store a controlled object in the Test object. -- This is due to the 'for Obj'Address use Ret;' clause used by AUnit to allocate -- a test object. -- The application object is allocated dyanmically by Set_Up. ELContext : EL.Contexts.Default.Default_Context_Access; Variables : EL.Variables.Variable_Mapper_Access; Root_Resolver : EL.Contexts.Default.Default_ELResolver_Access; Form : ASF.Applications.Tests.Form_Bean_Access; end record; -- Cleanup the test instance. overriding procedure Tear_Down (T : in out Test); -- Setup the faces context for the unit test. procedure Setup (T : in out Test; Context : in out Faces_Context); -- Test getting an attribute from the faces context. procedure Test_Get_Attribute (T : in out Test); -- Test getting a bean object from the faces context. procedure Test_Get_Bean (T : in out Test); -- Test getting a bean object from the faces context and doing a conversion. procedure Test_Get_Bean_Helper (T : in out Test); -- Test the faces message queue. procedure Test_Add_Message (T : in out Test); procedure Test_Max_Severity (T : in out Test); procedure Test_Get_Messages (T : in out Test); -- Test adding some exception in the faces context. procedure Test_Queue_Exception (T : in out Test); -- Test the flash instance. procedure Test_Flash_Context (T : in out Test); -- Test the mockup faces context. procedure Test_Mockup_Faces_Context (T : in out Test); end ASF.Contexts.Faces.Tests;
----------------------------------------------------------------------- -- Faces Context Tests - Unit tests for ASF.Contexts.Faces -- Copyright (C) 2010, 2011, 2012, 2013, 2015 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Tests; with EL.Contexts.Default; with EL.Variables; with ASF.Tests; with ASF.Applications.Tests; with ASF.Helpers.Beans; package ASF.Contexts.Faces.Tests is procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite); function Get_Form_Bean is new ASF.Helpers.Beans.Get_Bean (ASF.Applications.Tests.Form_Bean, ASF.Applications.Tests.Form_Bean_Access); type Test is new ASF.Tests.EL_Test with record -- The ELContext, Variables, Resolver, Form area controlled object. -- Due to AUnit implementation, we cannot store a controlled object in the Test object. -- This is due to the 'for Obj'Address use Ret;' clause used by AUnit to allocate -- a test object. -- The application object is allocated dyanmically by Set_Up. Form : ASF.Applications.Tests.Form_Bean_Access; end record; -- Cleanup the test instance. overriding procedure Tear_Down (T : in out Test); -- Setup the faces context for the unit test. procedure Setup (T : in out Test; Context : in out Faces_Context); -- Test getting an attribute from the faces context. procedure Test_Get_Attribute (T : in out Test); -- Test getting a bean object from the faces context. procedure Test_Get_Bean (T : in out Test); -- Test getting a bean object from the faces context and doing a conversion. procedure Test_Get_Bean_Helper (T : in out Test); -- Test the faces message queue. procedure Test_Add_Message (T : in out Test); procedure Test_Max_Severity (T : in out Test); procedure Test_Get_Messages (T : in out Test); -- Test adding some exception in the faces context. procedure Test_Queue_Exception (T : in out Test); -- Test the flash instance. procedure Test_Flash_Context (T : in out Test); -- Test the mockup faces context. procedure Test_Mockup_Faces_Context (T : in out Test); end ASF.Contexts.Faces.Tests;
Refactor to use the ASF.Tests.EL_Test type
Refactor to use the ASF.Tests.EL_Test type
Ada
apache-2.0
stcarrez/ada-asf,stcarrez/ada-asf,stcarrez/ada-asf
b5da5db7837305b31dedb03b2c32ff3830ffe356
src/ado-drivers-connections.ads
src/ado-drivers-connections.ads
----------------------------------------------------------------------- -- ADO Drivers -- Database Drivers -- Copyright (C) 2010, 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 Ada.Finalization; with ADO.Statements; with ADO.Schemas; with Util.Properties; with Util.Strings; -- 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 Ada.Finalization.Limited_Controlled with record Count : Natural := 0; Ident : String (1 .. 8) := (others => ' '); end record; type Database_Connection_Access is access all Database_Connection'Class; 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; -- ------------------------------ -- 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; -- Create a new connection using the configuration parameters. procedure Create_Connection (Config : in Configuration'Class; Result : out Database_Connection_Access); -- ------------------------------ -- Database Driver -- ------------------------------ -- Create a new connection using the configuration parameters. procedure Create_Connection (D : in out Driver; Config : in Configuration'Class; Result : out Database_Connection_Access) 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 := Null_Unbounded_String; Server : Unbounded_String := Null_Unbounded_String; Port : Natural := 0; Database : Unbounded_String := Null_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 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES 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; -- 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 Ada.Finalization.Limited_Controlled with record Count : Natural := 0; Ident : String (1 .. 8) := (others => ' '); end record; type Database_Connection_Access is access all Database_Connection'Class; 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; -- ------------------------------ -- 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 : out Database_Connection_Access); -- ------------------------------ -- Database Driver -- ------------------------------ -- Create a new connection using the configuration parameters. procedure Create_Connection (D : in out Driver; Config : in Configuration'Class; Result : out Database_Connection_Access) 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 := Null_Unbounded_String; Server : Unbounded_String := Null_Unbounded_String; Port : Natural := 0; Database : Unbounded_String := Null_Unbounded_String; Properties : Util.Properties.Manager; Driver : Driver_Access; end record; end ADO.Drivers.Connections;
Declare the Get_Driver function to retrieve the driver's name from the database connection object
Declare the Get_Driver function to retrieve the driver's name from the database connection object
Ada
apache-2.0
stcarrez/ada-ado
a267a356fea1c7f8ce95cd1ee021e6ae111517cb
src/util-beans-objects-datasets.ads
src/util-beans-objects-datasets.ads
----------------------------------------------------------------------- -- Util.Beans.Objects.Datasets -- Datasets -- 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.Hash; with Ada.Finalization; with Ada.Containers.Indefinite_Hashed_Maps; with Util.Beans.Basic; -- == Introduction == -- The <tt>Datasets</tt> package implements the <tt>Dataset</tt> list bean which -- defines a set of objects organized in rows and columns. The <tt>Dataset</tt> -- implements the <tt>List_Bean</tt> interface and allows to iterate over its rows. -- Each row defines a <tt>Bean</tt> instance and allows to access each column value. -- Each column is associated with a unique name. The row <tt>Bean</tt> allows to -- get or set the column by using the column name. package Util.Beans.Objects.Datasets is Invalid_State : exception; -- An array of objects. type Object_Array is array (Positive range <>) of Object; type Dataset is new Util.Beans.Basic.List_Bean with private; -- Get the number of elements in the list. overriding function Get_Count (From : in Dataset) return Natural; -- Set the current row index. Valid row indexes start at 1. overriding procedure Set_Row_Index (From : in out Dataset; Index : in Natural); -- Get the element at the current row index. overriding function Get_Row (From : in Dataset) 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 Dataset; Name : in String) return Util.Beans.Objects.Object; -- Append a row in the dataset and call the fill procedure to populate -- the row content. procedure Append (Into : in out Dataset; Fill : not null access procedure (Data : in out Object_Array)); -- Add a column to the dataset. If the position is not specified, -- the column count is incremented and the name associated with the last column. -- Raises Invalid_State exception if the dataset contains some rows, procedure Add_Column (Into : in out Dataset; Name : in String; Pos : in Natural := 0); -- Clear the content of the dataset. procedure Clear (Set : in out Dataset); private type Object_Array_Access is access all Object_Array; type Dataset_Array is array (Positive range <>) of Object_Array_Access; type Dataset_Array_Access is access all Dataset_Array; package Dataset_Map is new Ada.Containers.Indefinite_Hashed_Maps (Key_Type => String, Element_Type => Positive, Hash => Ada.Strings.Hash, Equivalent_Keys => "=", "=" => "="); type Row is new Util.Beans.Basic.Bean with record Data : Object_Array_Access; Map : access Dataset_Map.Map; end record; -- Get the value identified by the name. -- If the name cannot be found, the method should return the Null object. overriding function Get_Value (From : in Row; Name : in String) return Util.Beans.Objects.Object; -- Set the value identified by the name. -- If the name cannot be found, the method should raise the No_Value -- exception. overriding procedure Set_Value (From : in out Row; Name : in String; Value : in Util.Beans.Objects.Object); type Dataset is new Ada.Finalization.Controlled and Util.Beans.Basic.List_Bean with record Data : Dataset_Array_Access; Count : Natural := 0; Columns : Natural := 0; Map : aliased Dataset_Map.Map; Current : aliased Row; Current_Pos : Natural := 0; Row : Util.Beans.Objects.Object; end record; -- Initialize the dataset and the row bean instance. overriding procedure Initialize (Set : in out Dataset); -- Release the dataset storage. overriding procedure Finalize (Set : in out Dataset); end Util.Beans.Objects.Datasets;
----------------------------------------------------------------------- -- Util.Beans.Objects.Datasets -- Datasets -- Copyright (C) 2013, 2018 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Strings.Hash; with Ada.Finalization; with Ada.Containers.Indefinite_Hashed_Maps; with Util.Beans.Basic; -- == Datasets == -- The `Datasets` package implements the `Dataset` list bean which -- defines a set of objects organized in rows and columns. The `Dataset` -- implements the `List_Bean` interface and allows to iterate over its rows. -- Each row defines a `Bean` instance and allows to access each column value. -- Each column is associated with a unique name. The row `Bean` allows to -- get or set the column by using the column name. package Util.Beans.Objects.Datasets is Invalid_State : exception; -- An array of objects. type Object_Array is array (Positive range <>) of Object; type Dataset is new Util.Beans.Basic.List_Bean with private; -- Get the number of elements in the list. overriding function Get_Count (From : in Dataset) return Natural; -- Set the current row index. Valid row indexes start at 1. overriding procedure Set_Row_Index (From : in out Dataset; Index : in Natural); -- Get the element at the current row index. overriding function Get_Row (From : in Dataset) 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 Dataset; Name : in String) return Util.Beans.Objects.Object; -- Append a row in the dataset and call the fill procedure to populate -- the row content. procedure Append (Into : in out Dataset; Fill : not null access procedure (Data : in out Object_Array)); -- Add a column to the dataset. If the position is not specified, -- the column count is incremented and the name associated with the last column. -- Raises Invalid_State exception if the dataset contains some rows, procedure Add_Column (Into : in out Dataset; Name : in String; Pos : in Natural := 0); -- Clear the content of the dataset. procedure Clear (Set : in out Dataset); private type Object_Array_Access is access all Object_Array; type Dataset_Array is array (Positive range <>) of Object_Array_Access; type Dataset_Array_Access is access all Dataset_Array; package Dataset_Map is new Ada.Containers.Indefinite_Hashed_Maps (Key_Type => String, Element_Type => Positive, Hash => Ada.Strings.Hash, Equivalent_Keys => "=", "=" => "="); type Row is new Util.Beans.Basic.Bean with record Data : Object_Array_Access; Map : access Dataset_Map.Map; end record; -- Get the value identified by the name. -- If the name cannot be found, the method should return the Null object. overriding function Get_Value (From : in Row; Name : in String) return Util.Beans.Objects.Object; -- Set the value identified by the name. -- If the name cannot be found, the method should raise the No_Value -- exception. overriding procedure Set_Value (From : in out Row; Name : in String; Value : in Util.Beans.Objects.Object); type Dataset is new Ada.Finalization.Controlled and Util.Beans.Basic.List_Bean with record Data : Dataset_Array_Access; Count : Natural := 0; Columns : Natural := 0; Map : aliased Dataset_Map.Map; Current : aliased Row; Current_Pos : Natural := 0; Row : Util.Beans.Objects.Object; end record; -- Initialize the dataset and the row bean instance. overriding procedure Initialize (Set : in out Dataset); -- Release the dataset storage. overriding procedure Finalize (Set : in out Dataset); end Util.Beans.Objects.Datasets;
Add and update the documentation
Add and update the documentation
Ada
apache-2.0
stcarrez/ada-util,stcarrez/ada-util
a8d0d9ebfd9f86c39fc52b3b1c2092b339314251
awa/plugins/awa-workspaces/src/awa-workspaces-modules.ads
awa/plugins/awa-workspaces/src/awa-workspaces-modules.ads
----------------------------------------------------------------------- -- awa-workspaces-module -- Module workspaces -- Copyright (C) 2011, 2012, 2017 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with ADO.Sessions; with ASF.Applications; with AWA.Modules; with AWA.Services.Contexts; with AWA.Workspaces.Models; with AWA.Users.Services; with AWA.Users.Models; with AWA.Events; package AWA.Workspaces.Modules is Not_Found : exception; -- The name under which the module is registered. NAME : constant String := "workspaces"; package Invite_User_Event is new AWA.Events.Definition (Name => "invite-user"); -- ------------------------------ -- Module workspaces -- ------------------------------ type Workspace_Module is new AWA.Modules.Module with private; type Workspace_Module_Access is access all Workspace_Module'Class; -- Initialize the workspaces module. overriding procedure Initialize (Plugin : in out Workspace_Module; App : in AWA.Modules.Application_Access; Props : in ASF.Applications.Config); -- Get the current workspace associated with the current user. -- If the user has not workspace, create one. procedure Get_Workspace (Session : in out ADO.Sessions.Master_Session; Context : in AWA.Services.Contexts.Service_Context_Access; Workspace : out AWA.Workspaces.Models.Workspace_Ref); -- Load the invitation from the access key and verify that the key is still valid. procedure Load_Invitation (Module : in Workspace_Module; Key : in String; Invitation : in out AWA.Workspaces.Models.Invitation_Ref'Class; Inviter : in out AWA.Users.Models.User_Ref); -- Accept the invitation identified by the access key. procedure Accept_Invitation (Module : in Workspace_Module; Key : in String); -- Send the invitation to the user. procedure Send_Invitation (Module : in Workspace_Module; Invitation : in out AWA.Workspaces.Models.Invitation_Ref'Class); private type Workspace_Module is new AWA.Modules.Module with record User_Manager : AWA.Users.Services.User_Service_Access; end record; end AWA.Workspaces.Modules;
----------------------------------------------------------------------- -- awa-workspaces-module -- Module workspaces -- Copyright (C) 2011, 2012, 2017 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with ADO.Sessions; with ASF.Applications; with AWA.Modules; with AWA.Services.Contexts; with AWA.Workspaces.Models; with AWA.Users.Services; with AWA.Users.Models; with AWA.Events; package AWA.Workspaces.Modules is Not_Found : exception; -- The name under which the module is registered. NAME : constant String := "workspaces"; package Invite_User_Event is new AWA.Events.Definition (Name => "invite-user"); -- ------------------------------ -- Module workspaces -- ------------------------------ type Workspace_Module is new AWA.Modules.Module with private; type Workspace_Module_Access is access all Workspace_Module'Class; -- Initialize the workspaces module. overriding procedure Initialize (Plugin : in out Workspace_Module; App : in AWA.Modules.Application_Access; Props : in ASF.Applications.Config); -- Get the current workspace associated with the current user. -- If the user has not workspace, create one. procedure Get_Workspace (Session : in out ADO.Sessions.Master_Session; Context : in AWA.Services.Contexts.Service_Context_Access; Workspace : out AWA.Workspaces.Models.Workspace_Ref); -- Load the invitation from the access key and verify that the key is still valid. procedure Load_Invitation (Module : in Workspace_Module; Key : in String; Invitation : in out AWA.Workspaces.Models.Invitation_Ref'Class; Inviter : in out AWA.Users.Models.User_Ref); -- Accept the invitation identified by the access key. procedure Accept_Invitation (Module : in Workspace_Module; Key : in String); -- Send the invitation to the user. procedure Send_Invitation (Module : in Workspace_Module; Invitation : in out AWA.Workspaces.Models.Invitation_Ref'Class); -- Delete the member from the workspace. Remove the invitation if there is one. procedure Delete_Member (Module : in Workspace_Module; User_Id : in ADO.Identifier; Workspace_Id : in ADO.Identifier); private type Workspace_Module is new AWA.Modules.Module with record User_Manager : AWA.Users.Services.User_Service_Access; end record; end AWA.Workspaces.Modules;
Declare the Delete_Member procedure
Declare the Delete_Member procedure
Ada
apache-2.0
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
f782820b20bc4f5cd8b7e6bbef5f324b191765c6
awa/regtests/awa-users-services-tests.adb
awa/regtests/awa-users-services-tests.adb
----------------------------------------------------------------------- -- users - User creation, password tests -- Copyright (C) 2009, 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.Test_Caller; with Util.Measures; with ADO; with ADO.Sessions; with ADO.SQL; with ADO.Objects; with Ada.Calendar; with AWA.Users.Module; with AWA.Tests.Helpers.Users; package body AWA.Users.Services.Tests is use Util.Tests; use ADO; use ADO.Objects; package Caller is new Util.Test_Caller (Test, "Users.Services"); procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is begin Caller.Add_Test (Suite, "Test AWA.Users.Services.Create_User", Test_Create_User'Access); Caller.Add_Test (Suite, "Test AWA.Users.Services.Close_Session", Test_Logout_User'Access); Caller.Add_Test (Suite, "Test AWA.Users.Services.Authenticate, Close_Session", Test_Login_User'Access); Caller.Add_Test (Suite, "Test AWA.Users.Services.Lost_Password, Reset_Password", Test_Reset_Password_User'Access); Caller.Add_Test (Suite, "Test AWA.Users.Module.Get_User_Module", Test_Get_Module'Access); end Add_Tests; -- ------------------------------ -- Test creation of a user -- ------------------------------ procedure Test_Create_User (T : in out Test) is Principal : AWA.Tests.Helpers.Users.Test_User; begin -- Create the user AWA.Tests.Helpers.Users.Create_User (Principal); T.Assert (not Principal.User.Is_Null, "User is created"); T.Assert (Principal.User.Get_Id > 0, "User has an allocated key"); T.Assert (Principal.Email.Get_Id > 0, "Email has an allocated key"); T.Assert (not Principal.Session.Is_Null, "Session must be created"); T.Assert (Principal.Session.Get_End_Date.Is_Null, "Session must be opened"); -- Verify the user session declare S1 : Session_Ref; U1 : User_Ref; begin Principal.Manager.Verify_Session (Id => Principal.Session.Get_Id, Session => S1, User => U1); T.Assert (not S1.Is_Null, "Null session returned by Verify_Session"); T.Assert (not U1.Is_Null, "Null user returned by Verify_Session"); T.Assert (not S1.Get_Start_Date.Is_Null, "Session must be started"); T.Assert (S1.Get_End_Date.Is_Null, "Session must not be finished"); Util.Tests.Assert_Equals (T, Principal.Session.Get_Start_Date.Value, S1.Get_Start_Date.Value, "Invalid start date"); Principal.Manager.Close_Session (Principal.Session.Get_Id); end; end Test_Create_User; -- ------------------------------ -- Test logout of a user -- ------------------------------ procedure Test_Logout_User (T : in out Test) is Principal : AWA.Tests.Helpers.Users.Test_User; begin -- Create the user AWA.Tests.Helpers.Users.Create_User (Principal); T.Assert (not Principal.User.Is_Null, "User is created"); T.Assert (Principal.User.Get_Id > 0, "User has an allocated key"); T.Assert (Principal.Email.Get_Id > 0, "Email has an allocated key"); AWA.Tests.Helpers.Users.Logout (Principal); -- Verify the user session declare S1 : Session_Ref; U1 : User_Ref; begin Principal.Manager.Verify_Session (Id => Principal.Session.Get_Id, Session => S1, User => U1); T.Assert (False, "Verify_Session should report a non-existent session"); exception when Not_Found => null; end; begin AWA.Tests.Helpers.Users.Logout (Principal); T.Assert (False, "Second logout should report a non-existent session"); exception when Not_Found => null; end; end Test_Logout_User; -- ------------------------------ -- Test creation of a user -- ------------------------------ procedure Test_Login_User (T : in out Test) is use type Ada.Calendar.Time; Principal : AWA.Tests.Helpers.Users.Test_User; T1 : Ada.Calendar.Time; begin begin Principal.Email.Set_Email ("[email protected]"); AWA.Tests.Helpers.Users.Login (Principal); T.Assert (False, "Login succeeded with an invalid user name"); exception when Not_Found => null; end; -- Create the user T1 := Ada.Calendar.Clock; AWA.Tests.Helpers.Users.Create_User (Principal); AWA.Tests.Helpers.Users.Logout (Principal); AWA.Tests.Helpers.Users.Login (Principal); T.Assert (not Principal.User.Is_Null, "User is created"); T.Assert (Principal.User.Get_Id > 0, "User has an allocated key"); T.Assert (Principal.Email.Get_Id > 0, "Email has an allocated key"); T.Assert (not Principal.Session.Is_Null, "Session is not created"); -- Verify the user session declare S1 : Session_Ref; U1 : User_Ref; T2 : constant Ada.Calendar.Time := Ada.Calendar.Clock; begin Principal.Manager.Verify_Session (Id => Principal.Session.Get_Id, Session => S1, User => U1); T.Assert (not S1.Is_Null, "Null session returned by Verify_Session"); T.Assert (not U1.Is_Null, "Null user returned by Verify_Session"); T.Assert (not S1.Get_Start_Date.Is_Null, "Session start date must not be null"); T.Assert (S1.Get_End_Date.Is_Null, "Session end date must be null"); Util.Tests.Assert_Equals (T, Principal.Session.Get_Start_Date.Value, S1.Get_Start_Date.Value, "Invalid start date"); -- Storing a date in the database will loose some precision. T.Assert (S1.Get_Start_Date.Value >= T1 - 1.0, "Start date is invalid 1"); T.Assert (S1.Get_Start_Date.Value <= T2 + 10.0, "Start date is invalid 3"); Principal.Manager.Close_Session (Principal.Session.Get_Id); end; end Test_Login_User; -- ------------------------------ -- Test password reset process -- ------------------------------ procedure Test_Reset_Password_User (T : in out Test) is Principal : AWA.Tests.Helpers.Users.Test_User; Key : AWA.Users.Models.Access_Key_Ref; begin -- Create the user AWA.Tests.Helpers.Users.Create_User (Principal); AWA.Tests.Helpers.Users.Logout (Principal); -- Start the lost password process. Principal.Manager.Lost_Password (Email => Principal.Email.Get_Email); AWA.Tests.Helpers.Users.Login (Principal); -- Get the access key to reset the password declare DB : ADO.Sessions.Session := Principal.Manager.Get_Session; Query : ADO.SQL.Query; Found : Boolean; begin -- Find the access key Query.Set_Filter ("user_id = ?"); Query.Bind_Param (1, Principal.User.Get_Id); Key.Find (DB, Query, Found); T.Assert (Found, "Access key for lost_password process not found"); Principal.Manager.Reset_Password (Key => Key.Get_Access_Key, Password => "newadmin", IpAddr => "192.168.1.2", User => Principal.User, Session => Principal.Session); -- Search the access key again, it must have been removed. Key.Find (DB, Query, Found); T.Assert (not Found, "The access key is still present in the database"); end; T.Assert (not Principal.User.Is_Null, "User is created"); T.Assert (Principal.User.Get_Id > 0, "User has an allocated key"); T.Assert (Principal.Email.Get_Id > 0, "Email has an allocated key"); T.Assert (not Principal.Session.Is_Null, "Session is not created"); AWA.Tests.Helpers.Users.Logout (Principal); end Test_Reset_Password_User; -- ------------------------------ -- Test Get_User_Module operation -- ------------------------------ procedure Test_Get_Module (T : in out Test) is use type AWA.Users.Module.User_Module_Access; begin declare M : constant AWA.Users.Module.User_Module_Access := AWA.Users.Module.Get_User_Module; begin T.Assert (M /= null, "Get_User_Module returned null"); end; declare S : Util.Measures.Stamp; M : AWA.Users.Module.User_Module_Access; begin for I in 1 .. 1_000 loop M := AWA.Users.Module.Get_User_Module; end loop; Util.Measures.Report (S, "Get_User_Module (1000)"); T.Assert (M /= null, "Get_User_Module returned null"); end; end Test_Get_Module; end AWA.Users.Services.Tests;
----------------------------------------------------------------------- -- users - User creation, password tests -- Copyright (C) 2009, 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.Test_Caller; with Util.Measures; with ADO; with ADO.Sessions; with ADO.SQL; with ADO.Objects; with Ada.Calendar; with AWA.Users.Module; with AWA.Tests.Helpers.Users; package body AWA.Users.Services.Tests is use Util.Tests; use ADO; use ADO.Objects; package Caller is new Util.Test_Caller (Test, "Users.Services"); procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is begin Caller.Add_Test (Suite, "Test AWA.Users.Services.Create_User", Test_Create_User'Access); Caller.Add_Test (Suite, "Test AWA.Users.Services.Close_Session", Test_Logout_User'Access); Caller.Add_Test (Suite, "Test AWA.Users.Services.Authenticate, Close_Session", Test_Login_User'Access); Caller.Add_Test (Suite, "Test AWA.Users.Services.Lost_Password, Reset_Password", Test_Reset_Password_User'Access); Caller.Add_Test (Suite, "Test AWA.Users.Module.Get_User_Module", Test_Get_Module'Access); end Add_Tests; -- ------------------------------ -- Test creation of a user -- ------------------------------ procedure Test_Create_User (T : in out Test) is Principal : AWA.Tests.Helpers.Users.Test_User; begin -- Create the user AWA.Tests.Helpers.Users.Create_User (Principal); T.Assert (not Principal.User.Is_Null, "User is created"); T.Assert (Principal.User.Get_Id > 0, "User has an allocated key"); T.Assert (Principal.Email.Get_Id > 0, "Email has an allocated key"); T.Assert (not Principal.Session.Is_Null, "Session must be created"); T.Assert (Principal.Session.Get_End_Date.Is_Null, "Session must be opened"); -- Verify the user session declare S1 : Session_Ref; U1 : User_Ref; begin Principal.Manager.Verify_Session (Id => Principal.Session.Get_Id, Session => S1, User => U1); T.Assert (not S1.Is_Null, "Null session returned by Verify_Session"); T.Assert (not U1.Is_Null, "Null user returned by Verify_Session"); T.Assert (not S1.Get_Start_Date.Is_Null, "Session must be started"); T.Assert (S1.Get_End_Date.Is_Null, "Session must not be finished"); Util.Tests.Assert_Equals (T, Principal.Session.Get_Start_Date.Value, S1.Get_Start_Date.Value, "Invalid start date"); Principal.Manager.Close_Session (Principal.Session.Get_Id); end; end Test_Create_User; -- ------------------------------ -- Test logout of a user -- ------------------------------ procedure Test_Logout_User (T : in out Test) is Principal : AWA.Tests.Helpers.Users.Test_User; begin -- Create the user AWA.Tests.Helpers.Users.Create_User (Principal); T.Assert (not Principal.User.Is_Null, "User is created"); T.Assert (Principal.User.Get_Id > 0, "User has an allocated key"); T.Assert (Principal.Email.Get_Id > 0, "Email has an allocated key"); AWA.Tests.Helpers.Users.Logout (Principal); -- Verify the user session declare S1 : Session_Ref; U1 : User_Ref; begin Principal.Manager.Verify_Session (Id => Principal.Session.Get_Id, Session => S1, User => U1); T.Assert (False, "Verify_Session should report a non-existent session"); exception when Not_Found => null; end; begin AWA.Tests.Helpers.Users.Logout (Principal); T.Assert (False, "Second logout should report a non-existent session"); exception when Not_Found => null; end; end Test_Logout_User; -- ------------------------------ -- Test creation of a user -- ------------------------------ procedure Test_Login_User (T : in out Test) is use type Ada.Calendar.Time; Principal : AWA.Tests.Helpers.Users.Test_User; T1 : Ada.Calendar.Time; begin begin Principal.Email.Set_Email ("[email protected]"); AWA.Tests.Helpers.Users.Login (Principal); T.Assert (False, "Login succeeded with an invalid user name"); exception when Not_Found => null; end; -- Create the user T1 := Ada.Calendar.Clock; AWA.Tests.Helpers.Users.Create_User (Principal); AWA.Tests.Helpers.Users.Logout (Principal); AWA.Tests.Helpers.Users.Login (Principal); T.Assert (not Principal.User.Is_Null, "User is created"); T.Assert (Principal.User.Get_Id > 0, "User has an allocated key"); T.Assert (Principal.Email.Get_Id > 0, "Email has an allocated key"); T.Assert (not Principal.Session.Is_Null, "Session is not created"); -- Verify the user session declare S1 : Session_Ref; U1 : User_Ref; T2 : constant Ada.Calendar.Time := Ada.Calendar.Clock; begin Principal.Manager.Verify_Session (Id => Principal.Session.Get_Id, Session => S1, User => U1); T.Assert (not S1.Is_Null, "Null session returned by Verify_Session"); T.Assert (not U1.Is_Null, "Null user returned by Verify_Session"); T.Assert (not S1.Get_Start_Date.Is_Null, "Session start date must not be null"); T.Assert (S1.Get_End_Date.Is_Null, "Session end date must be null"); Util.Tests.Assert_Equals (T, Principal.Session.Get_Start_Date.Value, S1.Get_Start_Date.Value, "Invalid start date"); -- Storing a date in the database will loose some precision. T.Assert (S1.Get_Start_Date.Value >= T1 - 1.0, "Start date is invalid 1"); T.Assert (S1.Get_Start_Date.Value <= T2 + 10.0, "Start date is invalid 3"); Principal.Manager.Close_Session (Principal.Session.Get_Id); end; end Test_Login_User; -- ------------------------------ -- Test password reset process -- ------------------------------ procedure Test_Reset_Password_User (T : in out Test) is use type AWA.Users.Principals.Principal_Access; Principal : AWA.Tests.Helpers.Users.Test_User; Key : AWA.Users.Models.Access_Key_Ref; begin -- Create the user AWA.Tests.Helpers.Users.Create_User (Principal); AWA.Tests.Helpers.Users.Logout (Principal); -- Start the lost password process. Principal.Manager.Lost_Password (Email => Principal.Email.Get_Email); AWA.Tests.Helpers.Users.Login (Principal); -- Get the access key to reset the password declare DB : ADO.Sessions.Session := Principal.Manager.Get_Session; Query : ADO.SQL.Query; Found : Boolean; begin -- Find the access key Query.Set_Filter ("user_id = ?"); Query.Bind_Param (1, Principal.User.Get_Id); Key.Find (DB, Query, Found); T.Assert (Found, "Access key for lost_password process not found"); Principal.Manager.Reset_Password (Key => Key.Get_Access_Key, Password => "newadmin", IpAddr => "192.168.1.2", Principal => Principal.Principal); T.Assert (Principal.Principal /= null, "No principal returned"); Principal.User := Principal.Principal.Get_User; Principal.Session := Principal.Principal.Get_Session; -- Search the access key again, it must have been removed. Key.Find (DB, Query, Found); T.Assert (not Found, "The access key is still present in the database"); end; T.Assert (not Principal.User.Is_Null, "User is created"); T.Assert (Principal.User.Get_Id > 0, "User has an allocated key"); T.Assert (Principal.Email.Get_Id > 0, "Email has an allocated key"); T.Assert (not Principal.Session.Is_Null, "Session is not created"); AWA.Tests.Helpers.Users.Logout (Principal); end Test_Reset_Password_User; -- ------------------------------ -- Test Get_User_Module operation -- ------------------------------ procedure Test_Get_Module (T : in out Test) is use type AWA.Users.Module.User_Module_Access; begin declare M : constant AWA.Users.Module.User_Module_Access := AWA.Users.Module.Get_User_Module; begin T.Assert (M /= null, "Get_User_Module returned null"); end; declare S : Util.Measures.Stamp; M : AWA.Users.Module.User_Module_Access; begin for I in 1 .. 1_000 loop M := AWA.Users.Module.Get_User_Module; end loop; Util.Measures.Report (S, "Get_User_Module (1000)"); T.Assert (M /= null, "Get_User_Module returned null"); end; end Test_Get_Module; end AWA.Users.Services.Tests;
Update the unit tests
Update the unit tests
Ada
apache-2.0
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
0416b6f1f70849c22bf10c2200e7e3680f6718fc
src/util-dates.adb
src/util-dates.adb
----------------------------------------------------------------------- -- util-dates -- Date utilities -- Copyright (C) 2011, 2013 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Calendar.Arithmetic; package body Util.Dates is -- ------------------------------ -- Split the date into a date record (See Ada.Calendar.Formatting.Split). -- ------------------------------ procedure Split (Into : out Date_Record; Date : in Ada.Calendar.Time; Time_Zone : in Ada.Calendar.Time_Zones.Time_Offset := 0) is begin Into.Date := Date; Into.Time_Zone := Time_Zone; Ada.Calendar.Formatting.Split (Date => Date, Year => Into.Year, Month => Into.Month, Day => Into.Month_Day, Hour => Into.Hour, Minute => Into.Minute, Second => Into.Second, Sub_Second => Into.Sub_Second, Leap_Second => Into.Leap_Second, Time_Zone => Time_Zone); Into.Day := Ada.Calendar.Formatting.Day_Of_Week (Date); end Split; -- ------------------------------ -- Returns true if the given year is a leap year. -- ------------------------------ function Is_Leap_Year (Year : in Ada.Calendar.Year_Number) return Boolean is begin if Year mod 400 = 0 then return True; elsif Year mod 100 = 0 then return False; elsif Year mod 4 = 0 then return True; else return False; end if; end Is_Leap_Year; -- ------------------------------ -- Get the number of days in the given year. -- ------------------------------ function Get_Day_Count (Year : in Ada.Calendar.Year_Number) return Ada.Calendar.Arithmetic.Day_Count is begin if Is_Leap_Year (Year) then return 365; else return 366; end if; end Get_Day_Count; Month_Day_Count : constant array (Ada.Calendar.Month_Number) of Ada.Calendar.Arithmetic.Day_Count := (1 => 31, 2 => 28, 3 => 31, 4 => 30, 5 => 31, 6 => 30, 7 => 31, 8 => 31, 9 => 30, 10 => 31, 11 => 30, 12 => 31); -- ------------------------------ -- Get the number of days in the given month. -- ------------------------------ function Get_Day_Count (Year : in Ada.Calendar.Year_Number; Month : in Ada.Calendar.Month_Number) return Ada.Calendar.Arithmetic.Day_Count is begin if Month /= 2 then return Month_Day_Count (Month); elsif Is_Leap_Year (Year) then return 29; else return 28; end if; end Get_Day_Count; -- ------------------------------ -- Get a time representing the given date at 00:00:00. -- ------------------------------ function Get_Day_Start (Date : in Date_Record) return Ada.Calendar.Time is begin return Ada.Calendar.Formatting.Time_Of (Year => Date.Year, Month => Date.Month, Day => Date.Month_Day, Hour => 0, Minute => 0, Second => 0, Sub_Second => 0.0, Time_Zone => Date.Time_Zone); end Get_Day_Start; function Get_Day_Start (Date : in Ada.Calendar.Time) return Ada.Calendar.Time is D : Date_Record; begin Split (D, Date); return Get_Day_Start (D); end Get_Day_Start; -- ------------------------------ -- Get a time representing the given date at 23:59:59. -- ------------------------------ function Get_Day_End (Date : in Date_Record) return Ada.Calendar.Time is begin return Ada.Calendar.Formatting.Time_Of (Year => Date.Year, Month => Date.Month, Day => Date.Month_Day, Hour => 23, Minute => 59, Second => 59, Sub_Second => 0.999, Time_Zone => Date.Time_Zone); end Get_Day_End; function Get_Day_End (Date : in Ada.Calendar.Time) return Ada.Calendar.Time is D : Date_Record; begin Split (D, Date); return Get_Day_End (D); end Get_Day_End; -- ------------------------------ -- Get a time representing the beginning of the week at 00:00:00. -- ------------------------------ function Get_Week_Start (Date : in Date_Record) return Ada.Calendar.Time is use Ada.Calendar.Formatting; use Ada.Calendar.Arithmetic; T : constant Ada.Calendar.Time := Time_Of (Year => Date.Year, Month => Date.Month, Day => Date.Month_Day, Hour => 0, Minute => 0, Second => 0, Sub_Second => 0.0, Time_Zone => Date.Time_Zone); Day : constant Ada.Calendar.Formatting.Day_Name := Ada.Calendar.Formatting.Day_Of_Week (T); begin if Day = Ada.Calendar.Formatting.Monday then return T; else return T - Day_Count (Day_Name'Pos (Day) - Day_Name'Pos (Monday)); end if; end Get_Week_Start; function Get_Week_Start (Date : in Ada.Calendar.Time) return Ada.Calendar.Time is D : Date_Record; begin Split (D, Date); return Get_Week_Start (D); end Get_Week_Start; -- ------------------------------ -- Get a time representing the end of the week at 23:59:99. -- ------------------------------ function Get_Week_End (Date : in Date_Record) return Ada.Calendar.Time is use Ada.Calendar.Formatting; use Ada.Calendar.Arithmetic; T : constant Ada.Calendar.Time := Time_Of (Year => Date.Year, Month => Date.Month, Day => Date.Month_Day, Hour => 23, Minute => 59, Second => 59, Sub_Second => 0.999, Time_Zone => Date.Time_Zone); Day : constant Ada.Calendar.Formatting.Day_Name := Ada.Calendar.Formatting.Day_Of_Week (T); begin -- End of week is 6 days + 23:59:59 if Day = Ada.Calendar.Formatting.Monday then return T + Day_Count (6); else return T + Day_Count (6 - (Day_Name'Pos (Day) - Day_Name'Pos (Monday))); end if; end Get_Week_End; function Get_Week_End (Date : in Ada.Calendar.Time) return Ada.Calendar.Time is D : Date_Record; begin Split (D, Date); return Get_Week_End (D); end Get_Week_End; -- ------------------------------ -- Get a time representing the beginning of the month at 00:00:00. -- ------------------------------ function Get_Month_Start (Date : in Date_Record) return Ada.Calendar.Time is begin return Ada.Calendar.Formatting.Time_Of (Year => Date.Year, Month => Date.Month, Day => Ada.Calendar.Day_Number'First, Hour => 0, Minute => 0, Second => 0, Sub_Second => 0.0, Time_Zone => Date.Time_Zone); end Get_Month_Start; function Get_Month_Start (Date : in Ada.Calendar.Time) return Ada.Calendar.Time is D : Date_Record; begin Split (D, Date); return Get_Month_Start (D); end Get_Month_Start; -- ------------------------------ -- Get a time representing the end of the month at 23:59:59. -- ------------------------------ function Get_Month_End (Date : in Date_Record) return Ada.Calendar.Time is Last_Day : constant Ada.Calendar.Day_Number := Ada.Calendar.Day_Number (Get_Day_Count (Date.Year, Date.Month)); begin return Ada.Calendar.Formatting.Time_Of (Year => Date.Year, Month => Date.Month, Day => Last_Day, Hour => 23, Minute => 59, Second => 59, Sub_Second => 0.999, Time_Zone => Date.Time_Zone); end Get_Month_End; function Get_Month_End (Date : in Ada.Calendar.Time) return Ada.Calendar.Time is D : Date_Record; begin Split (D, Date); return Get_Month_End (D); end Get_Month_End; end Util.Dates;
----------------------------------------------------------------------- -- util-dates -- Date utilities -- Copyright (C) 2011, 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. ----------------------------------------------------------------------- package body Util.Dates is -- ------------------------------ -- Split the date into a date record (See Ada.Calendar.Formatting.Split). -- ------------------------------ procedure Split (Into : out Date_Record; Date : in Ada.Calendar.Time; Time_Zone : in Ada.Calendar.Time_Zones.Time_Offset := 0) is begin Into.Date := Date; Into.Time_Zone := Time_Zone; Ada.Calendar.Formatting.Split (Date => Date, Year => Into.Year, Month => Into.Month, Day => Into.Month_Day, Hour => Into.Hour, Minute => Into.Minute, Second => Into.Second, Sub_Second => Into.Sub_Second, Leap_Second => Into.Leap_Second, Time_Zone => Time_Zone); Into.Day := Ada.Calendar.Formatting.Day_Of_Week (Date); end Split; -- ------------------------------ -- Returns true if the given year is a leap year. -- ------------------------------ function Is_Leap_Year (Year : in Ada.Calendar.Year_Number) return Boolean is begin if Year mod 400 = 0 then return True; elsif Year mod 100 = 0 then return False; elsif Year mod 4 = 0 then return True; else return False; end if; end Is_Leap_Year; -- ------------------------------ -- Get the number of days in the given year. -- ------------------------------ function Get_Day_Count (Year : in Ada.Calendar.Year_Number) return Ada.Calendar.Arithmetic.Day_Count is begin if Is_Leap_Year (Year) then return 365; else return 366; end if; end Get_Day_Count; Month_Day_Count : constant array (Ada.Calendar.Month_Number) of Ada.Calendar.Arithmetic.Day_Count := (1 => 31, 2 => 28, 3 => 31, 4 => 30, 5 => 31, 6 => 30, 7 => 31, 8 => 31, 9 => 30, 10 => 31, 11 => 30, 12 => 31); -- ------------------------------ -- Get the number of days in the given month. -- ------------------------------ function Get_Day_Count (Year : in Ada.Calendar.Year_Number; Month : in Ada.Calendar.Month_Number) return Ada.Calendar.Arithmetic.Day_Count is begin if Month /= 2 then return Month_Day_Count (Month); elsif Is_Leap_Year (Year) then return 29; else return 28; end if; end Get_Day_Count; -- ------------------------------ -- Get a time representing the given date at 00:00:00. -- ------------------------------ function Get_Day_Start (Date : in Date_Record) return Ada.Calendar.Time is begin return Ada.Calendar.Formatting.Time_Of (Year => Date.Year, Month => Date.Month, Day => Date.Month_Day, Hour => 0, Minute => 0, Second => 0, Sub_Second => 0.0, Time_Zone => Date.Time_Zone); end Get_Day_Start; function Get_Day_Start (Date : in Ada.Calendar.Time) return Ada.Calendar.Time is D : Date_Record; begin Split (D, Date); return Get_Day_Start (D); end Get_Day_Start; -- ------------------------------ -- Get a time representing the given date at 23:59:59. -- ------------------------------ function Get_Day_End (Date : in Date_Record) return Ada.Calendar.Time is begin return Ada.Calendar.Formatting.Time_Of (Year => Date.Year, Month => Date.Month, Day => Date.Month_Day, Hour => 23, Minute => 59, Second => 59, Sub_Second => 0.999, Time_Zone => Date.Time_Zone); end Get_Day_End; function Get_Day_End (Date : in Ada.Calendar.Time) return Ada.Calendar.Time is D : Date_Record; begin Split (D, Date); return Get_Day_End (D); end Get_Day_End; -- ------------------------------ -- Get a time representing the beginning of the week at 00:00:00. -- ------------------------------ function Get_Week_Start (Date : in Date_Record) return Ada.Calendar.Time is use Ada.Calendar.Formatting; use Ada.Calendar.Arithmetic; T : constant Ada.Calendar.Time := Time_Of (Year => Date.Year, Month => Date.Month, Day => Date.Month_Day, Hour => 0, Minute => 0, Second => 0, Sub_Second => 0.0, Time_Zone => Date.Time_Zone); Day : constant Ada.Calendar.Formatting.Day_Name := Ada.Calendar.Formatting.Day_Of_Week (T); begin if Day = Ada.Calendar.Formatting.Monday then return T; else return T - Day_Count (Day_Name'Pos (Day) - Day_Name'Pos (Monday)); end if; end Get_Week_Start; function Get_Week_Start (Date : in Ada.Calendar.Time) return Ada.Calendar.Time is D : Date_Record; begin Split (D, Date); return Get_Week_Start (D); end Get_Week_Start; -- ------------------------------ -- Get a time representing the end of the week at 23:59:99. -- ------------------------------ function Get_Week_End (Date : in Date_Record) return Ada.Calendar.Time is use Ada.Calendar.Formatting; use Ada.Calendar.Arithmetic; T : constant Ada.Calendar.Time := Time_Of (Year => Date.Year, Month => Date.Month, Day => Date.Month_Day, Hour => 23, Minute => 59, Second => 59, Sub_Second => 0.999, Time_Zone => Date.Time_Zone); Day : constant Ada.Calendar.Formatting.Day_Name := Ada.Calendar.Formatting.Day_Of_Week (T); begin -- End of week is 6 days + 23:59:59 if Day = Ada.Calendar.Formatting.Monday then return T + Day_Count (6); else return T + Day_Count (6 - (Day_Name'Pos (Day) - Day_Name'Pos (Monday))); end if; end Get_Week_End; function Get_Week_End (Date : in Ada.Calendar.Time) return Ada.Calendar.Time is D : Date_Record; begin Split (D, Date); return Get_Week_End (D); end Get_Week_End; -- ------------------------------ -- Get a time representing the beginning of the month at 00:00:00. -- ------------------------------ function Get_Month_Start (Date : in Date_Record) return Ada.Calendar.Time is begin return Ada.Calendar.Formatting.Time_Of (Year => Date.Year, Month => Date.Month, Day => Ada.Calendar.Day_Number'First, Hour => 0, Minute => 0, Second => 0, Sub_Second => 0.0, Time_Zone => Date.Time_Zone); end Get_Month_Start; function Get_Month_Start (Date : in Ada.Calendar.Time) return Ada.Calendar.Time is D : Date_Record; begin Split (D, Date); return Get_Month_Start (D); end Get_Month_Start; -- ------------------------------ -- Get a time representing the end of the month at 23:59:59. -- ------------------------------ function Get_Month_End (Date : in Date_Record) return Ada.Calendar.Time is Last_Day : constant Ada.Calendar.Day_Number := Ada.Calendar.Day_Number (Get_Day_Count (Date.Year, Date.Month)); begin return Ada.Calendar.Formatting.Time_Of (Year => Date.Year, Month => Date.Month, Day => Last_Day, Hour => 23, Minute => 59, Second => 59, Sub_Second => 0.999, Time_Zone => Date.Time_Zone); end Get_Month_End; function Get_Month_End (Date : in Ada.Calendar.Time) return Ada.Calendar.Time is D : Date_Record; begin Split (D, Date); return Get_Month_End (D); end Get_Month_End; end Util.Dates;
Fix some compilation warning
Fix some compilation warning
Ada
apache-2.0
Letractively/ada-util,Letractively/ada-util,flottokarotto/ada-util,flottokarotto/ada-util
bf599e0cb624b6f720b5b6fc334bba86a80a01d9
src/postgresql/ado-statements-postgresql.ads
src/postgresql/ado-statements-postgresql.ads
----------------------------------------------------------------------- -- ADO Postgresql statements -- Postgresql query statements -- 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 ADO.SQL; with ADO.Schemas; with PQ; package ADO.Statements.Postgresql is -- ------------------------------ -- Delete statement -- ------------------------------ type Postgresql_Delete_Statement is new Delete_Statement with private; type Postgresql_Delete_Statement_Access is access all Postgresql_Delete_Statement'Class; -- Execute the query overriding procedure Execute (Stmt : in out Postgresql_Delete_Statement; Result : out Natural); -- Create the delete statement function Create_Statement (Database : in PQ.PGconn_Access; Table : in ADO.Schemas.Class_Mapping_Access) return Delete_Statement_Access; -- ------------------------------ -- Update statement -- ------------------------------ type Postgresql_Update_Statement is new Update_Statement with private; type Postgresql_Update_Statement_Access is access all Postgresql_Update_Statement'Class; -- Execute the query overriding procedure Execute (Stmt : in out Postgresql_Update_Statement); -- Execute the query overriding procedure Execute (Stmt : in out Postgresql_Update_Statement; Result : out Integer); -- Create an update statement. function Create_Statement (Database : in PQ.PGconn_Access; Table : in ADO.Schemas.Class_Mapping_Access) return Update_Statement_Access; -- ------------------------------ -- Insert statement -- ------------------------------ type Postgresql_Insert_Statement is new Insert_Statement with private; type Postgresql_Insert_Statement_Access is access all Postgresql_Insert_Statement'Class; -- Execute the query overriding procedure Execute (Stmt : in out Postgresql_Insert_Statement; Result : out Integer); -- Create an insert statement. function Create_Statement (Database : in PQ.PGconn_Access; Table : in ADO.Schemas.Class_Mapping_Access) return Insert_Statement_Access; -- ------------------------------ -- Query statement for Postgresql -- ------------------------------ type Postgresql_Query_Statement is new Query_Statement with private; type Postgresql_Query_Statement_Access is access all Postgresql_Query_Statement'Class; -- Execute the query overriding procedure Execute (Stmt : in out Postgresql_Query_Statement); -- Get the number of rows returned by the query overriding function Get_Row_Count (Query : in Postgresql_Query_Statement) return Natural; -- Returns True if there is more data (row) to fetch overriding function Has_Elements (Query : in Postgresql_Query_Statement) return Boolean; -- Fetch the next row overriding procedure Next (Query : in out Postgresql_Query_Statement); -- Returns true if the column <b>Column</b> is null. overriding function Is_Null (Query : in Postgresql_Query_Statement; Column : in Natural) return Boolean; -- Get the column value at position <b>Column</b> and -- return it as an <b>Int64</b>. -- Raises <b>Invalid_Type</b> if the value cannot be converted. -- Raises <b>Invalid_Column</b> if the column does not exist. overriding function Get_Int64 (Query : Postgresql_Query_Statement; Column : Natural) return Int64; -- Get the column value at position <b>Column</b> and -- return it as an <b>Boolean</b>. -- Raises <b>Invalid_Type</b> if the value cannot be converted. -- Raises <b>Invalid_Column</b> if the column does not exist. overriding function Get_Boolean (Query : Postgresql_Query_Statement; Column : Natural) return Boolean; -- Get the column value at position <b>Column</b> and -- return it as an <b>Unbounded_String</b>. -- Raises <b>Invalid_Type</b> if the value cannot be converted. -- Raises <b>Invalid_Column</b> if the column does not exist. overriding function Get_Unbounded_String (Query : Postgresql_Query_Statement; Column : Natural) return Unbounded_String; -- Get the column value at position <b>Column</b> and -- return it as an <b>Unbounded_String</b>. -- Raises <b>Invalid_Type</b> if the value cannot be converted. -- Raises <b>Invalid_Column</b> if the column does not exist. overriding function Get_String (Query : Postgresql_Query_Statement; Column : Natural) return String; -- Get the column value at position <b>Column</b> and -- return it as a <b>Blob</b> reference. overriding function Get_Blob (Query : in Postgresql_Query_Statement; Column : in Natural) return ADO.Blob_Ref; -- Get the column value at position <b>Column</b> and -- return it as an <b>Time</b>. -- Raises <b>Invalid_Type</b> if the value cannot be converted. -- Raises <b>Invalid_Column</b> if the column does not exist. function Get_Time (Query : Postgresql_Query_Statement; Column : Natural) return Ada.Calendar.Time; -- Get the column type -- Raises <b>Invalid_Column</b> if the column does not exist. overriding function Get_Column_Type (Query : Postgresql_Query_Statement; Column : Natural) return ADO.Schemas.Column_Type; -- Get the column name. -- Raises <b>Invalid_Column</b> if the column does not exist. overriding function Get_Column_Name (Query : in Postgresql_Query_Statement; Column : in Natural) return String; -- Get the number of columns in the result. overriding function Get_Column_Count (Query : in Postgresql_Query_Statement) return Natural; overriding procedure Finalize (Query : in out Postgresql_Query_Statement); -- Create the query statement. function Create_Statement (Database : in PQ.PGconn_Access; Table : in ADO.Schemas.Class_Mapping_Access) return Query_Statement_Access; function Create_Statement (Database : in PQ.PGconn_Access; Query : in String) return Query_Statement_Access; private type State is (HAS_ROW, HAS_MORE, DONE, ERROR); type Postgresql_Query_Statement is new Query_Statement with record This_Query : aliased ADO.SQL.Query; Connection : PQ.PGconn_Access := PQ.Null_PGconn; Result : PQ.PGresult_Access := PQ.Null_PGresult; Row : Interfaces.C.int := 0; Row_Count : Interfaces.C.int := 0; Counter : Natural := 1; Status : State := DONE; Max_Column : Natural; end record; -- Get a column field address. -- If the query was not executed, raises Invalid_Statement -- If the column is out of bound, raises Constraint_Error function Get_Field (Query : Postgresql_Query_Statement'Class; Column : Natural) return chars_ptr; -- Get a column field length. -- If the query was not executed, raises Invalid_Statement -- If the column is out of bound, raises Constraint_Error -- ------------------------------ function Get_Field_Length (Query : in Postgresql_Query_Statement'Class; Column : in Natural) return Natural; type Postgresql_Delete_Statement is new Delete_Statement with record Connection : PQ.PGconn_Access; Table : ADO.Schemas.Class_Mapping_Access; Delete_Query : aliased ADO.SQL.Query; end record; type Postgresql_Update_Statement is new Update_Statement with record Connection : PQ.PGconn_Access; This_Query : aliased ADO.SQL.Update_Query; Table : ADO.Schemas.Class_Mapping_Access; end record; type Postgresql_Insert_Statement is new Insert_Statement with record Connection : PQ.PGconn_Access; This_Query : aliased ADO.SQL.Update_Query; Table : ADO.Schemas.Class_Mapping_Access; end record; end ADO.Statements.Postgresql;
----------------------------------------------------------------------- -- ADO Postgresql statements -- Postgresql query statements -- Copyright (C) 2018, 2019 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with ADO.SQL; with ADO.Schemas; with PQ; package ADO.Statements.Postgresql is -- ------------------------------ -- Delete statement -- ------------------------------ type Postgresql_Delete_Statement is new Delete_Statement with private; type Postgresql_Delete_Statement_Access is access all Postgresql_Delete_Statement'Class; -- Execute the query overriding procedure Execute (Stmt : in out Postgresql_Delete_Statement; Result : out Natural); -- Create the delete statement function Create_Statement (Database : in PQ.PGconn_Access; Table : in ADO.Schemas.Class_Mapping_Access) return Delete_Statement_Access; -- ------------------------------ -- Update statement -- ------------------------------ type Postgresql_Update_Statement is new Update_Statement with private; type Postgresql_Update_Statement_Access is access all Postgresql_Update_Statement'Class; -- Execute the query overriding procedure Execute (Stmt : in out Postgresql_Update_Statement); -- Execute the query overriding procedure Execute (Stmt : in out Postgresql_Update_Statement; Result : out Integer); -- Create an update statement. function Create_Statement (Database : in PQ.PGconn_Access; Table : in ADO.Schemas.Class_Mapping_Access) return Update_Statement_Access; -- ------------------------------ -- Insert statement -- ------------------------------ type Postgresql_Insert_Statement is new Insert_Statement with private; type Postgresql_Insert_Statement_Access is access all Postgresql_Insert_Statement'Class; -- Execute the query overriding procedure Execute (Stmt : in out Postgresql_Insert_Statement; Result : out Integer); -- Create an insert statement. function Create_Statement (Database : in PQ.PGconn_Access; Table : in ADO.Schemas.Class_Mapping_Access) return Insert_Statement_Access; -- ------------------------------ -- Query statement for Postgresql -- ------------------------------ type Postgresql_Query_Statement is new Query_Statement with private; type Postgresql_Query_Statement_Access is access all Postgresql_Query_Statement'Class; -- Execute the query overriding procedure Execute (Stmt : in out Postgresql_Query_Statement); -- Get the number of rows returned by the query overriding function Get_Row_Count (Query : in Postgresql_Query_Statement) return Natural; -- Returns True if there is more data (row) to fetch overriding function Has_Elements (Query : in Postgresql_Query_Statement) return Boolean; -- Fetch the next row overriding procedure Next (Query : in out Postgresql_Query_Statement); -- Returns true if the column <b>Column</b> is null. overriding function Is_Null (Query : in Postgresql_Query_Statement; Column : in Natural) return Boolean; -- Get the column value at position <b>Column</b> and -- return it as an <b>Int64</b>. -- Raises <b>Invalid_Type</b> if the value cannot be converted. -- Raises <b>Invalid_Column</b> if the column does not exist. overriding function Get_Int64 (Query : Postgresql_Query_Statement; Column : Natural) return Int64; -- Get the column value at position <b>Column</b> and -- return it as an <b>Long_Float</b>. -- Raises <b>Invalid_Type</b> if the value cannot be converted. -- Raises <b>Invalid_Column</b> if the column does not exist. overriding function Get_Double (Query : Postgresql_Query_Statement; Column : Natural) return Long_Float; -- Get the column value at position <b>Column</b> and -- return it as an <b>Boolean</b>. -- Raises <b>Invalid_Type</b> if the value cannot be converted. -- Raises <b>Invalid_Column</b> if the column does not exist. overriding function Get_Boolean (Query : Postgresql_Query_Statement; Column : Natural) return Boolean; -- Get the column value at position <b>Column</b> and -- return it as an <b>Unbounded_String</b>. -- Raises <b>Invalid_Type</b> if the value cannot be converted. -- Raises <b>Invalid_Column</b> if the column does not exist. overriding function Get_Unbounded_String (Query : Postgresql_Query_Statement; Column : Natural) return Unbounded_String; -- Get the column value at position <b>Column</b> and -- return it as an <b>Unbounded_String</b>. -- Raises <b>Invalid_Type</b> if the value cannot be converted. -- Raises <b>Invalid_Column</b> if the column does not exist. overriding function Get_String (Query : Postgresql_Query_Statement; Column : Natural) return String; -- Get the column value at position <b>Column</b> and -- return it as a <b>Blob</b> reference. overriding function Get_Blob (Query : in Postgresql_Query_Statement; Column : in Natural) return ADO.Blob_Ref; -- Get the column value at position <b>Column</b> and -- return it as an <b>Time</b>. -- Raises <b>Invalid_Type</b> if the value cannot be converted. -- Raises <b>Invalid_Column</b> if the column does not exist. function Get_Time (Query : Postgresql_Query_Statement; Column : Natural) return Ada.Calendar.Time; -- Get the column type -- Raises <b>Invalid_Column</b> if the column does not exist. overriding function Get_Column_Type (Query : Postgresql_Query_Statement; Column : Natural) return ADO.Schemas.Column_Type; -- Get the column name. -- Raises <b>Invalid_Column</b> if the column does not exist. overriding function Get_Column_Name (Query : in Postgresql_Query_Statement; Column : in Natural) return String; -- Get the number of columns in the result. overriding function Get_Column_Count (Query : in Postgresql_Query_Statement) return Natural; overriding procedure Finalize (Query : in out Postgresql_Query_Statement); -- Create the query statement. function Create_Statement (Database : in PQ.PGconn_Access; Table : in ADO.Schemas.Class_Mapping_Access) return Query_Statement_Access; function Create_Statement (Database : in PQ.PGconn_Access; Query : in String) return Query_Statement_Access; private type State is (HAS_ROW, HAS_MORE, DONE, ERROR); type Postgresql_Query_Statement is new Query_Statement with record This_Query : aliased ADO.SQL.Query; Connection : PQ.PGconn_Access := PQ.Null_PGconn; Result : PQ.PGresult_Access := PQ.Null_PGresult; Row : Interfaces.C.int := 0; Row_Count : Interfaces.C.int := 0; Counter : Natural := 1; Status : State := DONE; Max_Column : Natural; end record; -- Get a column field address. -- If the query was not executed, raises Invalid_Statement -- If the column is out of bound, raises Constraint_Error function Get_Field (Query : Postgresql_Query_Statement'Class; Column : Natural) return chars_ptr; -- Get a column field length. -- If the query was not executed, raises Invalid_Statement -- If the column is out of bound, raises Constraint_Error -- ------------------------------ function Get_Field_Length (Query : in Postgresql_Query_Statement'Class; Column : in Natural) return Natural; type Postgresql_Delete_Statement is new Delete_Statement with record Connection : PQ.PGconn_Access; Table : ADO.Schemas.Class_Mapping_Access; Delete_Query : aliased ADO.SQL.Query; end record; type Postgresql_Update_Statement is new Update_Statement with record Connection : PQ.PGconn_Access; This_Query : aliased ADO.SQL.Update_Query; Table : ADO.Schemas.Class_Mapping_Access; end record; type Postgresql_Insert_Statement is new Insert_Statement with record Connection : PQ.PGconn_Access; This_Query : aliased ADO.SQL.Update_Query; Table : ADO.Schemas.Class_Mapping_Access; end record; end ADO.Statements.Postgresql;
Declare the Get_Double function to support floating point columns
Declare the Get_Double function to support floating point columns
Ada
apache-2.0
stcarrez/ada-ado
35cb08c934bd29bbb252fb65d327f007344df304
tools/druss-commands-ping.adb
tools/druss-commands-ping.adb
----------------------------------------------------------------------- -- druss-commands-devices -- Print information about the devices -- 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.Properties; with Util.Log.Loggers; with Bbox.API; with Druss.Gateways; with Ada.Strings.Unbounded; package body Druss.Commands.Ping is use Ada.Strings.Unbounded; -- The logger Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("Druss.Commands.Ping"); -- ------------------------------ -- Execute the wifi 'status' command to print the Wifi current status. -- ------------------------------ procedure Do_Ping (Command : in Command_Type; Args : in Argument_List'Class; Selector : in Device_Selector_Type; Context : in out Context_Type) is pragma Unreferenced (Command, Args); procedure Do_Ping (Gateway : in out Druss.Gateways.Gateway_Type); procedure Box_Status (Gateway : in out Druss.Gateways.Gateway_Type); Console : constant Druss.Commands.Consoles.Console_Access := Context.Console; procedure Do_Ping (Gateway : in out Druss.Gateways.Gateway_Type) is procedure Ping_Device (Manager : in Util.Properties.Manager; Name : in String); Box : Bbox.API.Client_Type; procedure Ping_Device (Manager : in Util.Properties.Manager; Name : in String) is Id : constant String := Manager.Get (Name & ".id", ""); begin case Selector is when DEVICE_ALL => null; when DEVICE_ACTIVE => if Manager.Get (Name & ".active", "") = "0" then return; end if; when DEVICE_INACTIVE => if Manager.Get (Name & ".active", "") = "1" then return; end if; end case; Log.Info ("Ping command on {0}", Manager.Get (Name & ".ipaddress", "")); Box.Post ("hosts/" & Id, "action=ping"); end Ping_Device; begin if Ada.Strings.Unbounded.Length (Gateway.Passwd) = 0 then return; end if; Gateway.Refresh; Box.Set_Server (To_String (Gateway.Ip)); Box.Login (To_String (Gateway.Passwd)); Bbox.API.Iterate (Gateway.Hosts, "hosts.list", Ping_Device'Access); end Do_Ping; procedure Box_Status (Gateway : in out Druss.Gateways.Gateway_Type) is procedure Print_Device (Manager : in Util.Properties.Manager; Name : in String); procedure Print_Device (Manager : in Util.Properties.Manager; Name : in String) is Link : constant String := Manager.Get (Name & ".link", ""); begin if Manager.Get (Name & ".active", "") = "0" then return; end if; Console.Start_Row; Console.Print_Field (F_BBOX_IP_ADDR, Gateway.Ip); Console.Print_Field (F_IP_ADDR, Manager.Get (Name & ".ipaddress", "")); Console.Print_Field (F_HOSTNAME, Manager.Get (Name & ".hostname", "")); Print_Perf (Console, F_ACTIVE, Manager.Get (Name & ".ping.average", "")); if Link = "Ethernet" then Console.Print_Field (F_LINK, Link & " port " & Manager.Get (Name & ".ethernet.logicalport", "")); else Console.Print_Field (F_LINK, Link & " RSSI " & Manager.Get (Name & ".wireless.rssi0", "")); end if; Console.End_Row; end Print_Device; begin Gateway.Refresh; Bbox.API.Iterate (Gateway.Hosts, "hosts.list", Print_Device'Access); end Box_Status; begin Druss.Gateways.Iterate (Context.Gateways, Gateways.ITER_ENABLE, Do_Ping'Access); delay 5.0; Console.Start_Title; Console.Print_Title (F_BBOX_IP_ADDR, "Bbox IP", 16); Console.Print_Title (F_IP_ADDR, "Device IP", 16); Console.Print_Title (F_HOSTNAME, "Hostname", 28); Console.Print_Title (F_ACTIVE, "Ping", 15); Console.Print_Title (F_LINK, "Link", 18); Console.End_Title; Druss.Gateways.Iterate (Context.Gateways, Gateways.ITER_ENABLE, Box_Status'Access); end Do_Ping; -- ------------------------------ -- Execute a ping from the gateway to each device. -- ------------------------------ overriding procedure Execute (Command : in out Command_Type; Name : in String; Args : in Argument_List'Class; Context : in out Context_Type) is pragma Unreferenced (Name); begin if Args.Get_Count > 1 then Context.Console.Notice (N_USAGE, "Too many arguments to the command"); Druss.Commands.Driver.Usage (Args); elsif Args.Get_Count = 0 then Command.Do_Ping (Args, DEVICE_ALL, Context); elsif Args.Get_Argument (1) = "all" then Command.Do_Ping (Args, DEVICE_ALL, Context); elsif Args.Get_Argument (1) = "active" then Command.Do_Ping (Args, DEVICE_ACTIVE, Context); elsif Args.Get_Argument (1) = "inactive" then Command.Do_Ping (Args, DEVICE_INACTIVE, Context); else Context.Console.Notice (N_USAGE, "Invalid argument: " & 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 pragma Unreferenced (Command); Console : constant Druss.Commands.Consoles.Console_Access := Context.Console; begin Console.Notice (N_HELP, "ping: Ask the Bbox to ping the devices"); Console.Notice (N_HELP, "Usage: ping [all | active | inactive]"); Console.Notice (N_HELP, ""); Console.Notice (N_HELP, " Ask the Bbox to ping the devices. By default it will ping"); Console.Notice (N_HELP, " all the devices that have been discovered by the Bbox."); Console.Notice (N_HELP, " The command will wait 5 seconds and it will list the active"); Console.Notice (N_HELP, " devices with their ping performance."); Console.Notice (N_HELP, ""); Console.Notice (N_HELP, " all Ping all the devices"); Console.Notice (N_HELP, " active Ping the active devices only"); Console.Notice (N_HELP, " inative Ping the inactive devices only"); end Help; end Druss.Commands.Ping;
----------------------------------------------------------------------- -- druss-commands-devices -- Print information about the devices -- 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 Util.Properties; with Util.Log.Loggers; with Bbox.API; with Druss.Gateways; with Ada.Strings.Unbounded; package body Druss.Commands.Ping is use Ada.Strings.Unbounded; -- The logger Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("Druss.Commands.Ping"); -- ------------------------------ -- Execute the wifi 'status' command to print the Wifi current status. -- ------------------------------ procedure Do_Ping (Command : in Command_Type; Args : in Argument_List'Class; Selector : in Device_Selector_Type; Context : in out Context_Type) is pragma Unreferenced (Command, Args); procedure Do_Ping (Gateway : in out Druss.Gateways.Gateway_Type); procedure Box_Status (Gateway : in out Druss.Gateways.Gateway_Type); Console : constant Druss.Commands.Consoles.Console_Access := Context.Console; procedure Do_Ping (Gateway : in out Druss.Gateways.Gateway_Type) is procedure Ping_Device (Manager : in Util.Properties.Manager; Name : in String); Box : Bbox.API.Client_Type; procedure Ping_Device (Manager : in Util.Properties.Manager; Name : in String) is Id : constant String := Manager.Get (Name & ".id", ""); begin case Selector is when DEVICE_ALL => null; when DEVICE_ACTIVE => if Manager.Get (Name & ".active", "") = "0" then return; end if; when DEVICE_INACTIVE => if Manager.Get (Name & ".active", "") = "1" then return; end if; end case; Log.Info ("Ping command on {0}", Manager.Get (Name & ".ipaddress", "")); Box.Post ("hosts/" & Id, "action=ping"); end Ping_Device; begin if Ada.Strings.Unbounded.Length (Gateway.Passwd) = 0 then return; end if; Gateway.Refresh; Box.Set_Server (To_String (Gateway.Ip)); Box.Login (To_String (Gateway.Passwd)); Bbox.API.Iterate (Gateway.Hosts, "hosts.list", Ping_Device'Access); end Do_Ping; procedure Box_Status (Gateway : in out Druss.Gateways.Gateway_Type) is procedure Print_Device (Manager : in Util.Properties.Manager; Name : in String); procedure Print_Device (Manager : in Util.Properties.Manager; Name : in String) is Link : constant String := Manager.Get (Name & ".link", ""); begin if Manager.Get (Name & ".active", "") = "0" then return; end if; Console.Start_Row; Console.Print_Field (F_BBOX_IP_ADDR, Gateway.Ip); Console.Print_Field (F_IP_ADDR, Manager.Get (Name & ".ipaddress", "")); Console.Print_Field (F_HOSTNAME, Manager.Get (Name & ".hostname", "")); Print_Perf (Console, F_ACTIVE, Manager.Get (Name & ".ping.average", "")); if Link = "Ethernet" then Console.Print_Field (F_LINK, Link & " port " & Manager.Get (Name & ".ethernet.logicalport", "")); else Console.Print_Field (F_LINK, Link & " RSSI " & Manager.Get (Name & ".wireless.rssi0", "")); end if; Console.End_Row; end Print_Device; begin Gateway.Refresh; Bbox.API.Iterate (Gateway.Hosts, "hosts.list", Print_Device'Access); end Box_Status; begin Druss.Gateways.Iterate (Context.Gateways, Gateways.ITER_ENABLE, Do_Ping'Access); delay 5.0; Console.Start_Title; Console.Print_Title (F_BBOX_IP_ADDR, "Bbox IP", 16); Console.Print_Title (F_IP_ADDR, "Device IP", 16); Console.Print_Title (F_HOSTNAME, "Hostname", 28); Console.Print_Title (F_ACTIVE, "Ping", 15); Console.Print_Title (F_LINK, "Link", 18); Console.End_Title; Druss.Gateways.Iterate (Context.Gateways, Gateways.ITER_ENABLE, Box_Status'Access); end Do_Ping; -- ------------------------------ -- Execute a ping from the gateway to each device. -- ------------------------------ overriding procedure Execute (Command : in out Command_Type; Name : in String; Args : in Argument_List'Class; Context : in out Context_Type) is pragma Unreferenced (Name); begin if Args.Get_Count > 1 then Context.Console.Notice (N_USAGE, "Too many arguments to the command"); Druss.Commands.Driver.Usage (Args, Context); elsif Args.Get_Count = 0 then Command.Do_Ping (Args, DEVICE_ALL, Context); elsif Args.Get_Argument (1) = "all" then Command.Do_Ping (Args, DEVICE_ALL, Context); elsif Args.Get_Argument (1) = "active" then Command.Do_Ping (Args, DEVICE_ACTIVE, Context); elsif Args.Get_Argument (1) = "inactive" then Command.Do_Ping (Args, DEVICE_INACTIVE, Context); else Context.Console.Notice (N_USAGE, "Invalid argument: " & Args.Get_Argument (1)); Druss.Commands.Driver.Usage (Args, Context); end if; end Execute; -- ------------------------------ -- Write the help associated with the command. -- ------------------------------ overriding procedure Help (Command : in out Command_Type; Context : in out Context_Type) is pragma Unreferenced (Command); Console : constant Druss.Commands.Consoles.Console_Access := Context.Console; begin Console.Notice (N_HELP, "ping: Ask the Bbox to ping the devices"); Console.Notice (N_HELP, "Usage: ping [all | active | inactive]"); Console.Notice (N_HELP, ""); Console.Notice (N_HELP, " Ask the Bbox to ping the devices. By default it will ping"); Console.Notice (N_HELP, " all the devices that have been discovered by the Bbox."); Console.Notice (N_HELP, " The command will wait 5 seconds and it will list the active"); Console.Notice (N_HELP, " devices with their ping performance."); Console.Notice (N_HELP, ""); Console.Notice (N_HELP, " all Ping all the devices"); Console.Notice (N_HELP, " active Ping the active devices only"); Console.Notice (N_HELP, " inative Ping the inactive devices only"); end Help; end Druss.Commands.Ping;
Change Help command to accept in out command
Change Help command to accept in out command
Ada
apache-2.0
stcarrez/bbox-ada-api
ef6e7a860a77e4b43413aeebcfd77ec1fc7d5378
src/asf-routes.ads
src/asf-routes.ads
----------------------------------------------------------------------- -- asf-routes -- Request routing -- 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; with Util.Beans.Basic; with EL.Expressions; with EL.Contexts; package ASF.Routes is type Route_Type is limited interface; type Route_Type_Access is access all Route_Type'Class; -- The <tt>Route_Context_Type</tt> defines the context information after a path -- has been routed. type Route_Context_Type is tagged limited private; -- Get path information after the routing. function Get_Path_Info (Context : in Route_Context_Type) return String; -- Return the route associated with the resolved route context. function Get_Route (Context : in Route_Context_Type) return Route_Type_Access; -- Inject the parameters that have been extracted from the path according -- to the selected route. procedure Inject_Parameters (Context : in Route_Context_Type; Into : in out Util.Beans.Basic.Bean'Class; ELContext : in EL.Contexts.ELContext'Class); -- The <tt>Router_Type</tt> registers the different routes with their rules and -- resolves a path into a route context information. type Router_Type is new Ada.Finalization.Limited_Controlled with private; type Router_Type_Access is access all Router_Type'Class; -- Add a route associated with the given path pattern. The pattern is split into components. -- Some path components can be a fixed string (/home) and others can be variable. -- When a path component is variable, the value can be retrieved from the route context. procedure Add_Route (Router : in out Router_Type; Pattern : in String; To : in Route_Type_Access; ELContext : in EL.Contexts.ELContext'Class); -- Build the route context from the given path by looking at the different routes registered -- in the router with <tt>Add_Route</tt>. procedure Find_Route (Router : in Router_Type; Path : in String; Context : in out Route_Context_Type'Class); -- Walk the routes that have been added by <tt>Add_Route</tt> and call the <tt>Process</tt> -- procedure with each path pattern and route object. procedure Iterate (Router : in Router_Type; Process : not null access procedure (Pattern : in String; Route : in Route_Type_Access)); private type String_Access is access all String; type Route_Node_Type; type Route_Node_Access is access all Route_Node_Type'Class; type Route_Match_Type is (NO_MATCH, MAYBE_MATCH, WILDCARD_MATCH, YES_MATCH); type Route_Node_Type is abstract tagged limited record Next_Route : Route_Node_Access; Children : Route_Node_Access; Route : Route_Type_Access; end record; -- Inject the parameter that was extracted from the path. procedure Inject_Parameter (Node : in Route_Node_Type; Param : in String; Into : in out Util.Beans.Basic.Bean'Class; ELContext : in EL.Contexts.ELContext'Class) is null; -- Check if the route node accepts the given path component. function Matches (Node : in Route_Node_Type; Name : in String; Is_Last : in Boolean) return Route_Match_Type is abstract; -- Return the component path pattern that this route node represents. -- Example: 'index.html', '#{user.id}', ':id' function Get_Pattern (Node : in Route_Node_Type) return String is abstract; -- Find recursively a match on the given route sub-tree. The match must start at the position -- <tt>First</tt> in the path up to the last path position. While the path components are -- checked, the route context is populated with variable components. When the full path -- matches, <tt>YES_MATCH</tt> is returned in the context gets the route instance. procedure Find_Match (Node : in Route_Node_Type; Path : in String; First : in Natural; Match : out Route_Match_Type; Context : in out Route_Context_Type'Class); -- Walk the routes that have been added by <tt>Add_Route</tt> and call the <tt>Process</tt> -- procedure with each path pattern and route object. procedure Iterate (Node : in Route_Node_Type; Path : in String; Process : not null access procedure (Pattern : in String; Route : in Route_Type_Access)); -- A fixed path component identification. type Path_Node_Type (Len : Natural) is new Route_Node_Type with record Name : aliased String (1 .. Len); end record; type Path_Node_Access is access all Path_Node_Type'Class; -- Check if the route node accepts the given path component. -- Returns YES_MATCH if the name corresponds exactly to the node's name. overriding function Matches (Node : in Path_Node_Type; Name : in String; Is_Last : in Boolean) return Route_Match_Type; -- Return the component path pattern that this route node represents (ie, 'Name'). overriding function Get_Pattern (Node : in Path_Node_Type) return String; -- A variable path component whose value is injected in an Ada bean using the EL expression. -- The route node is created each time an EL expression is found in the route pattern. -- Example: /home/#{user.id}/index.html -- In this example, the EL expression refers to <tt>user.id</tt>. type EL_Node_Type is new Route_Node_Type with record Value : EL.Expressions.Value_Expression; end record; type EL_Node_Access is access all EL_Node_Type'Class; -- Check if the route node accepts the given path component. -- Returns MAYBE_MATCH. overriding function Matches (Node : in EL_Node_Type; Name : in String; Is_Last : in Boolean) return Route_Match_Type; -- Return the component path pattern that this route node represents (ie, the EL expr). overriding function Get_Pattern (Node : in EL_Node_Type) return String; -- Inject the parameter that was extracted from the path. overriding procedure Inject_Parameter (Node : in EL_Node_Type; Param : in String; Into : in out Util.Beans.Basic.Bean'Class; ELContext : in EL.Contexts.ELContext'Class); -- A variable path component which can be injected in an Ada bean. -- Example: /home/:id/view.html -- The path component represented by <tt>:id</tt> is injected in the Ada bean object -- passed to the <tt>Inject_Parameters</tt> procedure. type Param_Node_Type (Len : Natural) is new Route_Node_Type with record Name : String (1 .. Len); end record; type Param_Node_Access is access all Param_Node_Type'Class; -- Check if the route node accepts the given path component. -- Returns MAYBE_MATCH. overriding function Matches (Node : in Param_Node_Type; Name : in String; Is_Last : in Boolean) return Route_Match_Type; -- Return the component path pattern that this route node represents (ie, Name). overriding function Get_Pattern (Node : in Param_Node_Type) return String; -- Inject the parameter that was extracted from the path. overriding procedure Inject_Parameter (Node : in Param_Node_Type; Param : in String; Into : in out Util.Beans.Basic.Bean'Class; ELContext : in EL.Contexts.ELContext'Class); type Extension_Node_Type (Len : Natural) is new Route_Node_Type with record Ext : String (1 .. Len); end record; type Extension_Node_Access is access all Extension_Node_Type'Class; -- Check if the route node accepts the given extension. -- Returns MAYBE_MATCH. overriding function Matches (Node : in Extension_Node_Type; Name : in String; Is_Last : in Boolean) return Route_Match_Type; -- Return the component path pattern that this route node represents (ie, *.Ext). overriding function Get_Pattern (Node : in Extension_Node_Type) return String; type Wildcard_Node_Type is new Route_Node_Type with null record; type Wildcard_Node_Access is access all Wildcard_Node_Type'Class; -- Check if the route node accepts the given extension. -- Returns WILDCARD_MATCH. overriding function Matches (Node : in Wildcard_Node_Type; Name : in String; Is_Last : in Boolean) return Route_Match_Type; -- Return the component path pattern that this route node represents (ie, *). overriding function Get_Pattern (Node : in Wildcard_Node_Type) return String; -- Describes a variable path component whose value must be injected in an Ada bean. type Route_Param_Type is limited record Route : Route_Node_Access; First : Natural := 0; Last : Natural := 0; end record; type Route_Param_Array is array (Positive range <>) of Route_Param_Type; MAX_ROUTE_PARAMS : constant Positive := 10; type Route_Context_Type is limited new Ada.Finalization.Limited_Controlled with record Route : Route_Type_Access; Path : String_Access; Params : Route_Param_Array (1 .. MAX_ROUTE_PARAMS); Count : Natural := 0; end record; -- Release the storage held by the route context. overriding procedure Finalize (Context : in out Route_Context_Type); type Router_Type is new Ada.Finalization.Limited_Controlled with record Route : aliased Path_Node_Type (Len => 0); end record; -- Release the storage held by the router. overriding procedure Finalize (Router : in out Router_Type); end ASF.Routes;
----------------------------------------------------------------------- -- asf-routes -- Request routing -- 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; with Util.Beans.Basic; with EL.Expressions; with EL.Contexts; package ASF.Routes is type Route_Type is limited interface; type Route_Type_Access is access all Route_Type'Class; -- The <tt>Route_Context_Type</tt> defines the context information after a path -- has been routed. type Route_Context_Type is tagged limited private; -- Get path information after the routing. function Get_Path_Info (Context : in Route_Context_Type) return String; -- Return the position of the variable part of the path. -- If the URI matches a wildcard pattern, the position of the last '/' in the wildcard pattern -- is returned. function Get_Path_Pos (Context : in Route_Context_Type) return Natural; -- Return the route associated with the resolved route context. function Get_Route (Context : in Route_Context_Type) return Route_Type_Access; -- Inject the parameters that have been extracted from the path according -- to the selected route. procedure Inject_Parameters (Context : in Route_Context_Type; Into : in out Util.Beans.Basic.Bean'Class; ELContext : in EL.Contexts.ELContext'Class); -- The <tt>Router_Type</tt> registers the different routes with their rules and -- resolves a path into a route context information. type Router_Type is new Ada.Finalization.Limited_Controlled with private; type Router_Type_Access is access all Router_Type'Class; -- Add a route associated with the given path pattern. The pattern is split into components. -- Some path components can be a fixed string (/home) and others can be variable. -- When a path component is variable, the value can be retrieved from the route context. procedure Add_Route (Router : in out Router_Type; Pattern : in String; To : in Route_Type_Access; ELContext : in EL.Contexts.ELContext'Class); -- Build the route context from the given path by looking at the different routes registered -- in the router with <tt>Add_Route</tt>. procedure Find_Route (Router : in Router_Type; Path : in String; Context : in out Route_Context_Type'Class); -- Walk the routes that have been added by <tt>Add_Route</tt> and call the <tt>Process</tt> -- procedure with each path pattern and route object. procedure Iterate (Router : in Router_Type; Process : not null access procedure (Pattern : in String; Route : in Route_Type_Access)); private type String_Access is access all String; type Route_Node_Type; type Route_Node_Access is access all Route_Node_Type'Class; type Route_Match_Type is (NO_MATCH, MAYBE_MATCH, WILDCARD_MATCH, YES_MATCH); type Route_Node_Type is abstract tagged limited record Next_Route : Route_Node_Access; Children : Route_Node_Access; Route : Route_Type_Access; end record; -- Inject the parameter that was extracted from the path. procedure Inject_Parameter (Node : in Route_Node_Type; Param : in String; Into : in out Util.Beans.Basic.Bean'Class; ELContext : in EL.Contexts.ELContext'Class) is null; -- Check if the route node accepts the given path component. function Matches (Node : in Route_Node_Type; Name : in String; Is_Last : in Boolean) return Route_Match_Type is abstract; -- Return the component path pattern that this route node represents. -- Example: 'index.html', '#{user.id}', ':id' function Get_Pattern (Node : in Route_Node_Type) return String is abstract; -- Find recursively a match on the given route sub-tree. The match must start at the position -- <tt>First</tt> in the path up to the last path position. While the path components are -- checked, the route context is populated with variable components. When the full path -- matches, <tt>YES_MATCH</tt> is returned in the context gets the route instance. procedure Find_Match (Node : in Route_Node_Type; Path : in String; First : in Natural; Match : out Route_Match_Type; Context : in out Route_Context_Type'Class); -- Walk the routes that have been added by <tt>Add_Route</tt> and call the <tt>Process</tt> -- procedure with each path pattern and route object. procedure Iterate (Node : in Route_Node_Type; Path : in String; Process : not null access procedure (Pattern : in String; Route : in Route_Type_Access)); -- A fixed path component identification. type Path_Node_Type (Len : Natural) is new Route_Node_Type with record Name : aliased String (1 .. Len); end record; type Path_Node_Access is access all Path_Node_Type'Class; -- Check if the route node accepts the given path component. -- Returns YES_MATCH if the name corresponds exactly to the node's name. overriding function Matches (Node : in Path_Node_Type; Name : in String; Is_Last : in Boolean) return Route_Match_Type; -- Return the component path pattern that this route node represents (ie, 'Name'). overriding function Get_Pattern (Node : in Path_Node_Type) return String; -- A variable path component whose value is injected in an Ada bean using the EL expression. -- The route node is created each time an EL expression is found in the route pattern. -- Example: /home/#{user.id}/index.html -- In this example, the EL expression refers to <tt>user.id</tt>. type EL_Node_Type is new Route_Node_Type with record Value : EL.Expressions.Value_Expression; end record; type EL_Node_Access is access all EL_Node_Type'Class; -- Check if the route node accepts the given path component. -- Returns MAYBE_MATCH. overriding function Matches (Node : in EL_Node_Type; Name : in String; Is_Last : in Boolean) return Route_Match_Type; -- Return the component path pattern that this route node represents (ie, the EL expr). overriding function Get_Pattern (Node : in EL_Node_Type) return String; -- Inject the parameter that was extracted from the path. overriding procedure Inject_Parameter (Node : in EL_Node_Type; Param : in String; Into : in out Util.Beans.Basic.Bean'Class; ELContext : in EL.Contexts.ELContext'Class); -- A variable path component which can be injected in an Ada bean. -- Example: /home/:id/view.html -- The path component represented by <tt>:id</tt> is injected in the Ada bean object -- passed to the <tt>Inject_Parameters</tt> procedure. type Param_Node_Type (Len : Natural) is new Route_Node_Type with record Name : String (1 .. Len); end record; type Param_Node_Access is access all Param_Node_Type'Class; -- Check if the route node accepts the given path component. -- Returns MAYBE_MATCH. overriding function Matches (Node : in Param_Node_Type; Name : in String; Is_Last : in Boolean) return Route_Match_Type; -- Return the component path pattern that this route node represents (ie, Name). overriding function Get_Pattern (Node : in Param_Node_Type) return String; -- Inject the parameter that was extracted from the path. overriding procedure Inject_Parameter (Node : in Param_Node_Type; Param : in String; Into : in out Util.Beans.Basic.Bean'Class; ELContext : in EL.Contexts.ELContext'Class); type Extension_Node_Type (Len : Natural) is new Route_Node_Type with record Ext : String (1 .. Len); end record; type Extension_Node_Access is access all Extension_Node_Type'Class; -- Check if the route node accepts the given extension. -- Returns MAYBE_MATCH. overriding function Matches (Node : in Extension_Node_Type; Name : in String; Is_Last : in Boolean) return Route_Match_Type; -- Return the component path pattern that this route node represents (ie, *.Ext). overriding function Get_Pattern (Node : in Extension_Node_Type) return String; type Wildcard_Node_Type is new Route_Node_Type with null record; type Wildcard_Node_Access is access all Wildcard_Node_Type'Class; -- Check if the route node accepts the given extension. -- Returns WILDCARD_MATCH. overriding function Matches (Node : in Wildcard_Node_Type; Name : in String; Is_Last : in Boolean) return Route_Match_Type; -- Return the component path pattern that this route node represents (ie, *). overriding function Get_Pattern (Node : in Wildcard_Node_Type) return String; -- Describes a variable path component whose value must be injected in an Ada bean. type Route_Param_Type is limited record Route : Route_Node_Access; First : Natural := 0; Last : Natural := 0; end record; type Route_Param_Array is array (Positive range <>) of Route_Param_Type; MAX_ROUTE_PARAMS : constant Positive := 10; type Route_Context_Type is limited new Ada.Finalization.Limited_Controlled with record Route : Route_Type_Access; Path : String_Access; Params : Route_Param_Array (1 .. MAX_ROUTE_PARAMS); Count : Natural := 0; end record; -- Release the storage held by the route context. overriding procedure Finalize (Context : in out Route_Context_Type); type Router_Type is new Ada.Finalization.Limited_Controlled with record Route : aliased Path_Node_Type (Len => 0); end record; -- Release the storage held by the router. overriding procedure Finalize (Router : in out Router_Type); end ASF.Routes;
Declare the Get_Path_Info function
Declare the Get_Path_Info function
Ada
apache-2.0
stcarrez/ada-asf,stcarrez/ada-asf,stcarrez/ada-asf
84547a56368757af0bdfb71223505165ae3d0557
src/wiki-filters.ads
src/wiki-filters.ads
----------------------------------------------------------------------- -- wiki-filters -- Wiki filters -- 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 Ada.Finalization; with Wiki.Attributes; with Wiki.Documents; with Wiki.Nodes; with Wiki.Strings; -- == Filters == -- The <b>Wiki.Filters</b> package provides a simple filter framework that allows to plug -- specific filters when a wiki document is parsed and processed. The <tt>Filter_Type</tt> -- implements the <tt>Document_Reader</tt> interface to catch all the wiki document operations -- and it forwards the different calls to a next wiki document instance. A filter can do some -- operations while calls are made so that it can: -- -- * Get the text content and filter it by looking at forbidden words in some dictionary, -- * Ignore some formatting construct (for example to forbid the use of links), -- * Verify and do some corrections on HTML content embedded in wiki text, -- * Expand some plugins, specific links to complex content. -- -- To implement a new filter, the <tt>Filter_Type</tt> type must be used as a base type -- and some of the operations have to be overriden. The default <tt>Filter_Type</tt> operations -- just propagate the call to the attached wiki document instance (ie, a kind of pass -- through filter). -- package Wiki.Filters is pragma Preelaborate; use Ada.Strings.Wide_Wide_Unbounded; -- ------------------------------ -- Filter type -- ------------------------------ type Filter_Type is new Ada.Finalization.Limited_Controlled with private; type Filter_Type_Access is access all Filter_Type'Class; -- Add a simple node such as N_LINE_BREAK, N_HORIZONTAL_RULE or N_PARAGRAPH to the document. procedure Add_Node (Filter : in out Filter_Type; Document : in out Wiki.Nodes.Document; Kind : in Wiki.Nodes.Simple_Node_Kind); -- Add a text content with the given format to the document. procedure Add_Text (Filter : in out Filter_Type; Document : in out Wiki.Nodes.Document; Text : in Wiki.Strings.WString; Format : in Wiki.Nodes.Format_Map); -- Add a section header with the given level in the document. procedure Add_Header (Filter : in out Filter_Type; Document : in out Wiki.Nodes.Document; Header : in Wiki.Strings.WString; Level : in Natural); -- Push a HTML node with the given tag to the document. procedure Push_Node (Filter : in out Filter_Type; Document : in out Wiki.Nodes.Document; Tag : in Wiki.Nodes.Html_Tag_Type; Attributes : in out Wiki.Attributes.Attribute_List_Type); -- Pop a HTML node with the given tag. procedure Pop_Node (Filter : in out Filter_Type; Document : in out Wiki.Nodes.Document; Tag : in Wiki.Nodes.Html_Tag_Type); -- Add a section header in the document. procedure Add_Header (Document : in out Filter_Type; Header : in Unbounded_Wide_Wide_String; Level : in Positive); -- Add a blockquote (<blockquote>). The level indicates the blockquote nested level. -- The blockquote must be closed at the next header. procedure Add_Blockquote (Document : in out Filter_Type; Level : in Natural); -- 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 (Document : in out Filter_Type; Level : in Positive; Ordered : in Boolean); -- Add a link. procedure Add_Link (Document : in out Filter_Type; Name : in Unbounded_Wide_Wide_String; Link : in Unbounded_Wide_Wide_String; Language : in Unbounded_Wide_Wide_String; Title : in Unbounded_Wide_Wide_String); -- Add an image. procedure Add_Image (Document : in out Filter_Type; Link : in Unbounded_Wide_Wide_String; Alt : in Unbounded_Wide_Wide_String; Position : in Unbounded_Wide_Wide_String; Description : in Unbounded_Wide_Wide_String); -- Add a quote. procedure Add_Quote (Document : in out Filter_Type; Quote : in Unbounded_Wide_Wide_String; Link : in Unbounded_Wide_Wide_String; Language : in Unbounded_Wide_Wide_String); -- Add a text block with the given format. procedure Add_Text (Document : in out Filter_Type; Text : in Unbounded_Wide_Wide_String; Format : in Wiki.Documents.Format_Map); -- Add a text block that is pre-formatted. procedure Add_Preformatted (Document : in out Filter_Type; Text : in Unbounded_Wide_Wide_String; Format : in Unbounded_Wide_Wide_String); procedure Start_Element (Document : in out Filter_Type; Name : in Unbounded_Wide_Wide_String; Attributes : in Wiki.Attributes.Attribute_List_Type); procedure End_Element (Document : in out Filter_Type; Name : in Unbounded_Wide_Wide_String); -- Finish the document after complete wiki text has been parsed. procedure Finish (Document : in out Filter_Type); -- Set the document reader. procedure Set_Document (Filter : in out Filter_Type; Document : in Wiki.Documents.Document_Reader_Access); private type Filter_Type is new Ada.Finalization.Limited_Controlled with record Next : Filter_Type_Access; Document : Wiki.Documents.Document_Reader_Access; end record; end Wiki.Filters;
----------------------------------------------------------------------- -- wiki-filters -- Wiki filters -- 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 Ada.Finalization; with Wiki.Attributes; with Wiki.Documents; with Wiki.Nodes; with Wiki.Strings; -- == Filters == -- The <b>Wiki.Filters</b> package provides a simple filter framework that allows to plug -- specific filters when a wiki document is parsed and processed. The <tt>Filter_Type</tt> -- implements the <tt>Document_Reader</tt> interface to catch all the wiki document operations -- and it forwards the different calls to a next wiki document instance. A filter can do some -- operations while calls are made so that it can: -- -- * Get the text content and filter it by looking at forbidden words in some dictionary, -- * Ignore some formatting construct (for example to forbid the use of links), -- * Verify and do some corrections on HTML content embedded in wiki text, -- * Expand some plugins, specific links to complex content. -- -- To implement a new filter, the <tt>Filter_Type</tt> type must be used as a base type -- and some of the operations have to be overriden. The default <tt>Filter_Type</tt> operations -- just propagate the call to the attached wiki document instance (ie, a kind of pass -- through filter). -- package Wiki.Filters is pragma Preelaborate; use Ada.Strings.Wide_Wide_Unbounded; -- ------------------------------ -- Filter type -- ------------------------------ type Filter_Type is new Ada.Finalization.Limited_Controlled with private; type Filter_Type_Access is access all Filter_Type'Class; -- Add a simple node such as N_LINE_BREAK, N_HORIZONTAL_RULE or N_PARAGRAPH to the document. procedure Add_Node (Filter : in out Filter_Type; Document : in out Wiki.Nodes.Document; Kind : in Wiki.Nodes.Simple_Node_Kind); -- Add a text content with the given format to the document. procedure Add_Text (Filter : in out Filter_Type; Document : in out Wiki.Nodes.Document; Text : in Wiki.Strings.WString; Format : in Wiki.Nodes.Format_Map); -- Add a section header with the given level in the document. procedure Add_Header (Filter : in out Filter_Type; Document : in out Wiki.Nodes.Document; Header : in Wiki.Strings.WString; Level : in Natural); -- Push a HTML node with the given tag to the document. procedure Push_Node (Filter : in out Filter_Type; Document : in out Wiki.Nodes.Document; Tag : in Wiki.Nodes.Html_Tag_Type; Attributes : in out Wiki.Attributes.Attribute_List_Type); -- Pop a HTML node with the given tag. procedure Pop_Node (Filter : in out Filter_Type; Document : in out Wiki.Nodes.Document; Tag : in Wiki.Nodes.Html_Tag_Type); -- Add a section header in the document. procedure Add_Header (Document : in out Filter_Type; Header : in Unbounded_Wide_Wide_String; Level : in Positive); -- Add a blockquote (<blockquote>). The level indicates the blockquote nested level. -- The blockquote must be closed at the next header. procedure Add_Blockquote (Document : in out Filter_Type; Level : in Natural); -- 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 (Document : in out Filter_Type; Level : in Positive; Ordered : in Boolean); -- Add a link. procedure Add_Link (Document : in out Filter_Type; Name : in Unbounded_Wide_Wide_String; Link : in Unbounded_Wide_Wide_String; Language : in Unbounded_Wide_Wide_String; Title : in Unbounded_Wide_Wide_String); -- Add an image. procedure Add_Image (Document : in out Filter_Type; Link : in Unbounded_Wide_Wide_String; Alt : in Unbounded_Wide_Wide_String; Position : in Unbounded_Wide_Wide_String; Description : in Unbounded_Wide_Wide_String); -- Add a quote. procedure Add_Quote (Document : in out Filter_Type; Quote : in Unbounded_Wide_Wide_String; Link : in Unbounded_Wide_Wide_String; Language : in Unbounded_Wide_Wide_String); -- Add a text block with the given format. procedure Add_Text (Document : in out Filter_Type; Text : in Unbounded_Wide_Wide_String; Format : in Wiki.Documents.Format_Map); -- Add a text block that is pre-formatted. procedure Add_Preformatted (Document : in out Filter_Type; Text : in Unbounded_Wide_Wide_String; Format : in Unbounded_Wide_Wide_String); procedure Start_Element (Document : in out Filter_Type; Name : in Unbounded_Wide_Wide_String; Attributes : in Wiki.Attributes.Attribute_List_Type); procedure End_Element (Document : in out Filter_Type; Name : in Unbounded_Wide_Wide_String); -- Finish the document after complete wiki text has been parsed. procedure Finish (Document : in out Filter_Type); private type Filter_Type is new Ada.Finalization.Limited_Controlled with record Next : Filter_Type_Access; end record; end Wiki.Filters;
Remove the Set_Document procedure
Remove the Set_Document procedure
Ada
apache-2.0
stcarrez/ada-wiki,stcarrez/ada-wiki
a3cc5dfa2b9a0997594851c3d060ada56a71bb7e
src/wiki-nodes.adb
src/wiki-nodes.adb
----------------------------------------------------------------------- -- wiki-nodes -- Wiki Document Internal representation -- Copyright (C) 2016 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Unchecked_Deallocation; package body Wiki.Nodes is -- ------------------------------ -- Append a node to the tag node. -- ------------------------------ procedure Append (Into : in Node_Type_Access; Node : in Node_Type_Access) is begin if Into.Children = null then Into.Children := new Node_List; Into.Children.Current := Into.Children.First'Access; end if; Append (Into.Children.all, Node); end Append; -- ------------------------------ -- Append a node to the node list. -- ------------------------------ procedure Append (Into : in out Node_List; Node : in Node_Type_Access) is Block : Node_List_Block_Access := Into.Current; begin if Block.Last = Block.Max then Block.Next := new Node_List_Block (Into.Length); Block := Block.Next; Into.Current := Block; end if; Block.Last := Block.Last + 1; Block.List (Block.Last) := Node; Into.Length := Into.Length + 1; end Append; -- ------------------------------ -- Finalize the node list to release the allocated memory. -- ------------------------------ overriding procedure Finalize (List : in out Node_List) is procedure Free is new Ada.Unchecked_Deallocation (Node_List_Block, Node_List_Block_Access); procedure Free is new Ada.Unchecked_Deallocation (Node_Type, Node_Type_Access); procedure Free is new Ada.Unchecked_Deallocation (Node_List, Node_List_Access); procedure Release (List : in Node_List_Block_Access); procedure Free_Block (Block : in out Node_List_Block) is begin for I in 1 .. Block.Last loop if Block.List (I).Kind = N_TAG_START and then Block.List (I).Children /= null then Finalize (Block.List (I).Children.all); Free (Block.List (I).Children); end if; Free (Block.List (I)); end loop; end Free_Block; procedure Release (List : in Node_List_Block_Access) is Next : Node_List_Block_Access := List; Block : Node_List_Block_Access; begin while Next /= null loop Block := Next; Free_Block (Block.all); Next := Next.Next; Free (Block); end loop; end Release; begin Release (List.First.Next); Free_Block (List.First); end Finalize; -- ------------------------------ -- 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)) is Block : Node_List_Block_Access := List.First'Access; begin loop for I in 1 .. Block.Last loop Process (Block.List (I).all); end loop; Block := Block.Next; exit when Block = null; end loop; end Iterate; -- ------------------------------ -- Append a node to the node list. -- ------------------------------ procedure Append (Into : in out Node_List_Ref; Node : in Node_Type_Access) is begin if Into.Is_Null then Node_List_Refs.Ref (Into) := Node_List_Refs.Create; Into.Value.Current := Into.Value.First'Access; end if; Append (Into.Value.all, Node); end Append; -- ------------------------------ -- Iterate over the nodes of the list and call the <tt>Process</tt> procedure with -- each node instance. -- ------------------------------ procedure Iterate (List : in Node_List_Ref; Process : not null access procedure (Node : in Node_Type)) is begin if not List.Is_Null then Iterate (List.Value, Process); end if; end Iterate; -- ------------------------------ -- Returns True if the list reference is empty. -- ------------------------------ function Is_Empty (List : in Node_List_Ref) return Boolean is begin return List.Is_Null; end Is_Empty; -- ------------------------------ -- Get the number of nodes in the list. -- ------------------------------ function Length (List : in Node_List_Ref) return Natural is begin if List.Is_Null then return 0; else return List.Value.Length; end if; end Length; end Wiki.Nodes;
----------------------------------------------------------------------- -- wiki-nodes -- Wiki Document Internal representation -- Copyright (C) 2016 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Unchecked_Deallocation; package body Wiki.Nodes is -- ------------------------------ -- Append a node to the tag node. -- ------------------------------ procedure Append (Into : in Node_Type_Access; Node : in Node_Type_Access) is begin if Into.Children = null then Into.Children := new Node_List; Into.Children.Current := Into.Children.First'Access; end if; Append (Into.Children.all, Node); end Append; -- ------------------------------ -- Append a node to the node list. -- ------------------------------ procedure Append (Into : in out Node_List; Node : in Node_Type_Access) is Block : Node_List_Block_Access := Into.Current; begin if Block.Last = Block.Max then Block.Next := new Node_List_Block (Into.Length); Block := Block.Next; Into.Current := Block; end if; Block.Last := Block.Last + 1; Block.List (Block.Last) := Node; Into.Length := Into.Length + 1; end Append; -- ------------------------------ -- Finalize the node list to release the allocated memory. -- ------------------------------ overriding procedure Finalize (List : in out Node_List) is procedure Free is new Ada.Unchecked_Deallocation (Node_List_Block, Node_List_Block_Access); procedure Free is new Ada.Unchecked_Deallocation (Node_Type, Node_Type_Access); procedure Free is new Ada.Unchecked_Deallocation (Node_List, Node_List_Access); procedure Release (List : in Node_List_Block_Access); procedure Free_Block (Block : in out Node_List_Block); procedure Free_Block (Block : in out Node_List_Block) is begin for I in 1 .. Block.Last loop if Block.List (I).Kind = N_TAG_START and then Block.List (I).Children /= null then Finalize (Block.List (I).Children.all); Free (Block.List (I).Children); end if; Free (Block.List (I)); end loop; end Free_Block; procedure Release (List : in Node_List_Block_Access) is Next : Node_List_Block_Access := List; Block : Node_List_Block_Access; begin while Next /= null loop Block := Next; Free_Block (Block.all); Next := Next.Next; Free (Block); end loop; end Release; begin Release (List.First.Next); Free_Block (List.First); end Finalize; -- ------------------------------ -- 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)) is Block : Node_List_Block_Access := List.First'Access; begin loop for I in 1 .. Block.Last loop Process (Block.List (I).all); end loop; Block := Block.Next; exit when Block = null; end loop; end Iterate; -- ------------------------------ -- Append a node to the node list. -- ------------------------------ procedure Append (Into : in out Node_List_Ref; Node : in Node_Type_Access) is begin if Into.Is_Null then Node_List_Refs.Ref (Into) := Node_List_Refs.Create; Into.Value.Current := Into.Value.First'Access; end if; Append (Into.Value.all, Node); end Append; -- ------------------------------ -- Iterate over the nodes of the list and call the <tt>Process</tt> procedure with -- each node instance. -- ------------------------------ procedure Iterate (List : in Node_List_Ref; Process : not null access procedure (Node : in Node_Type)) is begin if not List.Is_Null then Iterate (List.Value, Process); end if; end Iterate; -- ------------------------------ -- Returns True if the list reference is empty. -- ------------------------------ function Is_Empty (List : in Node_List_Ref) return Boolean is begin return List.Is_Null; end Is_Empty; -- ------------------------------ -- Get the number of nodes in the list. -- ------------------------------ function Length (List : in Node_List_Ref) return Natural is begin if List.Is_Null then return 0; else return List.Value.Length; end if; end Length; end Wiki.Nodes;
Fix compilation warning
Fix compilation warning
Ada
apache-2.0
stcarrez/ada-wiki,stcarrez/ada-wiki
cbf490ecb1a8cfd8da15cd1a205b1dd84083b84e
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.Strings; with Ada.Finalization; 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 new Ada.Finalization.Limited_Controlled with record Nodes : Node_List; Current : Node_Type_Access; end record; overriding procedure Initialize (Doc : in out Document); 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; with Ada.Finalization; 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)); -- Iterate over the nodes of the list and call the <tt>Process</tt> procedure with -- each node instance. procedure Iterate (Doc : in Document; 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 new Ada.Finalization.Limited_Controlled with record Nodes : Node_List; Current : Node_Type_Access; end record; overriding procedure Initialize (Doc : in out Document); end Wiki.Nodes;
Declare the Iterate procedure on a Document object
Declare the Iterate procedure on a Document object
Ada
apache-2.0
stcarrez/ada-wiki,stcarrez/ada-wiki
f008606a3588be017095f8e0c0f84d6f3fad92ee
matp/src/mat-expressions.ads
matp/src/mat-expressions.ads
----------------------------------------------------------------------- -- 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.Strings.Unbounded; with Ada.Finalization; private with Util.Concurrent.Counters; with MAT.Types; with MAT.Memory; with MAT.Events.Targets; package MAT.Expressions is type Context_Type is record Addr : MAT.Types.Target_Addr; Allocation : MAT.Memory.Allocation; end record; type Inside_Type is (INSIDE_FILE, INSIDE_DIRECT_FILE, INSIDE_FUNCTION, INSIDE_DIRECT_FUNCTION); type Expression_Type is tagged private; -- Create a NOT expression node. function Create_Not (Expr : in Expression_Type) return Expression_Type; -- Create a AND expression node. function Create_And (Left : in Expression_Type; Right : in Expression_Type) return Expression_Type; -- Create a OR expression node. function Create_Or (Left : in Expression_Type; Right : in Expression_Type) return Expression_Type; -- Create an INSIDE expression node. function Create_Inside (Name : in Ada.Strings.Unbounded.Unbounded_String; Kind : in Inside_Type) return Expression_Type; -- Create an size range expression node. function Create_Size (Min : in MAT.Types.Target_Size; Max : in MAT.Types.Target_Size) return Expression_Type; -- Create an addr range expression node. function Create_Addr (Min : in MAT.Types.Target_Addr; Max : in MAT.Types.Target_Addr) return Expression_Type; -- 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; -- 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; -- 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; -- Create a event type expression check. function Create_Event_Type (Event_Kind : in MAT.Events.Targets.Probe_Index_Type) return Expression_Type; -- Create an expression node to keep allocation events which don't have any associated free. function Create_No_Free 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; Addr : in MAT.Types.Target_Addr; Allocation : in MAT.Memory.Allocation) return Boolean; -- 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; -- Parse the string and return the expression tree. function Parse (Expr : in String) return Expression_Type; -- Empty expression. EMPTY : constant Expression_Type; type yystype is record low : MAT.Types.Uint64 := 0; high : MAT.Types.Uint64 := 0; bval : Boolean := False; name : Ada.Strings.Unbounded.Unbounded_String; expr : Expression_Type; end record; private type Kind_Type is (N_NOT, N_OR, N_AND, N_TRUE, N_FALSE, N_IN_FILE, N_IN_FILE_DIRECT, N_INSIDE, N_CALL_ADDR, N_CALL_ADDR_DIRECT, N_IN_FUNC, N_IN_FUNC_DIRECT, N_RANGE_SIZE, N_RANGE_ADDR, N_RANGE_TIME, N_EVENT, N_HAS_ADDR, N_CONDITION, N_THREAD, N_TYPE, N_NO_FREE); 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_INSIDE | N_IN_FILE | N_IN_FILE_DIRECT | N_IN_FUNC | N_IN_FUNC_DIRECT => Name : Ada.Strings.Unbounded.Unbounded_String; Inside : Inside_Type; 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 | N_HAS_ADDR => Min_Addr : MAT.Types.Target_Addr; Max_Addr : MAT.Types.Target_Addr; when N_RANGE_TIME => Min_Time : MAT.Types.Target_Tick_Ref; Max_Time : MAT.Types.Target_Tick_Ref; when N_THREAD => Min_Thread : MAT.Types.Target_Thread_Ref; Max_Thread : MAT.Types.Target_Thread_Ref; when N_EVENT => Min_Event : MAT.Events.Targets.Event_Id_Type; Max_Event : MAT.Events.Targets.Event_Id_Type; when N_TYPE => Event_Kind : MAT.Events.Targets.Probe_Index_Type; when others => null; end case; end record; -- 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; -- 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; type Expression_Type is new Ada.Finalization.Controlled with record Node : Node_Type_Access; end record; -- Release the reference and destroy the expression tree if it was the last reference. overriding procedure Finalize (Obj : in out Expression_Type); -- Update the reference after an assignment. overriding procedure Adjust (Obj : in out Expression_Type); -- Empty expression. EMPTY : constant Expression_Type := Expression_Type'(Ada.Finalization.Controlled with Node => null); 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.Strings.Unbounded; with Ada.Finalization; private with Util.Concurrent.Counters; with MAT.Types; with MAT.Memory; with MAT.Events.Targets; package MAT.Expressions is type Context_Type is record Addr : MAT.Types.Target_Addr; Allocation : MAT.Memory.Allocation; end record; type Inside_Type is (INSIDE_FILE, INSIDE_DIRECT_FILE, INSIDE_FUNCTION, INSIDE_DIRECT_FUNCTION); type Expression_Type is tagged private; -- Create a NOT expression node. function Create_Not (Expr : in Expression_Type) return Expression_Type; -- Create a AND expression node. function Create_And (Left : in Expression_Type; Right : in Expression_Type) return Expression_Type; -- Create a OR expression node. function Create_Or (Left : in Expression_Type; Right : in Expression_Type) return Expression_Type; -- Create an INSIDE expression node. function Create_Inside (Name : in Ada.Strings.Unbounded.Unbounded_String; Kind : in Inside_Type) return Expression_Type; -- Create an size range expression node. function Create_Size (Min : in MAT.Types.Target_Size; Max : in MAT.Types.Target_Size) return Expression_Type; -- Create an addr range expression node. function Create_Addr (Min : in MAT.Types.Target_Addr; Max : in MAT.Types.Target_Addr) return Expression_Type; -- 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; -- 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; -- 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; -- Create a event type expression check. function Create_Event_Type (Event_Kind : in MAT.Events.Targets.Probe_Index_Type) return Expression_Type; -- Create an expression node to keep allocation events which don't have any associated free. function Create_No_Free 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; Addr : in MAT.Types.Target_Addr; Allocation : in MAT.Memory.Allocation) return Boolean; -- 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; -- Parse the string and return the expression tree. function Parse (Expr : in String) return Expression_Type; -- Empty expression. EMPTY : constant Expression_Type; type yystype is record low : MAT.Types.Uint64 := 0; high : MAT.Types.Uint64 := 0; bval : Boolean := False; name : Ada.Strings.Unbounded.Unbounded_String; expr : Expression_Type; end record; private type Kind_Type is (N_NOT, N_OR, N_AND, N_TRUE, N_FALSE, N_IN_FILE, N_IN_FILE_DIRECT, N_INSIDE, N_CALL_ADDR, N_CALL_ADDR_DIRECT, N_IN_FUNC, N_IN_FUNC_DIRECT, N_RANGE_SIZE, N_RANGE_ADDR, N_RANGE_TIME, N_EVENT, N_HAS_ADDR, N_CONDITION, N_THREAD, N_TYPE, N_NO_FREE); 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_INSIDE | N_IN_FILE | N_IN_FILE_DIRECT | N_IN_FUNC_DIRECT => Name : Ada.Strings.Unbounded.Unbounded_String; Inside : Inside_Type; 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 | N_HAS_ADDR | N_IN_FUNC => Min_Addr : MAT.Types.Target_Addr; Max_Addr : MAT.Types.Target_Addr; when N_RANGE_TIME => Min_Time : MAT.Types.Target_Tick_Ref; Max_Time : MAT.Types.Target_Tick_Ref; when N_THREAD => Min_Thread : MAT.Types.Target_Thread_Ref; Max_Thread : MAT.Types.Target_Thread_Ref; when N_EVENT => Min_Event : MAT.Events.Targets.Event_Id_Type; Max_Event : MAT.Events.Targets.Event_Id_Type; when N_TYPE => Event_Kind : MAT.Events.Targets.Probe_Index_Type; when others => null; end case; end record; -- 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; -- 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; type Expression_Type is new Ada.Finalization.Controlled with record Node : Node_Type_Access; end record; -- Release the reference and destroy the expression tree if it was the last reference. overriding procedure Finalize (Obj : in out Expression_Type); -- Update the reference after an assignment. overriding procedure Adjust (Obj : in out Expression_Type); -- Empty expression. EMPTY : constant Expression_Type := Expression_Type'(Ada.Finalization.Controlled with Node => null); end MAT.Expressions;
Change N_IN_FUNC to use the Min_Addr and Max_Addr and define the function boundaries to check
Change N_IN_FUNC to use the Min_Addr and Max_Addr and define the function boundaries to check
Ada
apache-2.0
stcarrez/mat,stcarrez/mat,stcarrez/mat
664ee7562cad57e40b54604c2e8832e5f581a9bc
boards/stm32f7_discovery/hal-audio.adb
boards/stm32f7_discovery/hal-audio.adb
with Interfaces.Bit_Types; use Interfaces.Bit_Types; with STM32_SVD.RCC; use STM32_SVD.RCC; with STM32_SVD.SAI; use STM32_SVD.SAI; with STM32.Device; use STM32.Device; with STM32.Board; use STM32.Board; with STM32.GPIO; use STM32.GPIO; with STM32.DMA; use STM32.DMA; with STM32.I2C; use STM32.I2C; with STM32.SAI; use STM32.SAI; with WM8994; use WM8994; package body HAL.Audio is procedure Set_Audio_Clock (Freq : Audio_Frequency); procedure Initialize_Pins; procedure Initialize_SAI_Out (Freq : Audio_Frequency); procedure Initialize_Audio_I2C; -- Communication with the Audio chip Audio_I2C_Addr : constant I2C_Address := 16#34#; Driver : WM8994_Device (Port => Audio_I2C'Access, I2C_Addr => Audio_I2C_Addr); -- AUDIO OUT SAI_Out : SAI_Controller renames SAI_2; SAI_Out_Block : SAI_Block renames Block_A; DMA_Out : STM32.DMA.DMA_Controller renames DMA_2; DMA_Out_Stream : DMA_Stream_Selector renames Stream_4; DMA_Out_Channel : DMA_Channel_Selector renames Channel_3; -- AUDIO IN -- SAI_In : SAI_Controller renames SAI_2; -- SAI_In_Block : SAI_Block renames Block_B; -- DMA_In : STM32.DMA.DMA_Controller renames DMA_2; -- DMA_In_Sream : DMA_Stream_Selector renames Stream_7; -- DMA_In_Channel : DMA_Channel_Selector renames Channel_0; -------------------- -- DMA_Out_Status -- -------------------- function DMA_Out_Status (Flag : STM32.DMA.DMA_Status_Flag) return Boolean is begin return STM32.DMA.Status (DMA_Out, DMA_Out_Stream, Flag); end DMA_Out_Status; -------------------------- -- DMA_Out_Clear_Status -- -------------------------- procedure DMA_Out_Clear_Status (Flag : STM32.DMA.DMA_Status_Flag) is begin STM32.DMA.Clear_Status (DMA_Out, DMA_Out_Stream, Flag); end DMA_Out_Clear_Status; --------------------- -- Set_Audio_Clock -- --------------------- procedure Set_Audio_Clock (Freq : Audio_Frequency) is begin -- Two groups of frequencies: the 44kHz family and the 48kHz family -- The Actual audio frequency is calculated then with the following -- formula: -- Master_Clock = 256 * FS = SAI_CK / Master_Clock_Divider -- We need to find a value of SAI_CK that allows such integer master -- clock divider case Freq is when Audio_Freq_11kHz | Audio_Freq_22kHz | Audio_Freq_44kHz => -- HSE/PLLM = 1MHz = PLLI2S VCO Input Configure_SAI_I2S_Clock (SAI_Out, PLLI2SN => 429, -- VCO Output = 429MHz PLLI2SQ => 2, -- SAI Clk(First level) = 214.5 MHz PLLI2SDIVQ => 19); -- I2S Clk = 215.4 / 19 = 11.289 MHz when Audio_Freq_8kHz | Audio_Freq_16kHz | Audio_Freq_48kHz | Audio_Freq_96kHz => Configure_SAI_I2S_Clock (SAI_Out, PLLI2SN => 344, -- VCO Output = 344MHz PLLI2SQ => 7, -- SAI Clk(First level) = 49.142 MHz PLLI2SDIVQ => 1); -- I2S Clk = 49.142 MHz end case; end Set_Audio_Clock; --------------------- -- Initialize_Pins -- --------------------- procedure Initialize_Pins is SAI_Pins : constant GPIO_Points := (SAI2_MCLK_A, SAI2_FS_A, SAI2_SD_A, SAI2_SCK_A); begin Enable_Clock (SAI_2); Enable_Clock (SAI_Pins); Configure_IO (SAI_Pins, (Mode => Mode_AF, Output_Type => Push_Pull, Speed => Speed_High, Resistors => Floating)); Configure_Alternate_Function (SAI_Pins, GPIO_AF_SAI2); Enable_Clock (DMA_Out); -- Configure the DMA channel to the SAI peripheral Disable (DMA_Out, DMA_Out_Stream); Configure (DMA_Out, DMA_Out_Stream, (Channel => DMA_Out_Channel, Direction => Memory_To_Peripheral, Increment_Peripheral_Address => False, Increment_Memory_Address => True, Peripheral_Data_Format => HalfWords, Memory_Data_Format => HalfWords, Operation_Mode => Circular_Mode, Priority => Priority_High, FIFO_Enabled => True, FIFO_Threshold => FIFO_Threshold_Full_Configuration, Memory_Burst_Size => Memory_Burst_Single, Peripheral_Burst_Size => Peripheral_Burst_Single)); Clear_All_Status (DMA_Out, DMA_Out_Stream); end Initialize_Pins; ------------------------ -- Initialize_SAI_Out -- ------------------------ procedure Initialize_SAI_Out (Freq : Audio_Frequency) is begin STM32.SAI.Disable (SAI_Out, SAI_Out_Block); STM32.SAI.Configure_Audio_Block (SAI_Out, SAI_Out_Block, Frequency => Audio_Frequency'Enum_Rep (Freq), Stereo_Mode => Stereo, Mode => Master_Transmitter, MCD_Enabled => True, Protocol => Free_Protocol, Data_Size => Data_16b, Endianness => Data_MSB_First, Clock_Strobing => Clock_Strobing_Rising_Edge, Synchronization => Asynchronous_Mode, Output_Drive => Drive_Immediate, FIFO_Threshold => FIFO_1_Quarter_Full); STM32.SAI.Configure_Block_Frame (SAI_Out, SAI_Out_Block, Frame_Length => 64, Frame_Active => 32, Frame_Sync => FS_Frame_And_Channel_Identification, FS_Polarity => FS_Active_Low, FS_Offset => Before_First_Bit); STM32.SAI.Configure_Block_Slot (SAI_Out, SAI_Out_Block, First_Bit_Offset => 0, Slot_Size => Data_Size, Number_Of_Slots => 4, Enabled_Slots => Slot_0 or Slot_2); STM32.SAI.Enable (SAI_Out, SAI_Out_Block); end Initialize_SAI_Out; -------------------------- -- Initialize_Audio_I2C -- -------------------------- procedure Initialize_Audio_I2C is begin Initialize_I2C_GPIO (Audio_I2C); Configure_I2C (Audio_I2C); end Initialize_Audio_I2C; ---------------- -- Initialize -- ---------------- procedure Initialize_Audio_Out (Volume : Audio_Volume; Frequency : Audio_Frequency) is begin STM32.SAI.Deinitialize (SAI_Out, SAI_Out_Block); Set_Audio_Clock (Frequency); -- Initialize the SAI Initialize_Pins; Initialize_SAI_Out (Frequency); -- Initialize the I2C Port to send commands to the driver Initialize_Audio_I2C; if Driver.Read_ID /= WM8994.WM8994_ID then raise Constraint_Error with "Invalid ID received from the Audio Code"; end if; Driver.Reset; Driver.Init (Input => WM8994.No_Input, Output => WM8994.Auto, Volume => Byte (Volume), Frequency => WM8994.Audio_Frequency'Enum_Val (Audio_Frequency'Enum_Rep (Frequency))); end Initialize_Audio_Out; ---------- -- Play -- ---------- procedure Play (Buffer : Audio_Buffer) is begin Driver.Play; Start_Transfer_with_Interrupts (Unit => DMA_Out, Stream => DMA_Out_Stream, Source => Buffer (Buffer'First)'Address, Destination => SAI_Out.ADR'Address, Data_Count => Buffer'Length, Enabled_Interrupts => (Half_Transfer_Complete_Interrupt => True, Transfer_Complete_Interrupt => True, others => False)); Enable_DMA (SAI_Out, SAI_Out_Block); if not Enabled (SAI_Out, SAI_Out_Block) then Enable (SAI_Out, SAI_Out_Block); end if; end Play; ------------------- -- Change_Buffer -- ------------------- procedure Change_Buffer (Buffer : Audio_Buffer) is begin null; end Change_Buffer; ----------- -- Pause -- ----------- procedure Pause is begin Driver.Pause; STM32.DMA.Disable (DMA_Out, DMA_Out_Stream); end Pause; procedure Resume is begin null; end Resume; procedure Stop is begin null; end Stop; ---------------- -- Set_Volume -- ---------------- procedure Set_Volume (Volume : Audio_Volume) is begin Driver.Set_Volume (Byte (Volume)); end Set_Volume; ------------------- -- Set_Frequency -- ------------------- procedure Set_Frequency (Frequency : Audio_Frequency) is begin Set_Audio_Clock (Frequency); STM32.SAI.Disable (SAI_Out, SAI_Out_Block); Initialize_SAI_Out (Frequency); STM32.SAI.Enable (SAI_Out, SAI_Out_Block); end Set_Frequency; end HAL.Audio;
with STM32_SVD.RCC; use STM32_SVD.RCC; with STM32_SVD.SAI; use STM32_SVD.SAI; with STM32.Device; use STM32.Device; with STM32.Board; use STM32.Board; with STM32.GPIO; use STM32.GPIO; with STM32.DMA; use STM32.DMA; with STM32.I2C; use STM32.I2C; with STM32.SAI; use STM32.SAI; with WM8994; use WM8994; package body HAL.Audio is procedure Set_Audio_Clock (Freq : Audio_Frequency); procedure Initialize_Pins; procedure Initialize_SAI_Out (Freq : Audio_Frequency); procedure Initialize_Audio_I2C; -- Communication with the Audio chip Audio_I2C_Addr : constant I2C_Address := 16#34#; Driver : WM8994_Device (Port => Audio_I2C'Access, I2C_Addr => Audio_I2C_Addr); -- AUDIO OUT SAI_Out : SAI_Controller renames SAI_2; SAI_Out_Block : SAI_Block renames Block_A; DMA_Out : STM32.DMA.DMA_Controller renames DMA_2; DMA_Out_Stream : DMA_Stream_Selector renames Stream_4; DMA_Out_Channel : DMA_Channel_Selector renames Channel_3; -- AUDIO IN -- SAI_In : SAI_Controller renames SAI_2; -- SAI_In_Block : SAI_Block renames Block_B; -- DMA_In : STM32.DMA.DMA_Controller renames DMA_2; -- DMA_In_Sream : DMA_Stream_Selector renames Stream_7; -- DMA_In_Channel : DMA_Channel_Selector renames Channel_0; -------------------- -- DMA_Out_Status -- -------------------- function DMA_Out_Status (Flag : STM32.DMA.DMA_Status_Flag) return Boolean is begin return STM32.DMA.Status (DMA_Out, DMA_Out_Stream, Flag); end DMA_Out_Status; -------------------------- -- DMA_Out_Clear_Status -- -------------------------- procedure DMA_Out_Clear_Status (Flag : STM32.DMA.DMA_Status_Flag) is begin STM32.DMA.Clear_Status (DMA_Out, DMA_Out_Stream, Flag); end DMA_Out_Clear_Status; --------------------- -- Set_Audio_Clock -- --------------------- procedure Set_Audio_Clock (Freq : Audio_Frequency) is begin -- Two groups of frequencies: the 44kHz family and the 48kHz family -- The Actual audio frequency is calculated then with the following -- formula: -- Master_Clock = 256 * FS = SAI_CK / Master_Clock_Divider -- We need to find a value of SAI_CK that allows such integer master -- clock divider case Freq is when Audio_Freq_11kHz | Audio_Freq_22kHz | Audio_Freq_44kHz => -- HSE/PLLM = 1MHz = PLLI2S VCO Input Configure_SAI_I2S_Clock (SAI_Out, PLLI2SN => 429, -- VCO Output = 429MHz PLLI2SQ => 2, -- SAI Clk(First level) = 214.5 MHz PLLI2SDIVQ => 19); -- I2S Clk = 215.4 / 19 = 11.289 MHz when Audio_Freq_8kHz | Audio_Freq_16kHz | Audio_Freq_48kHz | Audio_Freq_96kHz => Configure_SAI_I2S_Clock (SAI_Out, PLLI2SN => 344, -- VCO Output = 344MHz PLLI2SQ => 7, -- SAI Clk(First level) = 49.142 MHz PLLI2SDIVQ => 1); -- I2S Clk = 49.142 MHz end case; end Set_Audio_Clock; --------------------- -- Initialize_Pins -- --------------------- procedure Initialize_Pins is SAI_Pins : constant GPIO_Points := (SAI2_MCLK_A, SAI2_FS_A, SAI2_SD_A, SAI2_SCK_A); begin Enable_Clock (SAI_2); Enable_Clock (SAI_Pins); Configure_IO (SAI_Pins, (Mode => Mode_AF, Output_Type => Push_Pull, Speed => Speed_High, Resistors => Floating)); Configure_Alternate_Function (SAI_Pins, GPIO_AF_SAI2); Enable_Clock (DMA_Out); -- Configure the DMA channel to the SAI peripheral Disable (DMA_Out, DMA_Out_Stream); Configure (DMA_Out, DMA_Out_Stream, (Channel => DMA_Out_Channel, Direction => Memory_To_Peripheral, Increment_Peripheral_Address => False, Increment_Memory_Address => True, Peripheral_Data_Format => HalfWords, Memory_Data_Format => HalfWords, Operation_Mode => Circular_Mode, Priority => Priority_High, FIFO_Enabled => True, FIFO_Threshold => FIFO_Threshold_Full_Configuration, Memory_Burst_Size => Memory_Burst_Single, Peripheral_Burst_Size => Peripheral_Burst_Single)); Clear_All_Status (DMA_Out, DMA_Out_Stream); end Initialize_Pins; ------------------------ -- Initialize_SAI_Out -- ------------------------ procedure Initialize_SAI_Out (Freq : Audio_Frequency) is begin STM32.SAI.Disable (SAI_Out, SAI_Out_Block); STM32.SAI.Configure_Audio_Block (SAI_Out, SAI_Out_Block, Frequency => Audio_Frequency'Enum_Rep (Freq), Stereo_Mode => Stereo, Mode => Master_Transmitter, MCD_Enabled => True, Protocol => Free_Protocol, Data_Size => Data_16b, Endianness => Data_MSB_First, Clock_Strobing => Clock_Strobing_Rising_Edge, Synchronization => Asynchronous_Mode, Output_Drive => Drive_Immediate, FIFO_Threshold => FIFO_1_Quarter_Full); STM32.SAI.Configure_Block_Frame (SAI_Out, SAI_Out_Block, Frame_Length => 64, Frame_Active => 32, Frame_Sync => FS_Frame_And_Channel_Identification, FS_Polarity => FS_Active_Low, FS_Offset => Before_First_Bit); STM32.SAI.Configure_Block_Slot (SAI_Out, SAI_Out_Block, First_Bit_Offset => 0, Slot_Size => Data_Size, Number_Of_Slots => 4, Enabled_Slots => Slot_0 or Slot_2); STM32.SAI.Enable (SAI_Out, SAI_Out_Block); end Initialize_SAI_Out; -------------------------- -- Initialize_Audio_I2C -- -------------------------- procedure Initialize_Audio_I2C is begin Initialize_I2C_GPIO (Audio_I2C); Configure_I2C (Audio_I2C); end Initialize_Audio_I2C; ---------------- -- Initialize -- ---------------- procedure Initialize_Audio_Out (Volume : Audio_Volume; Frequency : Audio_Frequency) is begin STM32.SAI.Deinitialize (SAI_Out, SAI_Out_Block); Set_Audio_Clock (Frequency); -- Initialize the SAI Initialize_Pins; Initialize_SAI_Out (Frequency); -- Initialize the I2C Port to send commands to the driver Initialize_Audio_I2C; if Driver.Read_ID /= WM8994.WM8994_ID then raise Constraint_Error with "Invalid ID received from the Audio Code"; end if; Driver.Reset; Driver.Init (Input => WM8994.No_Input, Output => WM8994.Auto, Volume => Byte (Volume), Frequency => WM8994.Audio_Frequency'Enum_Val (Audio_Frequency'Enum_Rep (Frequency))); end Initialize_Audio_Out; ---------- -- Play -- ---------- procedure Play (Buffer : Audio_Buffer) is begin Driver.Play; Start_Transfer_with_Interrupts (Unit => DMA_Out, Stream => DMA_Out_Stream, Source => Buffer (Buffer'First)'Address, Destination => SAI_Out.ADR'Address, Data_Count => Buffer'Length, Enabled_Interrupts => (Half_Transfer_Complete_Interrupt => True, Transfer_Complete_Interrupt => True, others => False)); Enable_DMA (SAI_Out, SAI_Out_Block); if not Enabled (SAI_Out, SAI_Out_Block) then Enable (SAI_Out, SAI_Out_Block); end if; end Play; ------------------- -- Change_Buffer -- ------------------- procedure Change_Buffer (Buffer : Audio_Buffer) is begin null; end Change_Buffer; ----------- -- Pause -- ----------- procedure Pause is begin Driver.Pause; STM32.DMA.Disable (DMA_Out, DMA_Out_Stream); end Pause; procedure Resume is begin null; end Resume; procedure Stop is begin null; end Stop; ---------------- -- Set_Volume -- ---------------- procedure Set_Volume (Volume : Audio_Volume) is begin Driver.Set_Volume (Byte (Volume)); end Set_Volume; ------------------- -- Set_Frequency -- ------------------- procedure Set_Frequency (Frequency : Audio_Frequency) is begin Set_Audio_Clock (Frequency); STM32.SAI.Disable (SAI_Out, SAI_Out_Block); Initialize_SAI_Out (Frequency); STM32.SAI.Enable (SAI_Out, SAI_Out_Block); end Set_Frequency; end HAL.Audio;
Fix compile error in stm32f6 "hal-audio.adb"
Fix compile error in stm32f6 "hal-audio.adb"
Ada
bsd-3-clause
simonjwright/Ada_Drivers_Library,Fabien-Chouteau/Ada_Drivers_Library,AdaCore/Ada_Drivers_Library,AdaCore/Ada_Drivers_Library,Fabien-Chouteau/Ada_Drivers_Library,simonjwright/Ada_Drivers_Library,lambourg/Ada_Drivers_Library,ellamosi/Ada_BMP_Library
c7064977f6b9c9768f9680a86d63f6205505aa9a
regtests/asf-applications-tests.adb
regtests/asf-applications-tests.adb
----------------------------------------------------------------------- -- 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.Test_Caller; with ASF.Tests; with ASF.Events.Actions; with ASF.Requests.Mockup; with ASF.Responses.Mockup; with ASF.Applications.Main; package body ASF.Applications.Tests is use ASF.Tests; use Util.Tests; package Caller is new Util.Test_Caller (Test); procedure Add_Tests (Suite : AUnit.Test_Suites.Access_Test_Suite) is begin Caller.Add_Test (Suite, "Test service HTTP invalid method", Test_Invalid_Request'Access); Caller.Add_Test (Suite, "Test service HTTP GET (File_Servlet)", Test_Get_File'Access); Caller.Add_Test (Suite, "Test service HTTP GET 404", Test_Get_404'Access); Caller.Add_Test (Suite, "Test service HTTP GET (Measure_Servlet)", Test_Get_Measures'Access); Caller.Add_Test (Suite, "Test service HTTP POST+INVOKE_APPLICATION", Test_Form_Post'Access); Caller.Add_Test (Suite, "Test service HTTP POST+PROCESS_VALIDATION", Test_Form_Post_Validation_Error'Access); end Add_Tests; package Save_Binding is new ASF.Events.Actions.Action_Method.Bind (Bean => Form_Bean, Method => Save, Name => "save"); Binding_Array : aliased constant Util.Beans.Methods.Method_Binding_Array := (Save_Binding.Proxy'Access, Save_Binding.Proxy'Access); -- ------------------------------ -- Get the value identified by the name. -- ------------------------------ overriding function Get_Value (From : in Form_Bean; Name : in String) return Util.Beans.Objects.Object is begin if Name = "email" then return Util.Beans.Objects.To_Object (From.Email); elsif Name = "password" then return Util.Beans.Objects.To_Object (From.Password); elsif Name = "name" then return Util.Beans.Objects.To_Object (From.Name); else return Util.Beans.Objects.Null_Object; end if; end Get_Value; -- ------------------------------ -- 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) is begin if Name = "email" then From.Email := Util.Beans.Objects.To_Unbounded_String (Value); elsif Name = "password" then From.Password := Util.Beans.Objects.To_Unbounded_String (Value); elsif Name = "name" then From.Name := Util.Beans.Objects.To_Unbounded_String (Value); end if; end Set_Value; -- ------------------------------ -- 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 is pragma Unreferenced (From); begin return Binding_Array'Access; end Get_Method_Bindings; -- ------------------------------ -- Initialize the test application -- ------------------------------ overriding procedure Set_Up (T : in out Test) is pragma Unreferenced (T); use type ASF.Applications.Main.Application_Access; begin if ASF.Tests.Get_Application = null then ASF.Tests.Initialize (Util.Tests.Get_Properties); end if; end Set_Up; -- ------------------------------ -- Action to authenticate a user (password authentication). -- ------------------------------ procedure Save (Data : in out Form_Bean; Outcome : in out Unbounded_String) is begin Outcome := To_Unbounded_String ("success"); end Save; -- ------------------------------ -- Test an invalid HTTP request. -- ------------------------------ procedure Test_Invalid_Request (T : in out Test) is Request : ASF.Requests.Mockup.Request; Reply : ASF.Responses.Mockup.Response; begin -- Unknown method Request.Set_Method ("BLAB"); Request.Set_Request_URI ("/asfunit/views/set.xhtml"); Do_Req (Request, Reply); Assert_Equals (T, ASF.Responses.SC_NOT_IMPLEMENTED, Reply.Get_Status, "Invalid response"); -- PUT on a file is not allowed Request.Set_Method ("PUT"); Request.Set_Request_URI ("/asfunit/views/set.xhtml"); Do_Req (Request, Reply); Assert_Equals (T, ASF.Responses.SC_METHOD_NOT_ALLOWED, Reply.Get_Status, "Invalid response"); -- POST on a file is not allowed Request.Set_Method ("POST"); Request.Set_Request_URI ("/asfunit/views/set.xhtml"); Do_Req (Request, Reply); Assert_Equals (T, ASF.Responses.SC_METHOD_NOT_ALLOWED, Reply.Get_Status, "Invalid response"); -- DELETE on a file is not allowed Request.Set_Method ("DELETE"); Request.Set_Request_URI ("/asfunit/views/set.xhtml"); Do_Req (Request, Reply); Assert_Equals (T, ASF.Responses.SC_METHOD_NOT_ALLOWED, Reply.Get_Status, "Invalid response"); end Test_Invalid_Request; -- ------------------------------ -- Test a GET request on a static file served by the File_Servlet. -- ------------------------------ procedure Test_Get_404 (T : in out Test) is Request : ASF.Requests.Mockup.Request; Reply : ASF.Responses.Mockup.Response; begin Do_Get (Request, Reply, "/file-does-not-exist.txt", "test-404.html"); Assert_Equals (T, ASF.Responses.SC_NOT_FOUND, Reply.Get_Status, "Invalid response"); end Test_Get_404; -- ------------------------------ -- Test a GET request on a static file served by the File_Servlet. -- ------------------------------ procedure Test_Get_File (T : in out Test) is Request : ASF.Requests.Mockup.Request; Reply : ASF.Responses.Mockup.Response; begin Do_Get (Request, Reply, "/views/set.xhtml", "get-file-set.txt"); Assert_Contains (T, "<c:set var=""user"" value=""John Smith""/>", Reply, "Wrong content"); Do_Get (Request, Reply, "/views/set.html", "get-file-set.html"); Assert_Matches (T, "^\s*John Smith\s?$", Reply, "Wrong content"); end Test_Get_File; -- ------------------------------ -- Test a GET request on the measure servlet -- ------------------------------ procedure Test_Get_Measures (T : in out Test) is Request : ASF.Requests.Mockup.Request; Reply : ASF.Responses.Mockup.Response; begin Do_Get (Request, Reply, "/stats.xml", "stats.xml"); -- We must get at least one measure value (assuming the Test_Get_File test -- was executed). Assert_Matches (T, "<time count=""\d+"" time=""\d+.\d+[um]s"" title="".*""/>", Reply, "Wrong content"); end Test_Get_Measures; -- ------------------------------ -- Test a GET+POST request with submitted values and an action method called on the bean. -- ------------------------------ procedure Test_Form_Post (T : in out Test) is use Util.Beans.Objects; Request : ASF.Requests.Mockup.Request; Reply : ASF.Responses.Mockup.Response; Form : aliased Form_Bean; begin Request.Set_Attribute ("form", To_Object (Value => Form'Unchecked_Access, Storage => STATIC)); Do_Get (Request, Reply, "/tests/form-text.html", "form-text.txt"); Assert_Matches (T, ".*<label for=.name.>Name</label>.*", Reply, "Wrong form content"); Assert_Matches (T, ".*<input type=.text. name=.name. value=.. id=.name.*", Reply, "Wrong form content"); Request.Set_Parameter ("formText", "1"); Request.Set_Parameter ("name", "John"); Request.Set_Parameter ("password", "12345"); Request.Set_Parameter ("email", "[email protected]"); Do_Post (Request, Reply, "/tests/form-text.html", "form-text-post.txt"); Assert_Matches (T, ".*<input type=.text. name=.name. value=.John. id=.name.*", Reply, "Wrong form content"); Assert_Equals (T, "John", Form.Name, "Form name not saved in the bean"); Assert_Equals (T, "12345", Form.Password, "Form password not saved in the bean"); Assert_Equals (T, "[email protected]", Form.Email, "Form email not saved in the bean"); end Test_Form_Post; -- ------------------------------ -- Test a POST request with an invalid submitted value -- ------------------------------ procedure Test_Form_Post_Validation_Error (T : in out Test) is use Util.Beans.Objects; Request : ASF.Requests.Mockup.Request; Reply : ASF.Responses.Mockup.Response; Form : aliased Form_Bean; begin Request.Set_Attribute ("form", To_Object (Value => Form'Unchecked_Access, Storage => STATIC)); -- Post with password too short and empty email Request.Set_Parameter ("formText", "1"); Request.Set_Parameter ("name", "John"); Request.Set_Parameter ("password", "12"); Request.Set_Parameter ("email", ""); Do_Post (Request, Reply, "/tests/form-text.html", "form-text-post-1.txt"); Assert_Matches (T, ".*<input type=.text. name=.name. value=.John. id=.name.*", Reply, "Wrong form content"); Assert_Matches (T, ".*Password: Validation Error: Length is less than " & "allowable minimum of '4'.*", Reply, "Missing error message"); -- No field should be modified. Assert_Equals (T, "", Form.Name, "Form name was saved in the bean"); Assert_Equals (T, "", Form.Password, "Form password was saved in the bean"); Assert_Equals (T, "", Form.Email, "Form email was saved in the bean"); Request.Set_Parameter ("email", "1"); Request.Set_Parameter ("password", "12333"); Request.Set_Parameter ("name", "122222222222222222222222222222222222222222"); Do_Post (Request, Reply, "/tests/form-text.html", "form-text-post-2.txt"); end Test_Form_Post_Validation_Error; end ASF.Applications.Tests;
----------------------------------------------------------------------- -- 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.Test_Caller; with ASF.Tests; with ASF.Events.Actions; with ASF.Requests.Mockup; with ASF.Responses.Mockup; with ASF.Applications.Main; package body ASF.Applications.Tests is use ASF.Tests; use Util.Tests; package Caller is new Util.Test_Caller (Test); procedure Add_Tests (Suite : AUnit.Test_Suites.Access_Test_Suite) is begin Caller.Add_Test (Suite, "Test service HTTP invalid method", Test_Invalid_Request'Access); Caller.Add_Test (Suite, "Test service HTTP GET (File_Servlet)", Test_Get_File'Access); Caller.Add_Test (Suite, "Test service HTTP GET 404", Test_Get_404'Access); Caller.Add_Test (Suite, "Test service HTTP GET (Measure_Servlet)", Test_Get_Measures'Access); Caller.Add_Test (Suite, "Test service HTTP POST+INVOKE_APPLICATION", Test_Form_Post'Access); Caller.Add_Test (Suite, "Test service HTTP POST+PROCESS_VALIDATION", Test_Form_Post_Validation_Error'Access); end Add_Tests; package Save_Binding is new ASF.Events.Actions.Action_Method.Bind (Bean => Form_Bean, Method => Save, Name => "save"); Binding_Array : aliased constant Util.Beans.Methods.Method_Binding_Array := (Save_Binding.Proxy'Access, Save_Binding.Proxy'Access); -- ------------------------------ -- Get the value identified by the name. -- ------------------------------ overriding function Get_Value (From : in Form_Bean; Name : in String) return Util.Beans.Objects.Object is begin if Name = "email" then return Util.Beans.Objects.To_Object (From.Email); elsif Name = "password" then return Util.Beans.Objects.To_Object (From.Password); elsif Name = "name" then return Util.Beans.Objects.To_Object (From.Name); else return Util.Beans.Objects.Null_Object; end if; end Get_Value; -- ------------------------------ -- 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) is begin if Name = "email" then From.Email := Util.Beans.Objects.To_Unbounded_String (Value); elsif Name = "password" then From.Password := Util.Beans.Objects.To_Unbounded_String (Value); elsif Name = "name" then From.Name := Util.Beans.Objects.To_Unbounded_String (Value); end if; end Set_Value; -- ------------------------------ -- 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 is pragma Unreferenced (From); begin return Binding_Array'Access; end Get_Method_Bindings; -- ------------------------------ -- Initialize the test application -- ------------------------------ overriding procedure Set_Up (T : in out Test) is pragma Unreferenced (T); use type ASF.Applications.Main.Application_Access; begin if ASF.Tests.Get_Application = null then ASF.Tests.Initialize (Util.Tests.Get_Properties); end if; end Set_Up; -- ------------------------------ -- Action to authenticate a user (password authentication). -- ------------------------------ procedure Save (Data : in out Form_Bean; Outcome : in out Unbounded_String) is begin Outcome := To_Unbounded_String ("success"); end Save; -- ------------------------------ -- Test an invalid HTTP request. -- ------------------------------ procedure Test_Invalid_Request (T : in out Test) is Request : ASF.Requests.Mockup.Request; Reply : ASF.Responses.Mockup.Response; begin -- Unknown method Request.Set_Method ("BLAB"); Request.Set_Request_URI ("/asfunit/views/set.xhtml"); Do_Req (Request, Reply); Assert_Equals (T, ASF.Responses.SC_NOT_IMPLEMENTED, Reply.Get_Status, "Invalid response"); -- PUT on a file is not allowed Request.Set_Method ("PUT"); Request.Set_Request_URI ("/asfunit/views/set.xhtml"); Do_Req (Request, Reply); Assert_Equals (T, ASF.Responses.SC_METHOD_NOT_ALLOWED, Reply.Get_Status, "Invalid response"); -- POST on a file is not allowed Request.Set_Method ("POST"); Request.Set_Request_URI ("/asfunit/views/set.xhtml"); Do_Req (Request, Reply); Assert_Equals (T, ASF.Responses.SC_METHOD_NOT_ALLOWED, Reply.Get_Status, "Invalid response"); -- DELETE on a file is not allowed Request.Set_Method ("DELETE"); Request.Set_Request_URI ("/asfunit/views/set.xhtml"); Do_Req (Request, Reply); Assert_Equals (T, ASF.Responses.SC_METHOD_NOT_ALLOWED, Reply.Get_Status, "Invalid response"); end Test_Invalid_Request; -- ------------------------------ -- Test a GET request on a static file served by the File_Servlet. -- ------------------------------ procedure Test_Get_404 (T : in out Test) is Request : ASF.Requests.Mockup.Request; Reply : ASF.Responses.Mockup.Response; begin Do_Get (Request, Reply, "/file-does-not-exist.txt", "test-404.html"); Assert_Equals (T, ASF.Responses.SC_NOT_FOUND, Reply.Get_Status, "Invalid response"); end Test_Get_404; -- ------------------------------ -- Test a GET request on a static file served by the File_Servlet. -- ------------------------------ procedure Test_Get_File (T : in out Test) is Request : ASF.Requests.Mockup.Request; Reply : ASF.Responses.Mockup.Response; begin Do_Get (Request, Reply, "/views/set.xhtml", "get-file-set.txt"); Assert_Contains (T, "<c:set var=""user"" value=""John Smith""/>", Reply, "Wrong content"); Do_Get (Request, Reply, "/views/set.html", "get-file-set.html"); Assert_Matches (T, "^\s*John Smith\s?$", Reply, "Wrong content"); end Test_Get_File; -- ------------------------------ -- Test a GET request on the measure servlet -- ------------------------------ procedure Test_Get_Measures (T : in out Test) is Request : ASF.Requests.Mockup.Request; Reply : ASF.Responses.Mockup.Response; begin Do_Get (Request, Reply, "/stats.xml", "stats.xml"); -- We must get at least one measure value (assuming the Test_Get_File test -- was executed). Assert_Matches (T, "<time count=""\d+"" time=""\d+.\d+[um]s"" title="".*""/>", Reply, "Wrong content"); end Test_Get_Measures; -- ------------------------------ -- Test a GET+POST request with submitted values and an action method called on the bean. -- ------------------------------ procedure Test_Form_Post (T : in out Test) is use Util.Beans.Objects; Request : ASF.Requests.Mockup.Request; Reply : ASF.Responses.Mockup.Response; Form : aliased Form_Bean; begin Request.Set_Attribute ("form", To_Object (Value => Form'Unchecked_Access, Storage => STATIC)); Do_Get (Request, Reply, "/tests/form-text.html", "form-text.txt"); Assert_Matches (T, ".*<label for=.name.>Name</label>.*", Reply, "Wrong form content"); Assert_Matches (T, ".*<input type=.text. name=.name. value=.. id=.name.*", Reply, "Wrong form content"); Request.Set_Parameter ("formText", "1"); Request.Set_Parameter ("name", "John"); Request.Set_Parameter ("password", "12345"); Request.Set_Parameter ("email", "[email protected]"); Do_Post (Request, Reply, "/tests/form-text.html", "form-text-post.txt"); Assert_Matches (T, ".*<input type=.text. name=.name. value=.John. id=.name.*", Reply, "Wrong form content"); Assert_Equals (T, "John", Form.Name, "Form name not saved in the bean"); Assert_Equals (T, "12345", Form.Password, "Form password not saved in the bean"); Assert_Equals (T, "[email protected]", Form.Email, "Form email not saved in the bean"); end Test_Form_Post; -- ------------------------------ -- Test a POST request with an invalid submitted value -- ------------------------------ procedure Test_Form_Post_Validation_Error (T : in out Test) is use Util.Beans.Objects; Request : ASF.Requests.Mockup.Request; Reply : ASF.Responses.Mockup.Response; Form : aliased Form_Bean; begin Request.Set_Attribute ("form", To_Object (Value => Form'Unchecked_Access, Storage => STATIC)); -- Post with password too short and empty email Request.Set_Parameter ("formText", "1"); Request.Set_Parameter ("name", "John"); Request.Set_Parameter ("password", "12"); Request.Set_Parameter ("email", ""); Do_Post (Request, Reply, "/tests/form-text.html", "form-text-post-1.txt"); Assert_Matches (T, ".*<input type=.text. name=.name. value=.John. id=.name.*", Reply, "Wrong form content"); Assert_Matches (T, ".*Password: Validation Error: Length is less than " & "allowable minimum of '4'.*", Reply, "Missing error message"); -- No field should be modified. Assert_Equals (T, "", Form.Name, "Form name was saved in the bean"); Assert_Equals (T, "", Form.Password, "Form password was saved in the bean"); Assert_Equals (T, "", Form.Email, "Form email was saved in the bean"); Request.Set_Parameter ("email", "1"); Request.Set_Parameter ("password", "12333"); Request.Set_Parameter ("name", "122222222222222222222222222222222222222222"); Do_Post (Request, Reply, "/tests/form-text.html", "form-text-post-2.txt"); Assert_Matches (T, ".*<span class=.error.>Invalid email address</span>.*", Reply, "Invalid error message for email"); Assert_Matches (T, ".*<span class=.error.>Invalid name</span>.*", Reply, "Invalid error message for name"); Request.Set_Parameter ("email", "1dddddd"); Request.Set_Parameter ("password", "12333ddddddddddddddd"); Request.Set_Parameter ("name", "1222222222"); Do_Post (Request, Reply, "/tests/form-text.html", "form-text-post-3.txt"); Assert_Matches (T, ".*Password: Validation Error: Length is greater than " & "allowable maximum of '10'.*", Reply, "Invalid error message for password"); end Test_Form_Post_Validation_Error; end ASF.Applications.Tests;
Verify the error message
Verify the error message
Ada
apache-2.0
Letractively/ada-asf,Letractively/ada-asf,Letractively/ada-asf
f748189fc4a415ccd2787fde5d411bc13cb192b2
awa/plugins/awa-questions/src/awa-questions-services.adb
awa/plugins/awa-questions/src/awa-questions-services.adb
----------------------------------------------------------------------- -- awa-questions-services -- Service services -- 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.Calendar; with Ada.Characters.Conversions; with AWA.Permissions; with AWA.Services.Contexts; with AWA.Users.Models; with AWA.Workspaces.Models; with AWA.Workspaces.Modules; with AWA.Wikis.Parsers; with AWA.Wikis.Writers; with ADO.Sessions; with ADO.Statements; with Util.Log.Loggers; package body AWA.Questions.Services is use AWA.Services; use ADO.Sessions; Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("AWA.Questions.Services"); -- ------------------------------ -- Create or save the question. -- ------------------------------ procedure Save_Question (Model : in Question_Service; Question : in out AWA.Questions.Models.Question_Ref'Class) is pragma Unreferenced (Model); function To_Wide (Item : in String) return Wide_Wide_String renames Ada.Characters.Conversions.To_Wide_Wide_String; Ctx : constant Contexts.Service_Context_Access := AWA.Services.Contexts.Current; User : constant AWA.Users.Models.User_Ref := Ctx.Get_User; DB : Master_Session := AWA.Services.Contexts.Get_Master_Session (Ctx); WS : AWA.Workspaces.Models.Workspace_Ref; begin Ctx.Start; if Question.Is_Inserted then Log.Info ("Updating question {0}", ADO.Identifier'Image (Question.Get_Id)); WS := AWA.Workspaces.Models.Workspace_Ref (Question.Get_Workspace); else Log.Info ("Creating new question {0}", String '(Question.Get_Title)); AWA.Workspaces.Modules.Get_Workspace (DB, Ctx, WS); -- Check that the user has the create permission on the given workspace. AWA.Permissions.Check (Permission => ACL_Create_Questions.Permission, Entity => WS); Question.Set_Workspace (WS); Question.Set_Author (User); end if; declare Text : constant String := AWA.Wikis.Writers.To_Text (To_Wide (Question.Get_Description), AWA.Wikis.Parsers.SYNTAX_MIX); Last : Natural; begin if Text'Length < SHORT_DESCRIPTION_LENGTH then Last := Text'Last; else Last := SHORT_DESCRIPTION_LENGTH; end if; Question.Set_Short_Description (Text (Text'First .. Last) & "..."); end; if not Question.Is_Inserted then Question.Set_Create_Date (Ada.Calendar.Clock); else Question.Set_Edit_Date (Ada.Calendar.Clock); end if; Question.Save (DB); Ctx.Commit; end Save_Question; -- ------------------------------ -- Delete the question. -- ------------------------------ procedure Delete_Question (Model : in Question_Service; Question : in out AWA.Questions.Models.Question_Ref'Class) is pragma Unreferenced (Model); Ctx : constant Contexts.Service_Context_Access := AWA.Services.Contexts.Current; DB : Master_Session := AWA.Services.Contexts.Get_Master_Session (Ctx); begin Ctx.Start; -- Check that the user has the delete permission on the given question. AWA.Permissions.Check (Permission => ACL_Delete_Questions.Permission, Entity => Question); -- Before deleting the question, delete the associated answers. declare Stmt : ADO.Statements.Delete_Statement := DB.Create_Statement (AWA.Questions.Models.ANSWER_TABLE); begin Stmt.Set_Filter (Filter => "question_id = ?"); Stmt.Add_Param (Value => Question); Stmt.Execute; end; Question.Delete (DB); Ctx.Commit; end Delete_Question; -- ------------------------------ -- Load the question. -- ------------------------------ procedure Load_Question (Model : in Question_Service; Question : in out AWA.Questions.Models.Question_Ref'Class; Id : in ADO.Identifier) is pragma Unreferenced (Model); Ctx : constant Contexts.Service_Context_Access := AWA.Services.Contexts.Current; DB : Master_Session := AWA.Services.Contexts.Get_Master_Session (Ctx); Found : Boolean; begin Question.Load (DB, Id, Found); end Load_Question; -- ------------------------------ -- Create or save the answer. -- ------------------------------ procedure Save_Answer (Model : in Question_Service; Question : in AWA.Questions.Models.Question_Ref'Class; Answer : in out AWA.Questions.Models.Answer_Ref'Class) is pragma Unreferenced (Model); Ctx : constant Contexts.Service_Context_Access := AWA.Services.Contexts.Current; User : constant AWA.Users.Models.User_Ref := Ctx.Get_User; DB : Master_Session := AWA.Services.Contexts.Get_Master_Session (Ctx); begin Ctx.Start; if Answer.Is_Inserted then Log.Info ("Updating question {0}", ADO.Identifier'Image (Answer.Get_Id)); else Log.Info ("Creating new answer for {0}", ADO.Identifier'Image (Question.Get_Id)); -- Check that the user has the create permission on the given workspace. AWA.Permissions.Check (Permission => ACL_Answer_Questions.Permission, Entity => Question); Answer.Set_Author (User); end if; if not Answer.Is_Inserted then Answer.Set_Create_Date (Ada.Calendar.Clock); Answer.Set_Question (Question); else Answer.Set_Edit_Date (ADO.Nullable_Time '(Value => Ada.Calendar.Clock, Is_Null => False)); end if; Answer.Save (DB); Ctx.Commit; end Save_Answer; -- ------------------------------ -- Load the answer. -- ------------------------------ procedure Load_Answer (Model : in Question_Service; Answer : in out AWA.Questions.Models.Answer_Ref'Class; Id : in ADO.Identifier) is pragma Unreferenced (Model); Ctx : constant Contexts.Service_Context_Access := AWA.Services.Contexts.Current; DB : Master_Session := AWA.Services.Contexts.Get_Master_Session (Ctx); Found : Boolean; begin Answer.Load (DB, Id, Found); end Load_Answer; end AWA.Questions.Services;
----------------------------------------------------------------------- -- awa-questions-services -- Service services -- 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.Calendar; with Ada.Characters.Conversions; with AWA.Permissions; with AWA.Services.Contexts; with AWA.Users.Models; with AWA.Workspaces.Models; with AWA.Workspaces.Modules; with AWA.Wikis.Parsers; with AWA.Wikis.Writers; with ADO.Sessions; with ADO.Statements; with Util.Log.Loggers; package body AWA.Questions.Services is use AWA.Services; use ADO.Sessions; Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("AWA.Questions.Services"); -- ------------------------------ -- Create or save the question. -- ------------------------------ procedure Save_Question (Model : in Question_Service; Question : in out AWA.Questions.Models.Question_Ref'Class) is pragma Unreferenced (Model); function To_Wide (Item : in String) return Wide_Wide_String renames Ada.Characters.Conversions.To_Wide_Wide_String; Ctx : constant Contexts.Service_Context_Access := AWA.Services.Contexts.Current; User : constant AWA.Users.Models.User_Ref := Ctx.Get_User; DB : Master_Session := AWA.Services.Contexts.Get_Master_Session (Ctx); WS : AWA.Workspaces.Models.Workspace_Ref; begin Ctx.Start; if Question.Is_Inserted then Log.Info ("Updating question {0}", ADO.Identifier'Image (Question.Get_Id)); WS := AWA.Workspaces.Models.Workspace_Ref (Question.Get_Workspace); else Log.Info ("Creating new question {0}", String '(Question.Get_Title)); AWA.Workspaces.Modules.Get_Workspace (DB, Ctx, WS); -- Check that the user has the create permission on the given workspace. AWA.Permissions.Check (Permission => ACL_Create_Questions.Permission, Entity => WS); Question.Set_Workspace (WS); Question.Set_Author (User); end if; declare Text : constant String := AWA.Wikis.Writers.To_Text (To_Wide (Question.Get_Description), AWA.Wikis.Parsers.SYNTAX_MIX); Last : Natural; begin if Text'Length < SHORT_DESCRIPTION_LENGTH then Last := Text'Last; else Last := SHORT_DESCRIPTION_LENGTH; end if; Question.Set_Short_Description (Text (Text'First .. Last) & "..."); end; if not Question.Is_Inserted then Question.Set_Create_Date (Ada.Calendar.Clock); else Question.Set_Edit_Date (Ada.Calendar.Clock); end if; Question.Save (DB); Ctx.Commit; end Save_Question; -- ------------------------------ -- Delete the question. -- ------------------------------ procedure Delete_Question (Model : in Question_Service; Question : in out AWA.Questions.Models.Question_Ref'Class) is pragma Unreferenced (Model); Ctx : constant Contexts.Service_Context_Access := AWA.Services.Contexts.Current; DB : Master_Session := AWA.Services.Contexts.Get_Master_Session (Ctx); begin Ctx.Start; -- Check that the user has the delete permission on the given question. AWA.Permissions.Check (Permission => ACL_Delete_Questions.Permission, Entity => Question); -- Before deleting the question, delete the associated answers. declare Stmt : ADO.Statements.Delete_Statement := DB.Create_Statement (AWA.Questions.Models.ANSWER_TABLE); begin Stmt.Set_Filter (Filter => "question_id = ?"); Stmt.Add_Param (Value => Question); Stmt.Execute; end; Question.Delete (DB); Ctx.Commit; end Delete_Question; -- ------------------------------ -- Load the question. -- ------------------------------ procedure Load_Question (Model : in Question_Service; Question : in out AWA.Questions.Models.Question_Ref'Class; Id : in ADO.Identifier) is pragma Unreferenced (Model); Ctx : constant Contexts.Service_Context_Access := AWA.Services.Contexts.Current; DB : Master_Session := AWA.Services.Contexts.Get_Master_Session (Ctx); Found : Boolean; begin Question.Load (DB, Id, Found); end Load_Question; -- ------------------------------ -- Create or save the answer. -- ------------------------------ procedure Save_Answer (Model : in Question_Service; Question : in AWA.Questions.Models.Question_Ref'Class; Answer : in out AWA.Questions.Models.Answer_Ref'Class) is pragma Unreferenced (Model); Ctx : constant Contexts.Service_Context_Access := AWA.Services.Contexts.Current; User : constant AWA.Users.Models.User_Ref := Ctx.Get_User; DB : Master_Session := AWA.Services.Contexts.Get_Master_Session (Ctx); begin Ctx.Start; if Answer.Is_Inserted then Log.Info ("Updating question {0}", ADO.Identifier'Image (Answer.Get_Id)); else Log.Info ("Creating new answer for {0}", ADO.Identifier'Image (Question.Get_Id)); -- Check that the user has the create permission on the given workspace. AWA.Permissions.Check (Permission => ACL_Answer_Questions.Permission, Entity => Question); Answer.Set_Author (User); end if; if not Answer.Is_Inserted then Answer.Set_Create_Date (Ada.Calendar.Clock); Answer.Set_Question (Question); else Answer.Set_Edit_Date (ADO.Nullable_Time '(Value => Ada.Calendar.Clock, Is_Null => False)); end if; Answer.Save (DB); Ctx.Commit; end Save_Answer; -- ------------------------------ -- Load the answer. -- ------------------------------ procedure Load_Answer (Model : in Question_Service; Answer : in out AWA.Questions.Models.Answer_Ref'Class; Question : in out AWA.Questions.Models.Question_Ref'Class; Id : in ADO.Identifier) is pragma Unreferenced (Model); Ctx : constant Contexts.Service_Context_Access := AWA.Services.Contexts.Current; DB : Master_Session := AWA.Services.Contexts.Get_Master_Session (Ctx); Found : Boolean; begin Answer.Load (DB, Id, Found); Question := Answer.Get_Question; end Load_Answer; end AWA.Questions.Services;
Load the question associated with the answer
Load the question associated with the answer
Ada
apache-2.0
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
3465a46a351fb30c494747aa7e1ca40c486e7816
lua.ads
lua.ads
-- Lua -- an Ada 2012 interface to Lua -- Copyright (c) 2015, James Humphry -- Permission is hereby granted, free of charge, to any person obtaining -- a copy of this software and associated documentation files (the -- "Software"), to deal in the Software without restriction, including -- without limitation the rights to use, copy, modify, merge, publish, -- distribute, sublicense, and/or sell copies of the Software, and to -- permit persons to whom the Software is furnished to do so, subject to -- the following conditions: -- -- The above copyright notice and this permission notice shall be -- included in all copies or substantial portions of the Software. -- -- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -- EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -- MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. -- IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY -- CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, -- TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE -- SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. with Ada.Finalization; private with System; private with Interfaces.C; package Lua is subtype Lua_Number is Long_Float; subtype Lua_Integer is Long_Long_Integer; type Thread_Status is (OK, YIELD, ERRRUN, ERRSYNTAX, ERRMEM, ERRGCMM, ERRERR); type Arith_Op is (OPADD, OPSUB, OPMUL, OPMOD, OPPOW, OPDIV, OPIDIV, OPBAND, OPBOR, OPBXOR, OPSHL, OPSHR, OPUNM, OPBNOT); type Comparison_Op is (OPEQ, OPLT, OPLE); type GC_Inputs is (GCSTOP, GCRESTART, GCCOLLECT, GCCOUNT, GCCOUNTB, GCSTEP, GCSETPAUSE, GCSETSTEPMUL, GCISRUNNING); for GC_Inputs use (GCSTOP => 0, GCRESTART => 1, GCCOLLECT => 2, GCCOUNT => 3, GCCOUNTB => 4, GCSTEP => 5, GCSETPAUSE => 6, GCSETSTEPMUL => 7, GCISRUNNING => 9); subtype GC_Op is GC_Inputs range GCSTOP..GCSTEP; subtype GC_Param is GC_Inputs range GCSETPAUSE..GCSETSTEPMUL; subtype GC_Queries is GC_Inputs range GCISRUNNING..GCISRUNNING; type Lua_Type is (TNONE, TNIL, TBOOLEAN, TLIGHTUSERDATA, TNUMBER, TSTRING, TTABLE, TFUNCTION, TUSERDATA, TTHREAD, TNUMTAGS); type Lua_ChunkMode is (Binary, Text, Binary_and_Text); Lua_Error : exception; -- Special stack positions and the registry MaxStack : constant Integer with Import, Convention => C, Link_Name => "lua_conf_luai_maxstack"; RegistryIndex : constant Integer with Import, Convention => C, Link_Name => "lua_conf_registry_index"; RIDX_MainThread : constant Integer; RIDX_Globals : constant Integer; RIDX_Last : constant Integer; function UpvalueIndex (i : in Integer) return Integer; -- Basic state control type Lua_State is tagged limited private; type Lua_Thread; function Version (L : in Lua_State) return Long_Float; function Status (L : in Lua_State) return Thread_Status; function LoadString (L : in Lua_State; S : in String) return Thread_Status; function LoadFile (L : in Lua_State; Name : in String; Mode : in Lua_ChunkMode := Binary_and_Text) return Thread_Status; -- Calling, yielding and functions procedure Call (L : in Lua_State; nargs : in Integer; nresults : in Integer); procedure Call_Function (L : in Lua_State; name : in String; nargs : in Integer; nresults : in Integer); function PCall (L : in Lua_State; nargs : in Integer; nresults : in Integer; msgh : in Integer := 0) return Thread_Status; function PCall_Function (L : in Lua_State; name : in String; nargs : in Integer; nresults : in Integer; msgh : in Integer := 0) return Thread_Status; type AdaFunction is access function (L : Lua_State'Class) return Natural; procedure Register(L : in Lua_State; name : in String; f : in AdaFunction); MultRet_Sentinel : constant Integer with Import, Convention => C, Link_Name => "lua_conf_multret"; -- Pushing values to the stack procedure PushAdaClosure (L : in Lua_State; f : in AdaFunction; n : in Natural); procedure PushAdaFunction (L : in Lua_State; f : in AdaFunction); procedure PushBoolean (L : in Lua_State; b : in Boolean); procedure PushInteger (L : in Lua_State; n : in Lua_Integer); procedure PushNil (L : in Lua_State); procedure PushNumber (L : in Lua_State; n : in Lua_Number); procedure PushString (L : in Lua_State; s : in String); function PushThread (L : in Lua_State) return Boolean; procedure PushThread (L : in Lua_State); function StringToNumber (L : in Lua_State; s : in String) return Boolean; -- Pulling values from the stack function ToAdaFunction (L : in Lua_State; index : in Integer) return AdaFunction; function ToBoolean (L : in Lua_State; index : in Integer) return Boolean; function ToInteger (L : in Lua_State; index : in Integer) return Lua_Integer; function ToNumber (L : in Lua_State; index : in Integer) return Lua_Number; function ToString (L : in Lua_State; index : in Integer) return String; function ToThread (L : in Lua_State; index : in Integer) return Lua_Thread; -- Operations on values procedure Arith (L : in Lua_State; op : in Arith_Op); function Compare (L : in Lua_State; index1 : in Integer; index2 : in Integer; op : in Comparison_Op) return Boolean; procedure Len (L : in Lua_State; index : Integer); function RawEqual (L : in Lua_State; index1, index2 : in Integer) return Boolean; function RawLen (L : in Lua_State; index : Integer) return Integer; -- Garbage Collector control procedure GC (L : in Lua_State; what : in GC_Op); function GC (L : in Lua_State; what : in GC_Param; data : in Integer) return Integer; function GC (L : in Lua_State) return Boolean; -- Stack manipulation and information function AbsIndex (L : in Lua_State; idx : in Integer) return Integer; function CheckStack (L : in Lua_State; n : in Integer) return Boolean; procedure Copy (L : in Lua_State; fromidx : in Integer; toidx : in Integer); function GetTop (L : in Lua_State) return Integer; procedure Insert (L : in Lua_State; index : in Integer); procedure Pop (L : in Lua_State; n : in Integer); procedure PushValue (L : in Lua_State; index : in Integer); procedure Remove (L : in Lua_State; index : in Integer); procedure Replace (L : in Lua_State; index : in Integer); procedure Rotate (L : in Lua_State; idx : in Integer; n : in Integer); procedure SetTop (L : in Lua_State; index : in Integer); -- Type information function IsAdaFunction (L : in Lua_State; index : in Integer) return Boolean; function IsBoolean (L : in Lua_State; index : in Integer) return Boolean; function IsCFunction (L : in Lua_State; index : in Integer) return Boolean; function IsFunction (L : in Lua_State; index : in Integer) return Boolean; function IsInteger (L : in Lua_State; index : in Integer) return Boolean; function IsLightuserdata (L : in Lua_State; index : in Integer) return Boolean; function IsNil (L : in Lua_State; index : in Integer) return Boolean; function IsNone (L : in Lua_State; index : in Integer) return Boolean; function IsNoneOrNil (L : in Lua_State; index : in Integer) return Boolean; function IsNumber (L : in Lua_State; index : in Integer) return Boolean; function IsString (L : in Lua_State; index : in Integer) return Boolean; function IsTable (L : in Lua_State; index : in Integer) return Boolean; function IsThread (L : in Lua_State; index : in Integer) return Boolean; function IsUserdata (L : in Lua_State; index : in Integer) return Boolean; function TypeInfo (L : in Lua_State; index : in Integer) return Lua_Type; function TypeName (L : in Lua_State; tp : in Lua_Type) return String; function TypeName (L : in Lua_State; index : in Integer) return String is (TypeName(L, Typeinfo(L, index))); function Userdata_Name (L : in Lua_State; index : in Integer) return String; -- Table manipulation procedure CreateTable (L : in Lua_State; narr : in Integer := 0; nrec : in Integer := 0); procedure NewTable (L : in Lua_State); function GetField (L : in Lua_State; index : in Integer; k : in String) return Lua_Type; procedure GetField (L : in Lua_State; index : in Integer; k : in String); function Geti (L : in Lua_State; index : in Integer; i : in Integer) return Lua_Type; procedure Geti (L : in Lua_State; index : in Integer; i : in Integer); function GetTable (L : in Lua_State; index : in Integer) return Lua_Type; procedure GetTable (L : in Lua_State; index : in Integer); function Next (L : in Lua_State; index : in Integer) return Boolean; function RawGet (L : in Lua_State; index : in Integer) return Lua_Type; procedure RawGet (L : in Lua_State; index : in Integer); function RawGeti (L : in Lua_State; index : in Integer; i : in Integer) return Lua_Type; procedure RawGeti (L : in Lua_State; index : in Integer; i : in Integer); procedure RawSet (L : in Lua_State; index : in Integer); procedure RawSeti (L : in Lua_State; index : in Integer; i : in Integer); procedure SetField (L : in Lua_State; index : in Integer; k : in String); procedure Seti (L : in Lua_State; index : in Integer; i : in Integer); procedure SetTable (L : in Lua_State; index : in Integer); -- Globals and metatables function GetGlobal (L : in Lua_State; name : in String) return Lua_Type; procedure GetGlobal (L : in Lua_State; name : in String); function GetMetatable (L : in Lua_State; index : in Integer) return Boolean; procedure GetMetatable (L : in Lua_State; index : in Integer); procedure PushGlobalTable (L : in Lua_State); procedure SetGlobal (L : in Lua_State; name : in String); procedure SetMetatable (L : in Lua_State; index : in Integer); -- Threads type Lua_Thread is new Lua_State with private; function IsYieldable (L : in Lua_State'Class) return Boolean; function NewThread (L : in Lua_State'Class) return Lua_Thread; function Resume(L : in Lua_State'Class; from : in Lua_State'Class; nargs : Integer) return Thread_Status; procedure XMove (from, to : in Lua_Thread; n : in Integer); procedure Yield (L : in Lua_State; nresults : Integer); -- References type Lua_Reference is tagged private; function Ref (L : in Lua_State'Class; t : in Integer := RegistryIndex) return Lua_Reference; function Get (L : in Lua_State; R : Lua_Reference'Class) return Lua_Type; procedure Get (L : in Lua_State; R : Lua_Reference'Class); private subtype void_ptr is System.Address; for Thread_Status use (OK => 0, YIELD => 1, ERRRUN => 2, ERRSYNTAX => 3, ERRMEM => 4, ERRGCMM => 5, ERRERR => 6); for Arith_Op use (OPADD => 0, OPSUB => 1, OPMUL => 2, OPMOD => 3, OPPOW => 4, OPDIV => 5, OPIDIV => 6, OPBAND => 7, OPBOR => 8, OPBXOR => 9, OPSHL => 10, OPSHR => 11, OPUNM => 12, OPBNOT => 13); for Comparison_Op use (OPEQ => 0, OPLT => 1, OPLE => 2); for Lua_Type use (TNONE => -1, TNIL => 0, TBOOLEAN => 1, TLIGHTUSERDATA => 2, TNUMBER => 3, TSTRING => 4, TTABLE => 5, TFUNCTION => 6, TUSERDATA => 7, TTHREAD => 8, TNUMTAGS => 9); RIDX_MainThread : constant Integer := 1; RIDX_Globals : constant Integer := 2; RIDX_Last : constant Integer := RIDX_Globals; type Lua_State is new Ada.Finalization.Limited_Controlled with record L : void_Ptr; end record; overriding procedure Initialize (Object : in out Lua_State); overriding procedure Finalize (Object : in out Lua_State); -- Existing_State is a clone of State but without automatic initialization -- It is used internally when lua_State* are returned from the Lua library -- and we don't want to re-initialize them when turning them into the -- State record type. type Existing_State is new Lua_State with null record; overriding procedure Initialize (Object : in out Existing_State) is null; overriding procedure Finalize (Object : in out Existing_State) is null; type Lua_Thread is new Existing_State with null record; -- Trampolines function CFunction_Trampoline (L : System.Address) return Interfaces.C.int with Convention => C; -- References type Lua_Reference_Value is record State : void_Ptr; Table : Interfaces.C.Int; Ref : Interfaces.C.Int; Count : Natural := 0; end record; type Lua_Reference_Value_Access is access Lua_Reference_Value; type Lua_Reference is new Ada.Finalization.Controlled with record E : Lua_Reference_Value_Access := null; end record; overriding procedure Initialize (Object : in out Lua_Reference) is null; overriding procedure Adjust (Object : in out Lua_Reference); overriding procedure Finalize (Object : in out Lua_Reference); end Lua;
-- Lua -- an Ada 2012 interface to Lua -- Copyright (c) 2015, James Humphry -- Permission is hereby granted, free of charge, to any person obtaining -- a copy of this software and associated documentation files (the -- "Software"), to deal in the Software without restriction, including -- without limitation the rights to use, copy, modify, merge, publish, -- distribute, sublicense, and/or sell copies of the Software, and to -- permit persons to whom the Software is furnished to do so, subject to -- the following conditions: -- -- The above copyright notice and this permission notice shall be -- included in all copies or substantial portions of the Software. -- -- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -- EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -- MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. -- IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY -- CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, -- TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE -- SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. with Ada.Finalization; private with System; private with Interfaces.C; package Lua is subtype Lua_Number is Long_Float; subtype Lua_Integer is Long_Long_Integer; type Thread_Status is (OK, YIELD, ERRRUN, ERRSYNTAX, ERRMEM, ERRGCMM, ERRERR); type Arith_Op is (OPADD, OPSUB, OPMUL, OPMOD, OPPOW, OPDIV, OPIDIV, OPBAND, OPBOR, OPBXOR, OPSHL, OPSHR, OPUNM, OPBNOT); type Comparison_Op is (OPEQ, OPLT, OPLE); type GC_Inputs is (GCSTOP, GCRESTART, GCCOLLECT, GCCOUNT, GCCOUNTB, GCSTEP, GCSETPAUSE, GCSETSTEPMUL, GCISRUNNING); for GC_Inputs use (GCSTOP => 0, GCRESTART => 1, GCCOLLECT => 2, GCCOUNT => 3, GCCOUNTB => 4, GCSTEP => 5, GCSETPAUSE => 6, GCSETSTEPMUL => 7, GCISRUNNING => 9); subtype GC_Op is GC_Inputs range GCSTOP..GCSTEP; subtype GC_Param is GC_Inputs range GCSETPAUSE..GCSETSTEPMUL; subtype GC_Queries is GC_Inputs range GCISRUNNING..GCISRUNNING; type Lua_Type is (TNONE, TNIL, TBOOLEAN, TLIGHTUSERDATA, TNUMBER, TSTRING, TTABLE, TFUNCTION, TUSERDATA, TTHREAD, TNUMTAGS); type Lua_ChunkMode is (Binary, Text, Binary_and_Text); Lua_Error : exception; -- Special stack positions and the registry MaxStack : constant Integer with Import, Convention => C, Link_Name => "lua_conf_luai_maxstack"; RegistryIndex : constant Integer with Import, Convention => C, Link_Name => "lua_conf_registry_index"; RIDX_MainThread : constant Integer; RIDX_Globals : constant Integer; RIDX_Last : constant Integer; function UpvalueIndex (i : in Integer) return Integer; -- Basic state control type Lua_State is tagged limited private; type Lua_Thread; function Version (L : in Lua_State) return Long_Float; function Status (L : in Lua_State) return Thread_Status; function LoadString (L : in Lua_State; S : in String) return Thread_Status; function LoadFile (L : in Lua_State; Name : in String; Mode : in Lua_ChunkMode := Binary_and_Text) return Thread_Status; -- Calling, yielding and functions procedure Call (L : in Lua_State; nargs : in Integer; nresults : in Integer) with Inline, Pre => IsFunction(L, -nargs-1); procedure Call_Function (L : in Lua_State; name : in String; nargs : in Integer; nresults : in Integer); function PCall (L : in Lua_State; nargs : in Integer; nresults : in Integer; msgh : in Integer := 0) return Thread_Status with Inline, Pre => IsFunction(L, -nargs-1); function PCall_Function (L : in Lua_State; name : in String; nargs : in Integer; nresults : in Integer; msgh : in Integer := 0) return Thread_Status; type AdaFunction is access function (L : Lua_State'Class) return Natural; procedure Register(L : in Lua_State; name : in String; f : in AdaFunction); MultRet_Sentinel : constant Integer with Import, Convention => C, Link_Name => "lua_conf_multret"; -- Pushing values to the stack procedure PushAdaClosure (L : in Lua_State; f : in AdaFunction; n : in Natural); procedure PushAdaFunction (L : in Lua_State; f : in AdaFunction); procedure PushBoolean (L : in Lua_State; b : in Boolean); procedure PushInteger (L : in Lua_State; n : in Lua_Integer); procedure PushNil (L : in Lua_State); procedure PushNumber (L : in Lua_State; n : in Lua_Number); procedure PushString (L : in Lua_State; s : in String); function PushThread (L : in Lua_State) return Boolean; procedure PushThread (L : in Lua_State); function StringToNumber (L : in Lua_State; s : in String) return Boolean; -- Pulling values from the stack function ToAdaFunction (L : in Lua_State; index : in Integer) return AdaFunction; function ToBoolean (L : in Lua_State; index : in Integer) return Boolean; function ToInteger (L : in Lua_State; index : in Integer) return Lua_Integer; function ToNumber (L : in Lua_State; index : in Integer) return Lua_Number; function ToString (L : in Lua_State; index : in Integer) return String; function ToThread (L : in Lua_State; index : in Integer) return Lua_Thread; -- Operations on values procedure Arith (L : in Lua_State; op : in Arith_Op); function Compare (L : in Lua_State; index1 : in Integer; index2 : in Integer; op : in Comparison_Op) return Boolean; procedure Len (L : in Lua_State; index : Integer); function RawEqual (L : in Lua_State; index1, index2 : in Integer) return Boolean; function RawLen (L : in Lua_State; index : Integer) return Integer; -- Garbage Collector control procedure GC (L : in Lua_State; what : in GC_Op); function GC (L : in Lua_State; what : in GC_Param; data : in Integer) return Integer; function GC (L : in Lua_State) return Boolean; -- Stack manipulation and information function AbsIndex (L : in Lua_State; idx : in Integer) return Integer; function CheckStack (L : in Lua_State; n : in Integer) return Boolean; procedure Copy (L : in Lua_State; fromidx : in Integer; toidx : in Integer); function GetTop (L : in Lua_State) return Integer; procedure Insert (L : in Lua_State; index : in Integer); procedure Pop (L : in Lua_State; n : in Integer); procedure PushValue (L : in Lua_State; index : in Integer); procedure Remove (L : in Lua_State; index : in Integer); procedure Replace (L : in Lua_State; index : in Integer); procedure Rotate (L : in Lua_State; idx : in Integer; n : in Integer); procedure SetTop (L : in Lua_State; index : in Integer); -- Type information function IsAdaFunction (L : in Lua_State; index : in Integer) return Boolean; function IsBoolean (L : in Lua_State; index : in Integer) return Boolean; function IsCFunction (L : in Lua_State; index : in Integer) return Boolean; function IsFunction (L : in Lua_State; index : in Integer) return Boolean; function IsInteger (L : in Lua_State; index : in Integer) return Boolean; function IsLightuserdata (L : in Lua_State; index : in Integer) return Boolean; function IsNil (L : in Lua_State; index : in Integer) return Boolean; function IsNone (L : in Lua_State; index : in Integer) return Boolean; function IsNoneOrNil (L : in Lua_State; index : in Integer) return Boolean; function IsNumber (L : in Lua_State; index : in Integer) return Boolean; function IsString (L : in Lua_State; index : in Integer) return Boolean; function IsTable (L : in Lua_State; index : in Integer) return Boolean; function IsThread (L : in Lua_State; index : in Integer) return Boolean; function IsUserdata (L : in Lua_State; index : in Integer) return Boolean; function TypeInfo (L : in Lua_State; index : in Integer) return Lua_Type; function TypeName (L : in Lua_State; tp : in Lua_Type) return String; function TypeName (L : in Lua_State; index : in Integer) return String is (TypeName(L, Typeinfo(L, index))); function Userdata_Name (L : in Lua_State; index : in Integer) return String; -- Table manipulation procedure CreateTable (L : in Lua_State; narr : in Integer := 0; nrec : in Integer := 0); procedure NewTable (L : in Lua_State); function GetField (L : in Lua_State; index : in Integer; k : in String) return Lua_Type with Inline, Pre => IsTable(L, index); procedure GetField (L : in Lua_State; index : in Integer; k : in String) with Inline, Pre => IsTable(L, index); function Geti (L : in Lua_State; index : in Integer; i : in Integer) return Lua_Type with Inline, Pre => IsTable(L, index); procedure Geti (L : in Lua_State; index : in Integer; i : in Integer) with Inline, Pre => IsTable(L, index); function GetTable (L : in Lua_State; index : in Integer) return Lua_Type with Inline, Pre => IsTable(L, index); procedure GetTable (L : in Lua_State; index : in Integer) with Inline, Pre => IsTable(L, index); function Next (L : in Lua_State; index : in Integer) return Boolean; function RawGet (L : in Lua_State; index : in Integer) return Lua_Type with Inline, Pre => IsTable(L, index); procedure RawGet (L : in Lua_State; index : in Integer) with Inline, Pre => IsTable(L, index); function RawGeti (L : in Lua_State; index : in Integer; i : in Integer) return Lua_Type with Inline, Pre => IsTable(L, index); procedure RawGeti (L : in Lua_State; index : in Integer; i : in Integer) with Inline, Pre => IsTable(L, index); procedure RawSet (L : in Lua_State; index : in Integer) with Inline, Pre => IsTable(L, index); procedure RawSeti (L : in Lua_State; index : in Integer; i : in Integer) with Inline, Pre => IsTable(L, index); procedure SetField (L : in Lua_State; index : in Integer; k : in String) with Inline, Pre => IsTable(L, index); procedure Seti (L : in Lua_State; index : in Integer; i : in Integer) with Inline, Pre => IsTable(L, index); procedure SetTable (L : in Lua_State; index : in Integer) with Inline, Pre => IsTable(L, index); -- Globals and metatables function GetGlobal (L : in Lua_State; name : in String) return Lua_Type; procedure GetGlobal (L : in Lua_State; name : in String); function GetMetatable (L : in Lua_State; index : in Integer) return Boolean; procedure GetMetatable (L : in Lua_State; index : in Integer); procedure PushGlobalTable (L : in Lua_State); procedure SetGlobal (L : in Lua_State; name : in String); procedure SetMetatable (L : in Lua_State; index : in Integer); -- Threads type Lua_Thread is new Lua_State with private; function IsYieldable (L : in Lua_State'Class) return Boolean; function NewThread (L : in Lua_State'Class) return Lua_Thread; function Resume(L : in Lua_State'Class; from : in Lua_State'Class; nargs : Integer) return Thread_Status; procedure XMove (from, to : in Lua_Thread; n : in Integer); procedure Yield (L : in Lua_State; nresults : Integer); -- References type Lua_Reference is tagged private; function Ref (L : in Lua_State'Class; t : in Integer := RegistryIndex) return Lua_Reference; function Get (L : in Lua_State; R : Lua_Reference'Class) return Lua_Type; procedure Get (L : in Lua_State; R : Lua_Reference'Class); private subtype void_ptr is System.Address; for Thread_Status use (OK => 0, YIELD => 1, ERRRUN => 2, ERRSYNTAX => 3, ERRMEM => 4, ERRGCMM => 5, ERRERR => 6); for Arith_Op use (OPADD => 0, OPSUB => 1, OPMUL => 2, OPMOD => 3, OPPOW => 4, OPDIV => 5, OPIDIV => 6, OPBAND => 7, OPBOR => 8, OPBXOR => 9, OPSHL => 10, OPSHR => 11, OPUNM => 12, OPBNOT => 13); for Comparison_Op use (OPEQ => 0, OPLT => 1, OPLE => 2); for Lua_Type use (TNONE => -1, TNIL => 0, TBOOLEAN => 1, TLIGHTUSERDATA => 2, TNUMBER => 3, TSTRING => 4, TTABLE => 5, TFUNCTION => 6, TUSERDATA => 7, TTHREAD => 8, TNUMTAGS => 9); RIDX_MainThread : constant Integer := 1; RIDX_Globals : constant Integer := 2; RIDX_Last : constant Integer := RIDX_Globals; type Lua_State is new Ada.Finalization.Limited_Controlled with record L : void_Ptr; end record; overriding procedure Initialize (Object : in out Lua_State); overriding procedure Finalize (Object : in out Lua_State); -- Existing_State is a clone of State but without automatic initialization -- It is used internally when lua_State* are returned from the Lua library -- and we don't want to re-initialize them when turning them into the -- State record type. type Existing_State is new Lua_State with null record; overriding procedure Initialize (Object : in out Existing_State) is null; overriding procedure Finalize (Object : in out Existing_State) is null; type Lua_Thread is new Existing_State with null record; -- Trampolines function CFunction_Trampoline (L : System.Address) return Interfaces.C.int with Convention => C; -- References type Lua_Reference_Value is record State : void_Ptr; Table : Interfaces.C.Int; Ref : Interfaces.C.Int; Count : Natural := 0; end record; type Lua_Reference_Value_Access is access Lua_Reference_Value; type Lua_Reference is new Ada.Finalization.Controlled with record E : Lua_Reference_Value_Access := null; end record; overriding procedure Initialize (Object : in out Lua_Reference) is null; overriding procedure Adjust (Object : in out Lua_Reference); overriding procedure Finalize (Object : in out Lua_Reference); end Lua;
Add preconditions on calling and table routines
Add preconditions on calling and table routines
Ada
mit
jhumphry/aLua
5bbe9ece7f3c0abbd7ad286045a31023b2358972
mat/src/mat-consoles.ads
mat/src/mat-consoles.ads
----------------------------------------------------------------------- -- mat-consoles - Console interface -- 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 MAT.Types; package MAT.Consoles is type Field_Type is (F_ADDR, F_SIZE, F_TOTAL_SIZE, F_MIN_SIZE, F_MAX_SIZE, F_MIN_ADDR, F_MAX_ADDR, F_THREAD, F_COUNT, F_FILE_NAME, F_FUNCTION_NAME, F_LINE_NUMBER, F_ID, F_OLD_ADDR, F_TIME, F_EVENT); type Notice_Type is (N_PID_INFO, N_DURATION, N_PATH_INFO); type Console_Type is abstract tagged limited private; type Console_Access is access all Console_Type'Class; -- Report an error message. procedure Error (Console : in out Console_Type; Message : in String) is abstract; -- Report a notice message. procedure Notice (Console : in out Console_Type; Kind : in Notice_Type; Message : in String) is abstract; -- Print the field value for the given field. procedure Print_Field (Console : in out Console_Type; Field : in Field_Type; Value : in String) is abstract; -- Print the title for the given field. procedure Print_Title (Console : in out Console_Type; Field : in Field_Type; Title : in String) is abstract; -- Start a new title in a report. procedure Start_Title (Console : in out Console_Type) is abstract; -- Finish a new title in a report. procedure End_Title (Console : in out Console_Type) is abstract; -- Start a new row in a report. procedure Start_Row (Console : in out Console_Type) is abstract; -- Finish a new row in a report. procedure End_Row (Console : in out Console_Type) is abstract; -- Print the title for the given field and setup the associated field size. procedure Print_Title (Console : in out Console_Type; Field : in Field_Type; Title : in String; Length : in Positive); -- Format the address and print it for the given field. procedure Print_Field (Console : in out Console_Type; Field : in Field_Type; Addr : in MAT.Types.Target_Addr); -- Format the size and print it for the given field. procedure Print_Size (Console : in out Console_Type; Field : in Field_Type; Size : in MAT.Types.Target_Size); -- Format the thread information and print it for the given field. procedure Print_Thread (Console : in out Console_Type; Field : in Field_Type; Thread : in MAT.Types.Target_Thread_Ref); -- Format the time tick as a duration and print it for the given field. procedure Print_Duration (Console : in out Console_Type; Field : in Field_Type; Duration : in MAT.Types.Target_Tick_Ref); -- Format the integer and print it for the given field. procedure Print_Field (Console : in out Console_Type; Field : in Field_Type; Value : in Integer); -- Format the integer and print it for the given field. procedure Print_Field (Console : in out Console_Type; Field : in Field_Type; Value : in Ada.Strings.Unbounded.Unbounded_String); private type Field_Size_Array is array (Field_Type) of Natural; type Field_List_Array is array (1 .. Field_Type'Pos (Field_Type'Last)) of Field_Type; type Console_Type is abstract tagged limited record Sizes : Field_Size_Array := (others => 1); Cols : Field_Size_Array := (others => 1); Fields : Field_List_Array; Field_Count : Natural := 0; end record; end MAT.Consoles;
----------------------------------------------------------------------- -- mat-consoles - Console interface -- 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 MAT.Types; package MAT.Consoles is type Field_Type is (F_ADDR, F_SIZE, F_TOTAL_SIZE, F_MIN_SIZE, F_MAX_SIZE, F_MIN_ADDR, F_MAX_ADDR, F_THREAD, F_COUNT, F_FILE_NAME, F_FUNCTION_NAME, F_LINE_NUMBER, F_ID, F_OLD_ADDR, F_TIME, F_EVENT, F_FRAME_ID, F_FRAME_ADDR); type Notice_Type is (N_PID_INFO, N_DURATION, N_PATH_INFO); type Console_Type is abstract tagged limited private; type Console_Access is access all Console_Type'Class; -- Report an error message. procedure Error (Console : in out Console_Type; Message : in String) is abstract; -- Report a notice message. procedure Notice (Console : in out Console_Type; Kind : in Notice_Type; Message : in String) is abstract; -- Print the field value for the given field. procedure Print_Field (Console : in out Console_Type; Field : in Field_Type; Value : in String) is abstract; -- Print the title for the given field. procedure Print_Title (Console : in out Console_Type; Field : in Field_Type; Title : in String) is abstract; -- Start a new title in a report. procedure Start_Title (Console : in out Console_Type) is abstract; -- Finish a new title in a report. procedure End_Title (Console : in out Console_Type) is abstract; -- Start a new row in a report. procedure Start_Row (Console : in out Console_Type) is abstract; -- Finish a new row in a report. procedure End_Row (Console : in out Console_Type) is abstract; -- Print the title for the given field and setup the associated field size. procedure Print_Title (Console : in out Console_Type; Field : in Field_Type; Title : in String; Length : in Positive); -- Format the address and print it for the given field. procedure Print_Field (Console : in out Console_Type; Field : in Field_Type; Addr : in MAT.Types.Target_Addr); -- Format the size and print it for the given field. procedure Print_Size (Console : in out Console_Type; Field : in Field_Type; Size : in MAT.Types.Target_Size); -- Format the thread information and print it for the given field. procedure Print_Thread (Console : in out Console_Type; Field : in Field_Type; Thread : in MAT.Types.Target_Thread_Ref); -- Format the time tick as a duration and print it for the given field. procedure Print_Duration (Console : in out Console_Type; Field : in Field_Type; Duration : in MAT.Types.Target_Tick_Ref); -- Format the integer and print it for the given field. procedure Print_Field (Console : in out Console_Type; Field : in Field_Type; Value : in Integer); -- Format the integer and print it for the given field. procedure Print_Field (Console : in out Console_Type; Field : in Field_Type; Value : in Ada.Strings.Unbounded.Unbounded_String); private type Field_Size_Array is array (Field_Type) of Natural; type Field_List_Array is array (1 .. Field_Type'Pos (Field_Type'Last)) of Field_Type; type Console_Type is abstract tagged limited record Sizes : Field_Size_Array := (others => 1); Cols : Field_Size_Array := (others => 1); Fields : Field_List_Array; Field_Count : Natural := 0; end record; end MAT.Consoles;
Add F_FRAME_ID and F_FRAME_ADDR enums
Add F_FRAME_ID and F_FRAME_ADDR enums
Ada
apache-2.0
stcarrez/mat,stcarrez/mat,stcarrez/mat
8b2aba86bb45b5b01d5da35c1894bc9fbbb8f9aa
regtests/el-expressions-tests.adb
regtests/el-expressions-tests.adb
----------------------------------------------------------------------- -- EL testsuite - EL Testsuite -- Copyright (C) 2009, 2010 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with AUnit.Test_Caller; with AUnit.Assertions; with EL.Expressions; with Test_Bean; package body EL.Expressions.Tests is use Test_Bean; use EL.Expressions; use AUnit.Assertions; use AUnit.Test_Fixtures; procedure Check_Error (T : in out Test'Class; Expr : in String); -- Check that evaluating an expression raises an exception procedure Check_Error (T : in out Test'Class; Expr : in String) is E : Expression; begin E := Create_Expression (Context => T.Context, Expr => Expr); pragma Unreferenced (E); Assert (Condition => False, Message => "Evaludation of '" & Expr & "' should raise an exception"); exception when Invalid_Expression => null; end Check_Error; -- Check that evaluating an expression returns the expected result -- (to keep the test simple, results are only checked using strings) procedure Check (T : in out Test; Expr : in String; Expect : in String) is E : constant Expression := Create_Expression (Context => T.Context, Expr => Expr); V : constant Object := E.Get_Value (Context => T.Context); begin Assert (Condition => To_String (V) = Expect, Message => "Evaluate '" & Expr & "' returned '" & To_String (V) & "' when we expect '" & Expect & "'"); declare E2 : constant Expression := E.Reduce_Expression (Context => T.Context); V2 : constant Object := E2.Get_Value (Context => T.Context); begin Assert (To_String (V2) = Expect, "Reduce produced incorrect result: " & To_String (V2)); end; end Check; -- Test evaluation of expression using a bean procedure Test_Bean_Evaluation (T : in out Test) is P : constant Person_Access := Create_Person ("Joe", "Black", 42); begin T.Context.Set_Variable ("user", P); Check (T, "#{empty user}", "FALSE"); Check (T, "#{not empty user}", "TRUE"); Check (T, "#{user.firstName}", "Joe"); Check (T, "#{user.lastName}", "Black"); Check (T, "#{user.age}", " 42"); Check (T, "#{user.date}", To_String (To_Object (P.Date))); Check (T, "#{user.weight}", To_String (To_Object (P.Weight))); P.Age := P.Age + 1; Check (T, "#{user.age}", " 43"); Check (T, "#{user.firstName & ' ' & user.lastName}", "Joe Black"); Check (T, "Joe is#{user.age} year#{user.age > 0 ? 's' : ''} old", "Joe is 43 years old"); end Test_Bean_Evaluation; -- Test evaluation of expression using a bean procedure Test_Parse_Error (T : in out Test) is begin Check_Error (T, "#{1 +}"); Check_Error (T, "#{12(}"); Check_Error (T, "#{foo(1)}"); Check_Error (T, "#{1+2+'abc}"); Check_Error (T, "#{1+""}"); Check_Error (T, "#{12"); Check_Error (T, "${1"); Check_Error (T, "test #{'}"); end Test_Parse_Error; package Caller is new AUnit.Test_Caller (Test); procedure Add_Tests (Suite : AUnit.Test_Suites.Access_Test_Suite) is begin -- Test_Bean verifies several methods. Register several times -- to enumerate what is tested. Suite.Add_Test (Caller.Create ("Test EL.Contexts.Set_Variable", Test_Bean_Evaluation'Access)); Suite.Add_Test (Caller.Create ("Test EL.Beans.Get_Value", Test_Bean_Evaluation'Access)); Suite.Add_Test (Caller.Create ("Test EL.Expressions.Create_Expression", Test_Bean_Evaluation'Access)); Suite.Add_Test (Caller.Create ("Test EL.Expressions.Get_Value", Test_Bean_Evaluation'Access)); Suite.Add_Test (Caller.Create ("Test EL.Expressions.Create_Expression (Parse Error)", Test_Parse_Error'Access)); end Add_Tests; end EL.Expressions.Tests;
----------------------------------------------------------------------- -- EL testsuite - EL Testsuite -- Copyright (C) 2009, 2010 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with AUnit.Test_Caller; with AUnit.Assertions; with EL.Expressions; with Test_Bean; package body EL.Expressions.Tests is use Test_Bean; use EL.Expressions; use AUnit.Assertions; use AUnit.Test_Fixtures; procedure Check_Error (T : in out Test'Class; Expr : in String); -- Check that evaluating an expression raises an exception procedure Check_Error (T : in out Test'Class; Expr : in String) is E : Expression; begin E := Create_Expression (Context => T.Context, Expr => Expr); pragma Unreferenced (E); Assert (Condition => False, Message => "Evaludation of '" & Expr & "' should raise an exception"); exception when Invalid_Expression => null; end Check_Error; -- Check that evaluating an expression returns the expected result -- (to keep the test simple, results are only checked using strings) procedure Check (T : in out Test; Expr : in String; Expect : in String) is E : constant Expression := Create_Expression (Context => T.Context, Expr => Expr); V : constant Object := E.Get_Value (Context => T.Context); begin Assert (Condition => To_String (V) = Expect, Message => "Evaluate '" & Expr & "' returned '" & To_String (V) & "' when we expect '" & Expect & "'"); declare E2 : constant Expression := E.Reduce_Expression (Context => T.Context); V2 : constant Object := E2.Get_Value (Context => T.Context); begin Assert (To_String (V2) = Expect, "Reduce produced incorrect result: " & To_String (V2)); end; end Check; -- Test evaluation of expression using a bean procedure Test_Bean_Evaluation (T : in out Test) is P : constant Person_Access := Create_Person ("Joe", "Black", 42); begin T.Context.Set_Variable ("user", P); Check (T, "#{user ne null}", "FALSE"); Check (T, "#{empty user}", "FALSE"); Check (T, "#{not empty user}", "TRUE"); Check (T, "#{user.firstName}", "Joe"); Check (T, "#{user.lastName}", "Black"); Check (T, "#{user.age}", " 42"); Check (T, "#{user.date}", To_String (To_Object (P.Date))); Check (T, "#{user.weight}", To_String (To_Object (P.Weight))); P.Age := P.Age + 1; Check (T, "#{user.age}", " 43"); Check (T, "#{user.firstName & ' ' & user.lastName}", "Joe Black"); Check (T, "Joe is#{user.age} year#{user.age > 0 ? 's' : ''} old", "Joe is 43 years old"); end Test_Bean_Evaluation; -- Test evaluation of expression using a bean procedure Test_Parse_Error (T : in out Test) is begin Check_Error (T, "#{1 +}"); Check_Error (T, "#{12(}"); Check_Error (T, "#{foo(1)}"); Check_Error (T, "#{1+2+'abc}"); Check_Error (T, "#{1+""}"); Check_Error (T, "#{12"); Check_Error (T, "${1"); Check_Error (T, "test #{'}"); end Test_Parse_Error; package Caller is new AUnit.Test_Caller (Test); procedure Add_Tests (Suite : AUnit.Test_Suites.Access_Test_Suite) is begin -- Test_Bean verifies several methods. Register several times -- to enumerate what is tested. Suite.Add_Test (Caller.Create ("Test EL.Contexts.Set_Variable", Test_Bean_Evaluation'Access)); Suite.Add_Test (Caller.Create ("Test EL.Beans.Get_Value", Test_Bean_Evaluation'Access)); Suite.Add_Test (Caller.Create ("Test EL.Expressions.Create_Expression", Test_Bean_Evaluation'Access)); Suite.Add_Test (Caller.Create ("Test EL.Expressions.Get_Value", Test_Bean_Evaluation'Access)); Suite.Add_Test (Caller.Create ("Test EL.Expressions.Create_Expression (Parse Error)", Test_Parse_Error'Access)); end Add_Tests; end EL.Expressions.Tests;
Add test for 'ne' operator
Add test for 'ne' operator
Ada
apache-2.0
Letractively/ada-el
a66d8868add5a0942664e09df0e5f2e648d05a71
src/sqlite/ado-drivers-connections-sqlite.adb
src/sqlite/ado-drivers-connections-sqlite.adb
----------------------------------------------------------------------- -- ADO Sqlite Database -- SQLite Database connections -- Copyright (C) 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 Sqlite3_H; with Interfaces.C.Strings; with Util.Log; with Util.Log.Loggers; with ADO.Statements.Sqlite; with ADO.Schemas.Sqlite; package body ADO.Drivers.Connections.Sqlite is use ADO.Statements.Sqlite; use Interfaces.C; pragma Linker_Options ("-lsqlite3"); Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("ADO.Databases.Sqlite"); Driver_Name : aliased constant String := "sqlite"; Driver : aliased Sqlite_Driver; No_Callback : constant Sqlite3_H.sqlite3_callback := null; -- ------------------------------ -- Get the database driver which manages this connection. -- ------------------------------ overriding function Get_Driver (Database : in Database_Connection) return Driver_Access is pragma Unreferenced (Database); begin return Driver'Access; end Get_Driver; -- ------------------------------ -- Check for an error after executing a sqlite statement. -- ------------------------------ procedure Check_Error (Connection : in Sqlite_Access; Result : in int) is begin if Result /= Sqlite3_H.SQLITE_OK and Result /= Sqlite3_H.SQLITE_DONE then declare Error : constant Strings.chars_ptr := Sqlite3_H.sqlite3_errmsg (Connection); Msg : constant String := Strings.Value (Error); begin Log.Error ("Error {0}: {1}", int'Image (Result), Msg); end; end if; end Check_Error; overriding function Create_Statement (Database : in Database_Connection; Table : in ADO.Schemas.Class_Mapping_Access) return Query_Statement_Access is begin return Create_Statement (Database => Database.Server, Table => Table); end Create_Statement; overriding function Create_Statement (Database : in Database_Connection; Query : in String) return Query_Statement_Access is begin return Create_Statement (Database => Database.Server, Query => Query); end Create_Statement; -- ------------------------------ -- Create a delete statement. -- ------------------------------ overriding function Create_Statement (Database : in Database_Connection; Table : in ADO.Schemas.Class_Mapping_Access) return Delete_Statement_Access is begin return Create_Statement (Database => Database.Server, Table => Table); end Create_Statement; -- ------------------------------ -- Create an insert statement. -- ------------------------------ overriding function Create_Statement (Database : in Database_Connection; Table : in ADO.Schemas.Class_Mapping_Access) return Insert_Statement_Access is begin return Create_Statement (Database => Database.Server, Table => Table); end Create_Statement; -- ------------------------------ -- Create an update statement. -- ------------------------------ overriding function Create_Statement (Database : in Database_Connection; Table : in ADO.Schemas.Class_Mapping_Access) return Update_Statement_Access is begin return Create_Statement (Database => Database.Server, Table => Table); end Create_Statement; -- ------------------------------ -- Start a transaction. -- ------------------------------ procedure Begin_Transaction (Database : in out Database_Connection) is begin -- Database.Execute ("begin transaction;"); null; end Begin_Transaction; -- ------------------------------ -- Commit the current transaction. -- ------------------------------ procedure Commit (Database : in out Database_Connection) is begin -- Database.Execute ("commit transaction;"); null; end Commit; -- ------------------------------ -- Rollback the current transaction. -- ------------------------------ procedure Rollback (Database : in out Database_Connection) is begin -- Database.Execute ("rollback transaction;"); null; end Rollback; procedure Sqlite3_Free (Arg1 : Strings.chars_ptr); pragma Import (C, sqlite3_free, "sqlite3_free"); procedure Execute (Database : in out Database_Connection; SQL : in Query_String) is use type Strings.chars_ptr; SQL_Stat : Strings.chars_ptr := Strings.New_String (SQL); Result : int; Error_Msg : Strings.chars_ptr; begin Log.Debug ("Execute: {0}", SQL); for Retry in 1 .. 100 loop Result := Sqlite3_H.sqlite3_exec (Database.Server, SQL_Stat, No_Callback, System.Null_Address, Error_Msg'Address); exit when Result /= Sqlite3_H.SQLITE_BUSY; delay 0.01 * Retry; end loop; Check_Error (Database.Server, Result); if Error_Msg /= Strings.Null_Ptr then Log.Error ("Error: {0}", Strings.Value (Error_Msg)); Sqlite3_Free (Error_Msg); end if; -- Free Strings.Free (SQL_Stat); end Execute; -- ------------------------------ -- Closes the database connection -- ------------------------------ overriding procedure Close (Database : in out Database_Connection) is pragma Unreferenced (Database); Result : int; begin Log.Info ("Close connection"); -- if Database.Count = 1 then -- Result := Sqlite3_H.sqlite3_close (Database.Server); -- Database.Server := System.Null_Address; -- end if; pragma Unreferenced (Result); end Close; -- ------------------------------ -- Releases the sqlite connection if it is open -- ------------------------------ overriding procedure Finalize (Database : in out Database_Connection) is Result : int; begin Log.Debug ("Release connection"); Database.Count := Database.Count - 1; -- if Database.Count <= 1 then -- Result := Sqlite3_H.Sqlite3_Close (Database.Server); -- end if; -- Database.Server := System.Null_Address; pragma Unreferenced (Result); end Finalize; -- ------------------------------ -- Load the database schema definition for the current database. -- ------------------------------ overriding procedure Load_Schema (Database : in Database_Connection; Schema : out ADO.Schemas.Schema_Definition) is begin ADO.Schemas.Sqlite.Load_Schema (Database, Schema); end Load_Schema; DB : ADO.Drivers.Connections.Database_Connection_Access := null; -- ------------------------------ -- Initialize the database connection manager. -- ------------------------------ procedure Create_Connection (D : in out Sqlite_Driver; Config : in Configuration'Class; Result : out ADO.Drivers.Connections.Database_Connection_Access) is pragma Unreferenced (D); use Strings; use type System.Address; Name : constant String := To_String (Config.Database); Filename : Strings.chars_ptr; Status : int; Handle : aliased System.Address; Flags : constant int := Sqlite3_H.SQLITE_OPEN_FULLMUTEX + Sqlite3_H.SQLITE_OPEN_READWRITE; begin Log.Info ("Opening database {0}", Name); if DB /= null then Result := DB; DB.Count := DB.Count + 1; return; end if; Filename := Strings.New_String (Name); Status := Sqlite3_H.sqlite3_open_v2 (Filename, Handle'Access, Flags, Strings.Null_Ptr); Strings.Free (Filename); if Status /= Sqlite3_H.SQLITE_OK then raise DB_Error; end if; declare Database : constant Database_Connection_Access := new Database_Connection; procedure Configure (Name, Item : in Util.Properties.Value); function Escape (Value : in Util.Properties.Value) return String; function Escape (Value : in Util.Properties.Value) return String is S : constant String := To_String (Value); begin if S'Length > 0 and then S (S'First) >= '0' and then S (S'First) <= '9' then return S; elsif S'Length > 0 and then S (S'First) = ''' then return S; else return "'" & S & "'"; end if; end Escape; procedure Configure (Name, Item : in Util.Properties.Value) is SQL : constant String := "PRAGMA " & To_String (Name) & "=" & Escape (Item); begin Log.Info ("Configure database with {0}", SQL); Database.Execute (SQL); end Configure; begin Database.Server := Handle; Database.Count := 2; Database.Name := Config.Database; -- Configure the connection by setting up the SQLite 'pragma X=Y' SQL commands. -- Typical configuration includes: -- synchronous=OFF -- temp_store=MEMORY -- encoding='UTF-8' Config.Properties.Iterate (Process => Configure'Access); Result := Database.all'Access; DB := Result; end; end Create_Connection; -- ------------------------------ -- Initialize the SQLite driver. -- ------------------------------ procedure Initialize is use type Util.Strings.Name_Access; begin Log.Debug ("Initializing sqlite driver"); if Driver.Name = null then Driver.Name := Driver_Name'Access; Register (Driver'Access); end if; end Initialize; end ADO.Drivers.Connections.Sqlite;
----------------------------------------------------------------------- -- ADO Sqlite Database -- SQLite Database connections -- Copyright (C) 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 Sqlite3_H; with Interfaces.C.Strings; with Util.Log; with Util.Log.Loggers; with ADO.Statements.Sqlite; with ADO.Schemas.Sqlite; package body ADO.Drivers.Connections.Sqlite is use ADO.Statements.Sqlite; use Interfaces.C; pragma Linker_Options ("-lsqlite3"); Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("ADO.Databases.Sqlite"); Driver_Name : aliased constant String := "sqlite"; Driver : aliased Sqlite_Driver; No_Callback : constant Sqlite3_H.sqlite3_callback := null; -- ------------------------------ -- Get the database driver which manages this connection. -- ------------------------------ overriding function Get_Driver (Database : in Database_Connection) return Driver_Access is pragma Unreferenced (Database); begin return Driver'Access; end Get_Driver; -- ------------------------------ -- Check for an error after executing a sqlite statement. -- ------------------------------ procedure Check_Error (Connection : in Sqlite_Access; Result : in int) is begin if Result /= Sqlite3_H.SQLITE_OK and Result /= Sqlite3_H.SQLITE_DONE then declare Error : constant Strings.chars_ptr := Sqlite3_H.sqlite3_errmsg (Connection); Msg : constant String := Strings.Value (Error); begin Log.Error ("Error {0}: {1}", int'Image (Result), Msg); end; end if; end Check_Error; overriding function Create_Statement (Database : in Database_Connection; Table : in ADO.Schemas.Class_Mapping_Access) return Query_Statement_Access is begin return Create_Statement (Database => Database.Server, Table => Table); end Create_Statement; overriding function Create_Statement (Database : in Database_Connection; Query : in String) return Query_Statement_Access is begin return Create_Statement (Database => Database.Server, Query => Query); end Create_Statement; -- ------------------------------ -- Create a delete statement. -- ------------------------------ overriding function Create_Statement (Database : in Database_Connection; Table : in ADO.Schemas.Class_Mapping_Access) return Delete_Statement_Access is begin return Create_Statement (Database => Database.Server, Table => Table); end Create_Statement; -- ------------------------------ -- Create an insert statement. -- ------------------------------ overriding function Create_Statement (Database : in Database_Connection; Table : in ADO.Schemas.Class_Mapping_Access) return Insert_Statement_Access is begin return Create_Statement (Database => Database.Server, Table => Table); end Create_Statement; -- ------------------------------ -- Create an update statement. -- ------------------------------ overriding function Create_Statement (Database : in Database_Connection; Table : in ADO.Schemas.Class_Mapping_Access) return Update_Statement_Access is begin return Create_Statement (Database => Database.Server, Table => Table); end Create_Statement; -- ------------------------------ -- Start a transaction. -- ------------------------------ procedure Begin_Transaction (Database : in out Database_Connection) is begin -- Database.Execute ("begin transaction;"); null; end Begin_Transaction; -- ------------------------------ -- Commit the current transaction. -- ------------------------------ procedure Commit (Database : in out Database_Connection) is begin -- Database.Execute ("commit transaction;"); null; end Commit; -- ------------------------------ -- Rollback the current transaction. -- ------------------------------ procedure Rollback (Database : in out Database_Connection) is begin -- Database.Execute ("rollback transaction;"); null; end Rollback; procedure Sqlite3_Free (Arg1 : Strings.chars_ptr); pragma Import (C, sqlite3_free, "sqlite3_free"); procedure Execute (Database : in out Database_Connection; SQL : in Query_String) is use type Strings.chars_ptr; SQL_Stat : Strings.chars_ptr := Strings.New_String (SQL); Result : int; Error_Msg : Strings.chars_ptr; begin Log.Debug ("Execute: {0}", SQL); for Retry in 1 .. 100 loop Result := Sqlite3_H.sqlite3_exec (Database.Server, SQL_Stat, No_Callback, System.Null_Address, Error_Msg'Address); exit when Result /= Sqlite3_H.SQLITE_BUSY; delay 0.01 * Retry; end loop; Check_Error (Database.Server, Result); if Error_Msg /= Strings.Null_Ptr then Log.Error ("Error: {0}", Strings.Value (Error_Msg)); Sqlite3_Free (Error_Msg); end if; -- Free Strings.Free (SQL_Stat); end Execute; -- ------------------------------ -- Closes the database connection -- ------------------------------ overriding procedure Close (Database : in out Database_Connection) is pragma Unreferenced (Database); Result : int; begin Log.Info ("Close connection"); -- if Database.Count = 1 then -- Result := Sqlite3_H.sqlite3_close (Database.Server); -- Database.Server := System.Null_Address; -- end if; pragma Unreferenced (Result); end Close; -- ------------------------------ -- Releases the sqlite connection if it is open -- ------------------------------ overriding procedure Finalize (Database : in out Database_Connection) is Result : int; begin Log.Debug ("Release connection"); Result := Sqlite3_H.sqlite3_close (Database.Server); Database.Server := System.Null_Address; pragma Unreferenced (Result); end Finalize; -- ------------------------------ -- Load the database schema definition for the current database. -- ------------------------------ overriding procedure Load_Schema (Database : in Database_Connection; Schema : out ADO.Schemas.Schema_Definition) is begin ADO.Schemas.Sqlite.Load_Schema (Database, Schema); end Load_Schema; DB : Ref.Ref; -- ------------------------------ -- Initialize the database connection manager. -- ------------------------------ procedure Create_Connection (D : in out Sqlite_Driver; Config : in Configuration'Class; Result : in out Ref.Ref'Class) is pragma Unreferenced (D); use Strings; use type System.Address; Name : constant String := To_String (Config.Database); Filename : Strings.chars_ptr; Status : int; Handle : aliased System.Address; Flags : constant int := Sqlite3_H.SQLITE_OPEN_FULLMUTEX + Sqlite3_H.SQLITE_OPEN_READWRITE; begin Log.Info ("Opening database {0}", Name); if not DB.Is_Null then Result := Ref.Create (DB.Value); return; end if; Filename := Strings.New_String (Name); Status := Sqlite3_H.sqlite3_open_v2 (Filename, Handle'Access, Flags, Strings.Null_Ptr); Strings.Free (Filename); if Status /= Sqlite3_H.SQLITE_OK then raise DB_Error; end if; declare Database : constant Database_Connection_Access := new Database_Connection; procedure Configure (Name, Item : in Util.Properties.Value); function Escape (Value : in Util.Properties.Value) return String; function Escape (Value : in Util.Properties.Value) return String is S : constant String := To_String (Value); begin if S'Length > 0 and then S (S'First) >= '0' and then S (S'First) <= '9' then return S; elsif S'Length > 0 and then S (S'First) = ''' then return S; else return "'" & S & "'"; end if; end Escape; procedure Configure (Name, Item : in Util.Properties.Value) is SQL : constant String := "PRAGMA " & To_String (Name) & "=" & Escape (Item); begin Log.Info ("Configure database with {0}", SQL); Database.Execute (SQL); end Configure; begin Database.Server := Handle; Database.Name := Config.Database; DB := Ref.Create (Database.all'Access); -- Configure the connection by setting up the SQLite 'pragma X=Y' SQL commands. -- Typical configuration includes: -- synchronous=OFF -- temp_store=MEMORY -- encoding='UTF-8' Config.Properties.Iterate (Process => Configure'Access); Result := Ref.Create (Database.all'Access); end; end Create_Connection; -- ------------------------------ -- Initialize the SQLite driver. -- ------------------------------ procedure Initialize is use type Util.Strings.Name_Access; begin Log.Debug ("Initializing sqlite driver"); if Driver.Name = null then Driver.Name := Driver_Name'Access; Register (Driver'Access); end if; end Initialize; end ADO.Drivers.Connections.Sqlite;
Update the Create_Connection procedure to return a reference counted value Changed the DB global to a reference counter. Update the Finalize procedure to release the SQLite database connection
Update the Create_Connection procedure to return a reference counted value Changed the DB global to a reference counter. Update the Finalize procedure to release the SQLite database connection
Ada
apache-2.0
stcarrez/ada-ado
2b6e83695923592fe9c9f88c220d50ea9be10af0
src/gen-artifacts-docs-markdown.adb
src/gen-artifacts-docs-markdown.adb
----------------------------------------------------------------------- -- gen-artifacts-docs-markdown -- Artifact for GitHub Markdown documentation format -- Copyright (C) 2015 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Strings.Fixed; with Util.Strings; with Util.Log.Loggers; package body Gen.Artifacts.Docs.Markdown is function Has_Scheme (Link : in String) return Boolean; use Util.Log; Log : constant Loggers.Logger := Loggers.Create ("Gen.Artifacts.Docs.Mark"); -- ------------------------------ -- Get the document name from the file document (ex: <name>.wiki or <name>.md). -- ------------------------------ overriding function Get_Document_Name (Formatter : in Document_Formatter; Document : in File_Document) return String is pragma Unreferenced (Formatter); begin return Ada.Strings.Unbounded.To_String (Document.Name) & ".md"; end Get_Document_Name; -- ------------------------------ -- Start a new document. -- ------------------------------ overriding procedure Start_Document (Formatter : in out Document_Formatter; Document : in File_Document; File : in Ada.Text_IO.File_Type) is pragma Unreferenced (Formatter); begin Ada.Text_IO.Put_Line (File, "# " & Ada.Strings.Unbounded.To_String (Document.Title)); Ada.Text_IO.New_Line (File); end Start_Document; -- ------------------------------ -- Return True if the link has either a http:// or a https:// scheme. -- ------------------------------ function Has_Scheme (Link : in String) return Boolean is begin if Link'Length < 8 then return False; elsif Link (Link'First .. Link'First + 6) = "http://" then return True; elsif Link (Link'First .. Link'First + 7) = "https://" then return True; else return False; end if; end Has_Scheme; function Is_Image (Link : in String) return Boolean is begin if Link'Length < 4 then return False; elsif Link (Link'Last - 3 .. Link'Last) = ".png" then return True; elsif Link (Link'Last - 3 .. Link'Last) = ".jpg" then return True; elsif Link (Link'Last - 3 .. Link'Last) = ".gif" then return True; else Log.Info ("Link {0} not an image", Link); return False; end if; end Is_Image; -- ------------------------------ -- Write a line doing some link transformation for Markdown. -- ------------------------------ procedure Write_Text (Formatter : in out Document_Formatter; File : in Ada.Text_IO.File_Type; Text : in String) is pragma Unreferenced (Formatter); Pos : Natural; Start : Natural := Text'First; End_Pos : Natural; Last_Pos : Natural; begin -- Transform links -- [Link] -> [[Link]] -- [Link Title] -> [[Title|Link]] -- -- Do not change the following links: -- [[Link|Title]] loop Pos := Util.Strings.Index (Text, '[', Start); if Pos = 0 or else Pos = Text'Last then Ada.Text_IO.Put (File, Text (Start .. Text'Last)); return; end if; Ada.Text_IO.Put (File, Text (Start .. Pos - 1)); -- Parse a markdown link format. if Text (Pos + 1) = '[' then Start := Pos + 2; Pos := Util.Strings.Index (Text, ']', Pos + 2); if Pos = 0 then if Is_Image (Text (Start .. Text'Last)) then Ada.Text_IO.Put (File, Text (Start - 2 .. Text'Last)); else Ada.Text_IO.Put (File, Text (Start - 2 .. Text'Last)); end if; return; end if; if Is_Image (Text (Start .. Pos - 1)) then Ada.Text_IO.Put (File, "![]("); Ada.Text_IO.Put (File, Text (Start .. Pos - 1)); Ada.Text_IO.Put (File, ")"); Start := Pos + 2; else Ada.Text_IO.Put (File, Text (Start .. Pos)); Start := Pos + 1; end if; else Pos := Pos + 1; End_Pos := Pos; while End_Pos < Text'Last and Text (End_Pos) /= ' ' and Text (End_Pos) /= ']' loop End_Pos := End_Pos + 1; end loop; Last_Pos := End_Pos; while Last_Pos < Text'Last and Text (Last_Pos) /= ']' loop Last_Pos := Last_Pos + 1; end loop; if Is_Image (Text (Pos .. Last_Pos - 1)) then Ada.Text_IO.Put (File, "!["); -- Ada.Text_IO.Put (File, Text (Pos .. End_Pos)); Ada.Text_IO.Put (File, "]("); Ada.Text_IO.Put (File, Text (Pos .. Last_Pos - 1)); Ada.Text_IO.Put (File, ")"); elsif Is_Image (Text (Pos .. End_Pos)) then Last_Pos := Last_Pos - 1; Ada.Text_IO.Put (File, "!["); Ada.Text_IO.Put (File, Text (Pos .. End_Pos)); Ada.Text_IO.Put (File, "]("); Ada.Text_IO.Put (File, Text (Pos .. End_Pos)); Ada.Text_IO.Put (File, ")"); elsif Has_Scheme (Text (Pos .. End_Pos)) then Ada.Text_IO.Put (File, "["); Ada.Text_IO.Put (File, Text (End_Pos + 1 .. Last_Pos)); Ada.Text_IO.Put (File, "("); Ada.Text_IO.Put (File, Ada.Strings.Fixed.Trim (Text (Pos .. End_Pos), Ada.Strings.Both)); Ada.Text_IO.Put (File, ")"); else Last_Pos := Last_Pos - 1; Ada.Text_IO.Put (File, "[["); Ada.Text_IO.Put (File, Text (End_Pos + 1 .. Last_Pos)); Ada.Text_IO.Put (File, "|"); Ada.Text_IO.Put (File, Text (Pos .. End_Pos)); Ada.Text_IO.Put (File, "]"); end if; Start := Last_Pos + 1; end if; end loop; end Write_Text; -- ------------------------------ -- Write a line in the document. -- ------------------------------ procedure Write_Line (Formatter : in out Document_Formatter; File : in Ada.Text_IO.File_Type; Line : in String) is begin if Formatter.Need_Newline then Ada.Text_IO.New_Line (File); Formatter.Need_Newline := False; end if; if Formatter.Mode = L_START_CODE and then Line'Length > 2 and then Line (Line'First .. Line'First + 1) = " " then Ada.Text_IO.Put_Line (File, Line (Line'First + 2 .. Line'Last)); elsif Formatter.Mode = L_TEXT then Formatter.Write_Text (File, Line); Ada.Text_IO.New_Line (File); else Ada.Text_IO.Put_Line (File, Line); end if; end Write_Line; -- ------------------------------ -- Write a line in the target document formatting the line if necessary. -- ------------------------------ overriding procedure Write_Line (Formatter : in out Document_Formatter; File : in Ada.Text_IO.File_Type; Line : in Line_Type) is begin case Line.Kind is when L_LIST => Ada.Text_IO.New_Line (File); Ada.Text_IO.Put (File, Line.Content); Formatter.Need_Newline := True; Formatter.Mode := Line.Kind; when L_LIST_ITEM => Ada.Text_IO.Put (File, Line.Content); Formatter.Need_Newline := True; when L_START_CODE => Formatter.Mode := Line.Kind; Formatter.Write_Line (File, "```"); when L_END_CODE => Formatter.Mode := L_TEXT; Formatter.Write_Line (File, "```"); when L_TEXT => Formatter.Write_Line (File, Line.Content); when L_HEADER_1 => Formatter.Mode := Line.Kind; Formatter.Write_Line (File, "# " & Line.Content); Formatter.Mode := L_TEXT; when L_HEADER_2 => Formatter.Mode := Line.Kind; Formatter.Write_Line (File, "## " & Line.Content); Formatter.Mode := L_TEXT; when L_HEADER_3 => Formatter.Mode := Line.Kind; Formatter.Write_Line (File, "### " & Line.Content); Formatter.Mode := L_TEXT; when L_HEADER_4 => Formatter.Mode := Line.Kind; Formatter.Write_Line (File, "#### " & Line.Content); Formatter.Mode := L_TEXT; when others => null; end case; end Write_Line; -- ------------------------------ -- Finish the document. -- ------------------------------ overriding procedure Finish_Document (Formatter : in out Document_Formatter; Document : in File_Document; File : in Ada.Text_IO.File_Type; Source : in String) is pragma Unreferenced (Formatter, Document); begin Ada.Text_IO.New_Line (File); Ada.Text_IO.Put_Line (File, "----"); Ada.Text_IO.Put_Line (File, "[Generated by Dynamo](https://github.com/stcarrez/dynamo) from *" & Source & "*"); end Finish_Document; end Gen.Artifacts.Docs.Markdown;
----------------------------------------------------------------------- -- gen-artifacts-docs-markdown -- Artifact for GitHub Markdown documentation format -- Copyright (C) 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.Fixed; with Util.Strings; with Util.Log.Loggers; package body Gen.Artifacts.Docs.Markdown is function Has_Scheme (Link : in String) return Boolean; function Is_Image (Link : in String) return Boolean; Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("Gen.Artifacts.Docs.Mark"); -- ------------------------------ -- Get the document name from the file document (ex: <name>.wiki or <name>.md). -- ------------------------------ overriding function Get_Document_Name (Formatter : in Document_Formatter; Document : in File_Document) return String is pragma Unreferenced (Formatter); begin return Ada.Strings.Unbounded.To_String (Document.Name) & ".md"; end Get_Document_Name; -- ------------------------------ -- Start a new document. -- ------------------------------ overriding procedure Start_Document (Formatter : in out Document_Formatter; Document : in File_Document; File : in Ada.Text_IO.File_Type) is pragma Unreferenced (Formatter); begin Ada.Text_IO.Put_Line (File, "# " & Ada.Strings.Unbounded.To_String (Document.Title)); Ada.Text_IO.New_Line (File); end Start_Document; -- ------------------------------ -- Return True if the link has either a http:// or a https:// scheme. -- ------------------------------ function Has_Scheme (Link : in String) return Boolean is begin if Link'Length < 8 then return False; elsif Link (Link'First .. Link'First + 6) = "http://" then return True; elsif Link (Link'First .. Link'First + 7) = "https://" then return True; else return False; end if; end Has_Scheme; function Is_Image (Link : in String) return Boolean is begin if Link'Length < 4 then return False; elsif Link (Link'Last - 3 .. Link'Last) = ".png" then return True; elsif Link (Link'Last - 3 .. Link'Last) = ".jpg" then return True; elsif Link (Link'Last - 3 .. Link'Last) = ".gif" then return True; else Log.Info ("Link {0} not an image", Link); return False; end if; end Is_Image; -- ------------------------------ -- Write a line doing some link transformation for Markdown. -- ------------------------------ procedure Write_Text (Formatter : in out Document_Formatter; File : in Ada.Text_IO.File_Type; Text : in String) is pragma Unreferenced (Formatter); Pos : Natural; Start : Natural := Text'First; End_Pos : Natural; Last_Pos : Natural; begin -- Transform links -- [Link] -> [[Link]] -- [Link Title] -> [[Title|Link]] -- -- Do not change the following links: -- [[Link|Title]] loop Pos := Util.Strings.Index (Text, '[', Start); if Pos = 0 or else Pos = Text'Last then Ada.Text_IO.Put (File, Text (Start .. Text'Last)); return; end if; Ada.Text_IO.Put (File, Text (Start .. Pos - 1)); -- Parse a markdown link format. if Text (Pos + 1) = '[' then Start := Pos + 2; Pos := Util.Strings.Index (Text, ']', Pos + 2); if Pos = 0 then if Is_Image (Text (Start .. Text'Last)) then Ada.Text_IO.Put (File, Text (Start - 2 .. Text'Last)); else Ada.Text_IO.Put (File, Text (Start - 2 .. Text'Last)); end if; return; end if; if Is_Image (Text (Start .. Pos - 1)) then Ada.Text_IO.Put (File, "![]("); Ada.Text_IO.Put (File, Text (Start .. Pos - 1)); Ada.Text_IO.Put (File, ")"); Start := Pos + 2; else Ada.Text_IO.Put (File, Text (Start .. Pos)); Start := Pos + 1; end if; else Pos := Pos + 1; End_Pos := Pos; while End_Pos < Text'Last and Text (End_Pos) /= ' ' and Text (End_Pos) /= ']' loop End_Pos := End_Pos + 1; end loop; Last_Pos := End_Pos; while Last_Pos < Text'Last and Text (Last_Pos) /= ']' loop Last_Pos := Last_Pos + 1; end loop; if Is_Image (Text (Pos .. Last_Pos - 1)) then Ada.Text_IO.Put (File, "!["); -- Ada.Text_IO.Put (File, Text (Pos .. End_Pos)); Ada.Text_IO.Put (File, "]("); Ada.Text_IO.Put (File, Text (Pos .. Last_Pos - 1)); Ada.Text_IO.Put (File, ")"); elsif Is_Image (Text (Pos .. End_Pos)) then Last_Pos := Last_Pos - 1; Ada.Text_IO.Put (File, "!["); Ada.Text_IO.Put (File, Text (Pos .. End_Pos)); Ada.Text_IO.Put (File, "]("); Ada.Text_IO.Put (File, Text (Pos .. End_Pos)); Ada.Text_IO.Put (File, ")"); elsif Has_Scheme (Text (Pos .. End_Pos)) then Ada.Text_IO.Put (File, "["); Ada.Text_IO.Put (File, Text (End_Pos + 1 .. Last_Pos)); Ada.Text_IO.Put (File, "("); Ada.Text_IO.Put (File, Ada.Strings.Fixed.Trim (Text (Pos .. End_Pos), Ada.Strings.Both)); Ada.Text_IO.Put (File, ")"); else Last_Pos := Last_Pos - 1; Ada.Text_IO.Put (File, "[["); Ada.Text_IO.Put (File, Text (End_Pos + 1 .. Last_Pos)); Ada.Text_IO.Put (File, "|"); Ada.Text_IO.Put (File, Text (Pos .. End_Pos)); Ada.Text_IO.Put (File, "]"); end if; Start := Last_Pos + 1; end if; end loop; end Write_Text; -- ------------------------------ -- Write a line in the document. -- ------------------------------ procedure Write_Line (Formatter : in out Document_Formatter; File : in Ada.Text_IO.File_Type; Line : in String) is begin if Formatter.Need_Newline then Ada.Text_IO.New_Line (File); Formatter.Need_Newline := False; end if; if Formatter.Mode = L_START_CODE and then Line'Length > 2 and then Line (Line'First .. Line'First + 1) = " " then Ada.Text_IO.Put_Line (File, Line (Line'First + 2 .. Line'Last)); elsif Formatter.Mode = L_TEXT then Formatter.Write_Text (File, Line); Ada.Text_IO.New_Line (File); else Ada.Text_IO.Put_Line (File, Line); end if; end Write_Line; -- ------------------------------ -- Write a line in the target document formatting the line if necessary. -- ------------------------------ overriding procedure Write_Line (Formatter : in out Document_Formatter; File : in Ada.Text_IO.File_Type; Line : in Line_Type) is begin case Line.Kind is when L_LIST => Ada.Text_IO.New_Line (File); Ada.Text_IO.Put (File, Line.Content); Formatter.Need_Newline := True; Formatter.Mode := Line.Kind; when L_LIST_ITEM => Ada.Text_IO.Put (File, Line.Content); Formatter.Need_Newline := True; when L_START_CODE => Formatter.Mode := Line.Kind; Formatter.Write_Line (File, "```"); when L_END_CODE => Formatter.Mode := L_TEXT; Formatter.Write_Line (File, "```"); when L_TEXT => Formatter.Write_Line (File, Line.Content); when L_HEADER_1 => Formatter.Mode := Line.Kind; Formatter.Write_Line (File, "# " & Line.Content); Formatter.Mode := L_TEXT; when L_HEADER_2 => Formatter.Mode := Line.Kind; Formatter.Write_Line (File, "## " & Line.Content); Formatter.Mode := L_TEXT; when L_HEADER_3 => Formatter.Mode := Line.Kind; Formatter.Write_Line (File, "### " & Line.Content); Formatter.Mode := L_TEXT; when L_HEADER_4 => Formatter.Mode := Line.Kind; Formatter.Write_Line (File, "#### " & Line.Content); Formatter.Mode := L_TEXT; when others => null; end case; end Write_Line; -- ------------------------------ -- Finish the document. -- ------------------------------ overriding procedure Finish_Document (Formatter : in out Document_Formatter; Document : in File_Document; File : in Ada.Text_IO.File_Type; Source : in String) is pragma Unreferenced (Formatter, Document); begin Ada.Text_IO.New_Line (File); Ada.Text_IO.Put_Line (File, "----"); Ada.Text_IO.Put_Line (File, "[Generated by Dynamo](https://github.com/stcarrez/dynamo) from *" & Source & "*"); end Finish_Document; end Gen.Artifacts.Docs.Markdown;
Fix compilation warning
Fix compilation warning
Ada
apache-2.0
stcarrez/dynamo,stcarrez/dynamo,stcarrez/dynamo
4c60a51305b9f7a3fbfa7b4e92150fbafc1f461b
src/sqlite/ado-statements-sqlite.ads
src/sqlite/ado-statements-sqlite.ads
----------------------------------------------------------------------- -- ado-statements-sqlite -- SQLite database statements -- Copyright (C) 2009, 2010, 2011, 2012, 2013, 2015, 2018 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Sqlite3_H; with ADO.Drivers.Connections.Sqlite; package ADO.Statements.Sqlite is type Handle is null record; -- ------------------------------ -- Delete statement -- ------------------------------ type Sqlite_Delete_Statement is new Delete_Statement with private; type Sqlite_Delete_Statement_Access is access all Sqlite_Delete_Statement'Class; -- Execute the query overriding procedure Execute (Stmt : in out Sqlite_Delete_Statement; Result : out Natural); -- Create the delete statement function Create_Statement (Database : access ADO.Drivers.Connections.Sqlite.Sqlite3; Table : in ADO.Schemas.Class_Mapping_Access) return Delete_Statement_Access; -- ------------------------------ -- Update statement -- ------------------------------ type Sqlite_Update_Statement is new Update_Statement with private; type Sqlite_Update_Statement_Access is access all Sqlite_Update_Statement'Class; -- Execute the query overriding procedure Execute (Stmt : in out Sqlite_Update_Statement); -- Execute the query overriding procedure Execute (Stmt : in out Sqlite_Update_Statement; Result : out Integer); -- Create an update statement function Create_Statement (Database : access ADO.Drivers.Connections.Sqlite.Sqlite3; Table : in ADO.Schemas.Class_Mapping_Access) return Update_Statement_Access; -- ------------------------------ -- Insert statement -- ------------------------------ type Sqlite_Insert_Statement is new Insert_Statement with private; type Sqlite_Insert_Statement_Access is access all Sqlite_Insert_Statement'Class; -- Execute the query overriding procedure Execute (Stmt : in out Sqlite_Insert_Statement; Result : out Integer); -- Create an insert statement. function Create_Statement (Database : access ADO.Drivers.Connections.Sqlite.Sqlite3; Table : in ADO.Schemas.Class_Mapping_Access) return Insert_Statement_Access; -- ------------------------------ -- Query statement for SQLite -- ------------------------------ type Sqlite_Query_Statement is new Query_Statement with private; type Sqlite_Query_Statement_Access is access all Sqlite_Query_Statement'Class; -- Execute the query overriding procedure Execute (Query : in out Sqlite_Query_Statement); -- Get the number of rows returned by the query overriding function Get_Row_Count (Query : in Sqlite_Query_Statement) return Natural; -- Returns True if there is more data (row) to fetch overriding function Has_Elements (Query : in Sqlite_Query_Statement) return Boolean; -- Fetch the next row overriding procedure Next (Query : in out Sqlite_Query_Statement); -- Returns true if the column <b>Column</b> is null. overriding function Is_Null (Query : in Sqlite_Query_Statement; Column : in Natural) return Boolean; -- Get the column value at position <b>Column</b> and -- return it as an <b>Int64</b>. -- Raises <b>Invalid_Type</b> if the value cannot be converted. -- Raises <b>Invalid_Column</b> if the column does not exist. overriding function Get_Int64 (Query : Sqlite_Query_Statement; Column : Natural) return Int64; -- Get the column value at position <b>Column</b> and -- return it as an <b>Unbounded_String</b>. -- Raises <b>Invalid_Type</b> if the value cannot be converted. -- Raises <b>Invalid_Column</b> if the column does not exist. overriding function Get_Unbounded_String (Query : Sqlite_Query_Statement; Column : Natural) return Unbounded_String; -- Get the column value at position <b>Column</b> and -- return it as an <b>Unbounded_String</b>. -- Raises <b>Invalid_Type</b> if the value cannot be converted. -- Raises <b>Invalid_Column</b> if the column does not exist. overriding function Get_String (Query : Sqlite_Query_Statement; Column : Natural) return String; -- Get the column value at position <b>Column</b> and -- return it as a <b>Blob</b> reference. overriding function Get_Blob (Query : in Sqlite_Query_Statement; Column : in Natural) return ADO.Blob_Ref; -- Get the column value at position <b>Column</b> and -- return it as an <b>Time</b>. -- Raises <b>Invalid_Type</b> if the value cannot be converted. -- Raises <b>Invalid_Column</b> if the column does not exist. function Get_Time (Query : Sqlite_Query_Statement; Column : Natural) return Ada.Calendar.Time; -- Get the column type -- Raises <b>Invalid_Column</b> if the column does not exist. overriding function Get_Column_Type (Query : Sqlite_Query_Statement; Column : Natural) return ADO.Schemas.Column_Type; -- Get the column name. -- Raises <b>Invalid_Column</b> if the column does not exist. overriding function Get_Column_Name (Query : in Sqlite_Query_Statement; Column : in Natural) return String; -- Get the number of columns in the result. overriding function Get_Column_Count (Query : in Sqlite_Query_Statement) return Natural; -- Deletes the query statement. overriding procedure Finalize (Query : in out Sqlite_Query_Statement); -- Create the query statement. function Create_Statement (Database : access ADO.Drivers.Connections.Sqlite.Sqlite3; Table : in ADO.Schemas.Class_Mapping_Access) return Query_Statement_Access; -- Create the query statement. function Create_Statement (Database : access ADO.Drivers.Connections.Sqlite.Sqlite3; Query : in String) return Query_Statement_Access; private type State is (HAS_ROW, HAS_MORE, DONE, ERROR); type Sqlite_Query_Statement is new Query_Statement with record This_Query : aliased ADO.SQL.Query; Connection : access ADO.Drivers.Connections.Sqlite.Sqlite3; Stmt : access Sqlite3_H.sqlite3_stmt; Counter : Natural := 1; Status : State := DONE; Max_Column : Natural; end record; type Sqlite_Delete_Statement is new Delete_Statement with record Connection : access ADO.Drivers.Connections.Sqlite.Sqlite3; Table : ADO.Schemas.Class_Mapping_Access; Delete_Query : aliased ADO.SQL.Query; end record; type Sqlite_Update_Statement is new Update_Statement with record Connection : access ADO.Drivers.Connections.Sqlite.Sqlite3; This_Query : aliased ADO.SQL.Update_Query; Table : ADO.Schemas.Class_Mapping_Access; end record; type Sqlite_Insert_Statement is new Insert_Statement with record Connection : access ADO.Drivers.Connections.Sqlite.Sqlite3; This_Query : aliased ADO.SQL.Update_Query; Table : ADO.Schemas.Class_Mapping_Access; end record; end ADO.Statements.Sqlite;
----------------------------------------------------------------------- -- ado-statements-sqlite -- SQLite database statements -- Copyright (C) 2009, 2010, 2011, 2012, 2013, 2015, 2018 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Sqlite3_H; with ADO.Drivers.Connections.Sqlite; package ADO.Statements.Sqlite is type Handle is null record; -- ------------------------------ -- Delete statement -- ------------------------------ type Sqlite_Delete_Statement is new Delete_Statement with private; type Sqlite_Delete_Statement_Access is access all Sqlite_Delete_Statement'Class; -- Execute the query overriding procedure Execute (Stmt : in out Sqlite_Delete_Statement; Result : out Natural); -- Create the delete statement function Create_Statement (Database : access ADO.Drivers.Connections.Sqlite.Sqlite3; Table : in ADO.Schemas.Class_Mapping_Access) return Delete_Statement_Access; -- ------------------------------ -- Update statement -- ------------------------------ type Sqlite_Update_Statement is new Update_Statement with private; type Sqlite_Update_Statement_Access is access all Sqlite_Update_Statement'Class; -- Execute the query overriding procedure Execute (Stmt : in out Sqlite_Update_Statement); -- Execute the query overriding procedure Execute (Stmt : in out Sqlite_Update_Statement; Result : out Integer); -- Create an update statement function Create_Statement (Database : access ADO.Drivers.Connections.Sqlite.Sqlite3; Table : in ADO.Schemas.Class_Mapping_Access) return Update_Statement_Access; -- ------------------------------ -- Insert statement -- ------------------------------ type Sqlite_Insert_Statement is new Insert_Statement with private; type Sqlite_Insert_Statement_Access is access all Sqlite_Insert_Statement'Class; -- Execute the query overriding procedure Execute (Stmt : in out Sqlite_Insert_Statement; Result : out Integer); -- Create an insert statement. function Create_Statement (Database : access ADO.Drivers.Connections.Sqlite.Sqlite3; Table : in ADO.Schemas.Class_Mapping_Access) return Insert_Statement_Access; -- ------------------------------ -- Query statement for SQLite -- ------------------------------ type Sqlite_Query_Statement is new Query_Statement with private; type Sqlite_Query_Statement_Access is access all Sqlite_Query_Statement'Class; -- Execute the query overriding procedure Execute (Query : in out Sqlite_Query_Statement); -- Get the number of rows returned by the query overriding function Get_Row_Count (Query : in Sqlite_Query_Statement) return Natural; -- Returns True if there is more data (row) to fetch overriding function Has_Elements (Query : in Sqlite_Query_Statement) return Boolean; -- Fetch the next row overriding procedure Next (Query : in out Sqlite_Query_Statement); -- Returns true if the column <b>Column</b> is null. overriding function Is_Null (Query : in Sqlite_Query_Statement; Column : in Natural) return Boolean; -- Get the column value at position <b>Column</b> and -- return it as an <b>Int64</b>. -- Raises <b>Invalid_Type</b> if the value cannot be converted. -- Raises <b>Invalid_Column</b> if the column does not exist. overriding function Get_Int64 (Query : Sqlite_Query_Statement; Column : Natural) return Int64; -- Get the column value at position <b>Column</b> and -- return it as an <b>Unbounded_String</b>. -- Raises <b>Invalid_Type</b> if the value cannot be converted. -- Raises <b>Invalid_Column</b> if the column does not exist. overriding function Get_Unbounded_String (Query : Sqlite_Query_Statement; Column : Natural) return Unbounded_String; -- Get the column value at position <b>Column</b> and -- return it as an <b>Unbounded_String</b>. -- Raises <b>Invalid_Type</b> if the value cannot be converted. -- Raises <b>Invalid_Column</b> if the column does not exist. overriding function Get_String (Query : Sqlite_Query_Statement; Column : Natural) return String; -- Get the column value at position <b>Column</b> and -- return it as a <b>Blob</b> reference. overriding function Get_Blob (Query : in Sqlite_Query_Statement; Column : in Natural) return ADO.Blob_Ref; -- Get the column value at position <b>Column</b> and -- return it as an <b>Time</b>. -- Raises <b>Invalid_Type</b> if the value cannot be converted. -- Raises <b>Invalid_Column</b> if the column does not exist. function Get_Time (Query : Sqlite_Query_Statement; Column : Natural) return Ada.Calendar.Time; -- Get the column type -- Raises <b>Invalid_Column</b> if the column does not exist. overriding function Get_Column_Type (Query : Sqlite_Query_Statement; Column : Natural) return ADO.Schemas.Column_Type; -- Get the column name. -- Raises <b>Invalid_Column</b> if the column does not exist. overriding function Get_Column_Name (Query : in Sqlite_Query_Statement; Column : in Natural) return String; -- Get the number of columns in the result. overriding function Get_Column_Count (Query : in Sqlite_Query_Statement) return Natural; -- Deletes the query statement. overriding procedure Finalize (Query : in out Sqlite_Query_Statement); -- Create the query statement. function Create_Statement (Database : access ADO.Drivers.Connections.Sqlite.Sqlite3; Table : in ADO.Schemas.Class_Mapping_Access) return Query_Statement_Access; -- Create the query statement. function Create_Statement (Database : access ADO.Drivers.Connections.Sqlite.Sqlite3; Query : in String) return Query_Statement_Access; -- Execute SQL statement. procedure Execute (Connection : access ADO.Drivers.Connections.Sqlite.Sqlite3; SQL : in String); private type State is (HAS_ROW, HAS_MORE, DONE, ERROR); type Sqlite_Query_Statement is new Query_Statement with record This_Query : aliased ADO.SQL.Query; Connection : access ADO.Drivers.Connections.Sqlite.Sqlite3; Stmt : access Sqlite3_H.sqlite3_stmt; Counter : Natural := 1; Status : State := DONE; Max_Column : Natural; end record; type Sqlite_Delete_Statement is new Delete_Statement with record Connection : access ADO.Drivers.Connections.Sqlite.Sqlite3; Table : ADO.Schemas.Class_Mapping_Access; Delete_Query : aliased ADO.SQL.Query; end record; type Sqlite_Update_Statement is new Update_Statement with record Connection : access ADO.Drivers.Connections.Sqlite.Sqlite3; This_Query : aliased ADO.SQL.Update_Query; Table : ADO.Schemas.Class_Mapping_Access; end record; type Sqlite_Insert_Statement is new Insert_Statement with record Connection : access ADO.Drivers.Connections.Sqlite.Sqlite3; This_Query : aliased ADO.SQL.Update_Query; Table : ADO.Schemas.Class_Mapping_Access; end record; end ADO.Statements.Sqlite;
Declare the Execute procedure to execute simple SQL statement
Declare the Execute procedure to execute simple SQL statement
Ada
apache-2.0
stcarrez/ada-ado
e420a1062d7eb0b97697a542bd3b4910259dc4ae
src/wiki-filters.adb
src/wiki-filters.adb
----------------------------------------------------------------------- -- wiki-filters -- Wiki filters -- 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. ----------------------------------------------------------------------- package body Wiki.Filters is -- ------------------------------ -- Add a simple node such as N_LINE_BREAK, N_HORIZONTAL_RULE or N_PARAGRAPH to the document. -- ------------------------------ procedure Add_Node (Filter : in out Filter_Type; Document : in out Wiki.Nodes.Document; Kind : in Wiki.Nodes.Simple_Node_Kind) is begin if Filter.Next /= null then Filter.Add_Node (Document, Kind); else Wiki.Nodes.Append (Document, Kind); end if; end Add_Node; -- ------------------------------ -- Add a text content with the given format to the document. -- ------------------------------ procedure Add_Text (Filter : in out Filter_Type; Document : in out Wiki.Nodes.Document; Text : in Wiki.Strings.WString; Format : in Wiki.Nodes.Format_Map) is begin if Filter.Next /= null then Filter.Add_Text (Document, Text, Format); else Wiki.Nodes.Append (Document, Text, Format); end if; end Add_Text; -- ------------------------------ -- Add a section header with the given level in the document. -- ------------------------------ procedure Add_Header (Filter : in out Filter_Type; Document : in out Wiki.Nodes.Document; Header : in Wiki.Strings.WString; Level : in Natural) is begin if Filter.Next /= null then Filter.Add_Header (Document, Header, Level); else Wiki.Nodes.Append (Document, Header, Level); end if; end Add_Header; -- ------------------------------ -- Add a line break (<br>). -- ------------------------------ overriding procedure Add_Line_Break (Document : in out Filter_Type) is begin Document.Document.Add_Line_Break; end Add_Line_Break; -- ------------------------------ -- Add a paragraph (<p>). Close the previous paragraph if any. -- The paragraph must be closed at the next paragraph or next header. -- ------------------------------ overriding procedure Add_Paragraph (Document : in out Filter_Type) is begin Document.Document.Add_Paragraph; end Add_Paragraph; -- ------------------------------ -- Add a blockquote (<blockquote>). The level indicates the blockquote nested level. -- The blockquote must be closed at the next header. -- ------------------------------ overriding procedure Add_Blockquote (Document : in out Filter_Type; Level : in Natural) is begin Document.Document.Add_Blockquote (Level); end Add_Blockquote; -- ------------------------------ -- 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. -- ------------------------------ overriding procedure Add_List_Item (Document : in out Filter_Type; Level : in Positive; Ordered : in Boolean) is begin Document.Document.Add_List_Item (Level, Ordered); end Add_List_Item; -- ------------------------------ -- Add an horizontal rule (<hr>). -- ------------------------------ overriding procedure Add_Horizontal_Rule (Document : in out Filter_Type) is begin Document.Document.Add_Horizontal_Rule; end Add_Horizontal_Rule; -- ------------------------------ -- Add a link. -- ------------------------------ overriding procedure Add_Link (Document : in out Filter_Type; Name : in Unbounded_Wide_Wide_String; Link : in Unbounded_Wide_Wide_String; Language : in Unbounded_Wide_Wide_String; Title : in Unbounded_Wide_Wide_String) is begin Document.Document.Add_Link (Name, Link, Language, Title); end Add_Link; -- ------------------------------ -- Add an image. -- ------------------------------ overriding procedure Add_Image (Document : in out Filter_Type; Link : in Unbounded_Wide_Wide_String; Alt : in Unbounded_Wide_Wide_String; Position : in Unbounded_Wide_Wide_String; Description : in Unbounded_Wide_Wide_String) is begin Document.Document.Add_Image (Link, Alt, Position, Description); end Add_Image; -- ------------------------------ -- Add a quote. -- ------------------------------ overriding procedure Add_Quote (Document : in out Filter_Type; Quote : in Unbounded_Wide_Wide_String; Link : in Unbounded_Wide_Wide_String; Language : in Unbounded_Wide_Wide_String) is begin Document.Document.Add_Quote (Quote, Link, Language); end Add_Quote; -- ------------------------------ -- Add a text block with the given format. -- ------------------------------ overriding procedure Add_Text (Document : in out Filter_Type; Text : in Unbounded_Wide_Wide_String; Format : in Wiki.Documents.Format_Map) is begin Document.Document.Add_Text (Text, Format); end Add_Text; -- ------------------------------ -- Add a text block that is pre-formatted. -- ------------------------------ overriding procedure Add_Preformatted (Document : in out Filter_Type; Text : in Unbounded_Wide_Wide_String; Format : in Unbounded_Wide_Wide_String) is begin Document.Document.Add_Preformatted (Text, Format); end Add_Preformatted; overriding procedure Start_Element (Document : in out Filter_Type; Name : in Unbounded_Wide_Wide_String; Attributes : in Wiki.Attributes.Attribute_List_Type) is begin Document.Document.Start_Element (Name, Attributes); end Start_Element; overriding procedure End_Element (Document : in out Filter_Type; Name : in Unbounded_Wide_Wide_String) is begin Document.Document.End_Element (Name); end End_Element; -- ------------------------------ -- Finish the document after complete wiki text has been parsed. -- ------------------------------ overriding procedure Finish (Document : in out Filter_Type) is begin Document.Document.Finish; end Finish; -- ------------------------------ -- Set the document reader. -- ------------------------------ procedure Set_Document (Filter : in out Filter_Type; Document : in Wiki.Documents.Document_Reader_Access) is begin Filter.Document := Document; end Set_Document; end Wiki.Filters;
----------------------------------------------------------------------- -- wiki-filters -- Wiki filters -- 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. ----------------------------------------------------------------------- package body Wiki.Filters is -- ------------------------------ -- Add a simple node such as N_LINE_BREAK, N_HORIZONTAL_RULE or N_PARAGRAPH to the document. -- ------------------------------ procedure Add_Node (Filter : in out Filter_Type; Document : in out Wiki.Nodes.Document; Kind : in Wiki.Nodes.Simple_Node_Kind) is begin if Filter.Next /= null then Filter.Add_Node (Document, Kind); else Wiki.Nodes.Append (Document, Kind); end if; end Add_Node; -- ------------------------------ -- Add a text content with the given format to the document. -- ------------------------------ procedure Add_Text (Filter : in out Filter_Type; Document : in out Wiki.Nodes.Document; Text : in Wiki.Strings.WString; Format : in Wiki.Nodes.Format_Map) is begin if Filter.Next /= null then Filter.Add_Text (Document, Text, Format); else Wiki.Nodes.Append (Document, Text, Format); end if; end Add_Text; -- ------------------------------ -- Add a section header with the given level in the document. -- ------------------------------ procedure Add_Header (Filter : in out Filter_Type; Document : in out Wiki.Nodes.Document; Header : in Wiki.Strings.WString; Level : in Natural) is begin if Filter.Next /= null then Filter.Add_Header (Document, Header, Level); else Wiki.Nodes.Append (Document, Header, Level); end if; end Add_Header; -- ------------------------------ -- Add a blockquote (<blockquote>). The level indicates the blockquote nested level. -- The blockquote must be closed at the next header. -- ------------------------------ overriding procedure Add_Blockquote (Document : in out Filter_Type; Level : in Natural) is begin Document.Document.Add_Blockquote (Level); end Add_Blockquote; -- ------------------------------ -- 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. -- ------------------------------ overriding procedure Add_List_Item (Document : in out Filter_Type; Level : in Positive; Ordered : in Boolean) is begin Document.Document.Add_List_Item (Level, Ordered); end Add_List_Item; -- ------------------------------ -- Add an horizontal rule (<hr>). -- ------------------------------ overriding procedure Add_Horizontal_Rule (Document : in out Filter_Type) is begin Document.Document.Add_Horizontal_Rule; end Add_Horizontal_Rule; -- ------------------------------ -- Add a link. -- ------------------------------ overriding procedure Add_Link (Document : in out Filter_Type; Name : in Unbounded_Wide_Wide_String; Link : in Unbounded_Wide_Wide_String; Language : in Unbounded_Wide_Wide_String; Title : in Unbounded_Wide_Wide_String) is begin Document.Document.Add_Link (Name, Link, Language, Title); end Add_Link; -- ------------------------------ -- Add an image. -- ------------------------------ overriding procedure Add_Image (Document : in out Filter_Type; Link : in Unbounded_Wide_Wide_String; Alt : in Unbounded_Wide_Wide_String; Position : in Unbounded_Wide_Wide_String; Description : in Unbounded_Wide_Wide_String) is begin Document.Document.Add_Image (Link, Alt, Position, Description); end Add_Image; -- ------------------------------ -- Add a quote. -- ------------------------------ overriding procedure Add_Quote (Document : in out Filter_Type; Quote : in Unbounded_Wide_Wide_String; Link : in Unbounded_Wide_Wide_String; Language : in Unbounded_Wide_Wide_String) is begin Document.Document.Add_Quote (Quote, Link, Language); end Add_Quote; -- ------------------------------ -- Add a text block with the given format. -- ------------------------------ overriding procedure Add_Text (Document : in out Filter_Type; Text : in Unbounded_Wide_Wide_String; Format : in Wiki.Documents.Format_Map) is begin Document.Document.Add_Text (Text, Format); end Add_Text; -- ------------------------------ -- Add a text block that is pre-formatted. -- ------------------------------ overriding procedure Add_Preformatted (Document : in out Filter_Type; Text : in Unbounded_Wide_Wide_String; Format : in Unbounded_Wide_Wide_String) is begin Document.Document.Add_Preformatted (Text, Format); end Add_Preformatted; overriding procedure Start_Element (Document : in out Filter_Type; Name : in Unbounded_Wide_Wide_String; Attributes : in Wiki.Attributes.Attribute_List_Type) is begin Document.Document.Start_Element (Name, Attributes); end Start_Element; overriding procedure End_Element (Document : in out Filter_Type; Name : in Unbounded_Wide_Wide_String) is begin Document.Document.End_Element (Name); end End_Element; -- ------------------------------ -- Finish the document after complete wiki text has been parsed. -- ------------------------------ overriding procedure Finish (Document : in out Filter_Type) is begin Document.Document.Finish; end Finish; -- ------------------------------ -- Set the document reader. -- ------------------------------ procedure Set_Document (Filter : in out Filter_Type; Document : in Wiki.Documents.Document_Reader_Access) is begin Filter.Document := Document; end Set_Document; end Wiki.Filters;
Remove Add_Line_Break and Add_Paragraph procedures
Remove Add_Line_Break and Add_Paragraph procedures
Ada
apache-2.0
stcarrez/ada-wiki,stcarrez/ada-wiki
cb8c218a6bc28189a30b49938d6933ff1839560d
src/wiki-helpers.ads
src/wiki-helpers.ads
----------------------------------------------------------------------- -- wiki-helpers -- Helper operations for wiki parsers and renderer -- 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. ----------------------------------------------------------------------- package Wiki.Helpers is pragma Preelaborate; LF : constant Wide_Wide_Character := Wide_Wide_Character'Val (16#0A#); CR : constant Wide_Wide_Character := Wide_Wide_Character'Val (16#0D#); HT : constant Wide_Wide_Character := Wide_Wide_Character'Val (16#09#); -- Returns True if the character is a space or tab. function Is_Space (C : in Wide_Wide_Character) return Boolean; -- Returns True if the character is a space, tab or a newline. function Is_Space_Or_Newline (C : in Wide_Wide_Character) return Boolean; -- Returns True if the text is a valid URL function Is_Url (Text : in Wide_Wide_String) return Boolean; -- Returns True if the extension part correspond to an image. -- Recognized extension are: .png, .gif, .jpg, .jpeg. -- The extension case is ignored. function Is_Image_Extension (Ext : in Wide_Wide_String) return Boolean; end Wiki.Helpers;
----------------------------------------------------------------------- -- wiki-helpers -- Helper operations for wiki parsers and renderer -- 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. ----------------------------------------------------------------------- package Wiki.Helpers is pragma Preelaborate; LF : constant Wide_Wide_Character := Wide_Wide_Character'Val (16#0A#); CR : constant Wide_Wide_Character := Wide_Wide_Character'Val (16#0D#); HT : constant Wide_Wide_Character := Wide_Wide_Character'Val (16#09#); -- Returns True if the character is a space or tab. function Is_Space (C : in Wide_Wide_Character) return Boolean; -- Returns True if the character is a space, tab or a newline. function Is_Space_Or_Newline (C : in Wide_Wide_Character) return Boolean; -- Returns True if the text is a valid URL function Is_Url (Text : in Wide_Wide_String) return Boolean; -- Returns True if the extension part correspond to an image. -- Recognized extension are: .png, .gif, .jpg, .jpeg. -- The extension case is ignored. function Is_Image_Extension (Ext : in Wide_Wide_String) return Boolean; -- Given the current tag on the top of the stack and the new tag that will be pushed, -- decide whether the current tag must be closed or not. -- Returns True if the current tag must be closed. function Need_Close (Tag : in Html_Tag; Current_Tag : in Html_Tag) return Boolean; end Wiki.Helpers;
Move the Need_Close internal function to the Wiki.Helpers package
Move the Need_Close internal function to the Wiki.Helpers package
Ada
apache-2.0
stcarrez/ada-wiki,stcarrez/ada-wiki
0762ee437bf8de34bf337554fa754be41839d8d5
src/wiki-plugins.ads
src/wiki-plugins.ads
----------------------------------------------------------------------- -- wiki-plugins -- Wiki plugins -- 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.Nodes; -- == Plugins == -- The <b>Wiki.Plugins</b> package defines the plugin interface that is used by the wiki -- engine to provide pluggable extensions in the Wiki. -- package Wiki.Plugins is pragma Preelaborate; type Wiki_Plugin is limited interface; type Wiki_Plugin_Access is access all Wiki_Plugin'Class; -- Expand the plugin configured with the parameters for the document. procedure Expand (Plugin : in out Wiki_Plugin; Document : in out Wiki.Nodes.Document; Params : in out Wiki.Attributes.Attribute_List_Type) is abstract; end Wiki.Plugins;
----------------------------------------------------------------------- -- wiki-plugins -- Wiki plugins -- 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.Nodes; -- == Plugins == -- The <b>Wiki.Plugins</b> package defines the plugin interface that is used by the wiki -- engine to provide pluggable extensions in the Wiki. -- package Wiki.Plugins is pragma Preelaborate; type Wiki_Plugin is limited interface; type Wiki_Plugin_Access is access all Wiki_Plugin'Class; -- Expand the plugin configured with the parameters for the document. procedure Expand (Plugin : in out Wiki_Plugin; Document : in out Wiki.Nodes.Document; Params : in out Wiki.Attributes.Attribute_List) is abstract; end Wiki.Plugins;
Rename Attribute_List_Type into Attribute_List
Rename Attribute_List_Type into Attribute_List
Ada
apache-2.0
stcarrez/ada-wiki,stcarrez/ada-wiki
1fc028c368771c2a72503ab95889f77136869cb7
src/wiki-plugins.ads
src/wiki-plugins.ads
----------------------------------------------------------------------- -- wiki-plugins -- Wiki plugins -- 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.Nodes; -- == Plugins == -- The <b>Wiki.Plugins</b> package defines the plugin interface that is used by the wiki -- engine to provide pluggable extensions in the Wiki. -- package Wiki.Plugins is pragma Preelaborate; type Wiki_Plugin is limited interface; type Wiki_Plugin_Access is access all Wiki_Plugin'Class; -- Expand the plugin configured with the parameters for the document. procedure Expand (Plugin : in out Wiki_Plugin; Document : in out Wiki.Nodes.Document; Params : in out Wiki.Attributes.Attribute_List) is abstract; end Wiki.Plugins;
----------------------------------------------------------------------- -- wiki-plugins -- Wiki plugins -- 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; -- == Plugins == -- The <b>Wiki.Plugins</b> package defines the plugin interface that is used by the wiki -- engine to provide pluggable extensions in the Wiki. -- package Wiki.Plugins is pragma Preelaborate; type Wiki_Plugin is limited interface; type Wiki_Plugin_Access is access all Wiki_Plugin'Class; -- Expand the plugin configured with the parameters for the document. procedure Expand (Plugin : in out Wiki_Plugin; Document : in out Wiki.Documents.Document; Params : in out Wiki.Attributes.Attribute_List) is abstract; end Wiki.Plugins;
Move the Document type to Wiki.Documents package
Move the Document type to Wiki.Documents package
Ada
apache-2.0
stcarrez/ada-wiki,stcarrez/ada-wiki
4affc9169e5dec0e634f542580cd1856754dd428
src/gen-commands.ads
src/gen-commands.ads
----------------------------------------------------------------------- -- gen-commands -- Commands for dynamo -- 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.Strings.Unbounded; with Ada.Containers.Ordered_Maps; with Gen.Generator; package Gen.Commands is -- ------------------------------ -- Command -- ------------------------------ type Command is abstract tagged private; type Command_Access is access all Command'Class; -- Execute the command with the arguments. procedure Execute (Cmd : in Command; Generator : in out Gen.Generator.Handler) is abstract; -- Write the help associated with the command. procedure Help (Cmd : in Command; Generator : in out Gen.Generator.Handler) is abstract; -- Write the command usage. procedure Usage (Cmd : in Command); -- Print a message on the standard output. procedure Print (Cmd : in Command; Message : in String); -- ------------------------------ -- Help Command -- ------------------------------ type Help_Command is new Command with private; -- Execute the command with the arguments. procedure Execute (Cmd : in Help_Command; Generator : in out Gen.Generator.Handler); -- Write the help associated with the command. procedure Help (Cmd : in Help_Command; Generator : in out Gen.Generator.Handler); -- Register the command under the given name. procedure Add_Command (Cmd : in Command_Access; Name : in String); -- Find the command having the given name. function Find_Command (Name : in String) return Command_Access; -- Print dynamo usage procedure Usage; -- Print dynamo short usage. procedure Short_Help_Usage; private package Command_Maps is new Ada.Containers.Ordered_Maps (Key_Type => Ada.Strings.Unbounded.Unbounded_String, Element_Type => Command_Access, "<" => Ada.Strings.Unbounded."<"); type Command is abstract tagged null record; type Help_Command is new Command with null record; end Gen.Commands;
----------------------------------------------------------------------- -- gen-commands -- Commands for dynamo -- Copyright (C) 2011, 2012, 2017 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Commands.Drivers; with Gen.Generator; package Gen.Commands is package Drivers is new Util.Commands.Drivers (Context_Type => Gen.Generator.Handler, Driver_Name => "gen-commands"); subtype Command is Drivers.Command_Type; subtype Command_Access is Drivers.Command_Access; subtype Argument_List is Util.Commands.Argument_List; Driver : Drivers.Driver_Type; -- Print dynamo usage procedure Usage; -- Print dynamo short usage. procedure Short_Help_Usage; end Gen.Commands;
Use the Util.Commands.Driver package for the command implementation
Use the Util.Commands.Driver package for the command implementation
Ada
apache-2.0
stcarrez/dynamo,stcarrez/dynamo,stcarrez/dynamo
3949814e461332b44c48e0d040539d61f1032771
awa/plugins/awa-jobs/src/awa-jobs-services.adb
awa/plugins/awa-jobs/src/awa-jobs-services.adb
----------------------------------------------------------------------- -- awa-jobs -- AWA Jobs -- Copyright (C) 2012 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Serialize.Tools; with Util.Log.Loggers; with Ada.Calendar; with Ada.Tags; with ADO.Sessions.Entities; with AWA.Users.Models; with AWA.Events.Models; with AWA.Services.Contexts; package body AWA.Jobs.Services is Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("AWA.Jobs.Services"); -- ------------------------------ -- Set the job parameter identified by the <b>Name</b> to the value given in <b>Value</b>. -- ------------------------------ procedure Set_Parameter (Job : in out Abstract_Job_Type; Name : in String; Value : in String) is begin Job.Set_Parameter (Name, Util.Beans.Objects.To_Object (Value)); end Set_Parameter; -- ------------------------------ -- Set the job parameter identified by the <b>Name</b> to the value given in <b>Value</b>. -- The value object can hold any kind of basic value type (integer, enum, date, strings). -- If the value represents a bean, the <tt>Invalid_Value</tt> exception is raised. -- ------------------------------ procedure Set_Parameter (Job : in out Abstract_Job_Type; Name : in String; Value : in Util.Beans.Objects.Object) is begin Job.Props.Include (Name, Value); Job.Props_Modified := True; end Set_Parameter; -- ------------------------------ -- Get the job parameter identified by the <b>Name</b> and convert the value into a string. -- ------------------------------ function Get_Parameter (Job : in Abstract_Job_Type; Name : in String) return String is Value : constant Util.Beans.Objects.Object := Job.Get_Parameter (Name); begin return Util.Beans.Objects.To_String (Value); end Get_Parameter; -- ------------------------------ -- Get the job parameter identified by the <b>Name</b> and return it as a typed object. -- ------------------------------ function Get_Parameter (Job : in Abstract_Job_Type; Name : in String) return Util.Beans.Objects.Object is begin return Job.Props.Element (Name); end Get_Parameter; -- ------------------------------ -- Get the job status. -- ------------------------------ function Get_Status (Job : in Abstract_Job_Type) return AWA.Jobs.Models.Job_Status_Type is begin return Job.Job.Get_Status; end Get_Status; -- ------------------------------ -- Set the job status. -- When the job is terminated, it is closed and the job parameters or results cannot be -- changed. -- ------------------------------ procedure Set_Status (Job : in out Abstract_Job_Type; Status : in AWA.Jobs.Models.Job_Status_Type) is begin case Job.Job.Get_Status is when AWA.Jobs.Models.CANCELED | Models.FAILED | Models.TERMINATED => raise Closed_Error; when Models.SCHEDULED | Models.RUNNING => Job.Job.Set_Status (Status); end case; end Set_Status; -- ------------------------------ -- Save the job information in the database. Use the database session defined by <b>DB</b> -- to save the job. -- ------------------------------ procedure Save (Job : in out Abstract_Job_Type; DB : in out ADO.Sessions.Master_Session'Class) is begin if Job.Results_Modified then Job.Job.Set_Results (Util.Serialize.Tools.To_JSON (Job.Results)); Job.Results_Modified := False; end if; Job.Job.Save (DB); end Save; -- Schedule the job. procedure Schedule (Job : in out Abstract_Job_Type; Definition : in Job_Factory'Class) is Ctx : constant AWA.Services.Contexts.Service_Context_Access := AWA.Services.Contexts.Current; DB : ADO.Sessions.Master_Session := AWA.Services.Contexts.Get_Master_Session (Ctx); Msg : AWA.Events.Models.Message_Ref; User : constant AWA.Users.Models.User_Ref := Ctx.Get_User; Sess : constant AWA.Users.Models.Session_Ref := Ctx.Get_User_Session; begin if Job.Job.Is_Inserted then Log.Error ("Job is already scheduled"); raise Schedule_Error with "The job is already scheduled."; end if; Job.Job.Set_Create_Date (Ada.Calendar.Clock); DB.Begin_Transaction; Job.Job.Set_Name (Definition.Get_Name); Job.Job.Set_User (User); Job.Job.Set_Session (Sess); Job.Save (DB); -- Create the event -- Msg.Set_Message_Type Msg.Set_Parameters (Util.Serialize.Tools.To_JSON (Job.Props)); Msg.Set_Create_Date (Job.Job.Get_Create_Date); Msg.Set_User (User); Msg.Set_Session (Sess); Msg.Set_Status (AWA.Events.Models.QUEUED); Msg.Set_Entity_Id (Job.Job.Get_Id); Msg.Set_Entity_Type (ADO.Sessions.Entities.Find_Entity_Type (Session => DB, Object => Job.Job.Get_Key)); Msg.Save (DB); Job.Job.Set_Event (Msg); Job.Job.Save (DB); DB.Commit; end Schedule; function Get_Name (Factory : in Job_Factory'Class) return String is begin return Ada.Tags.Expanded_Name (Factory'Tag); end Get_Name; procedure Set_Work (Job : in out Job_Type; Work : in Work_Factory'Class) is begin Job.Work := Work.Work; Job.Job.Set_Name (Work.Get_Name); end Set_Work; procedure Execute (Job : in out Job_Type) is begin Job.Work (Job); end Execute; overriding function Create (Factory : in Work_Factory) return Abstract_Job_Access is begin return new Job_Type '(Ada.Finalization.Limited_Controlled with Work => Factory.Work, others => <>); end Create; -- ------------------------------ -- Job Declaration -- ------------------------------ -- The <tt>Definition</tt> package must be instantiated with a given job type to -- register the new job definition. package body Definition is function Create (Factory : in Job_Type_Factory) return Abstract_Job_Access is pragma Unreferenced (Factory); begin return new T; end Create; end Definition; end AWA.Jobs.Services;
----------------------------------------------------------------------- -- awa-jobs -- AWA Jobs -- Copyright (C) 2012 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Serialize.Tools; with Util.Log.Loggers; with Ada.Tags; with ADO.Sessions.Entities; with AWA.Users.Models; with AWA.Events.Models; with AWA.Services.Contexts; with AWA.Jobs.Modules; with AWA.Applications; with AWA.Events.Services; package body AWA.Jobs.Services is Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("AWA.Jobs.Services"); -- ------------------------------ -- Set the job parameter identified by the <b>Name</b> to the value given in <b>Value</b>. -- ------------------------------ procedure Set_Parameter (Job : in out Abstract_Job_Type; Name : in String; Value : in String) is begin Job.Set_Parameter (Name, Util.Beans.Objects.To_Object (Value)); end Set_Parameter; -- ------------------------------ -- Set the job parameter identified by the <b>Name</b> to the value given in <b>Value</b>. -- The value object can hold any kind of basic value type (integer, enum, date, strings). -- If the value represents a bean, the <tt>Invalid_Value</tt> exception is raised. -- ------------------------------ procedure Set_Parameter (Job : in out Abstract_Job_Type; Name : in String; Value : in Util.Beans.Objects.Object) is begin Job.Props.Include (Name, Value); Job.Props_Modified := True; end Set_Parameter; -- ------------------------------ -- Get the job parameter identified by the <b>Name</b> and convert the value into a string. -- ------------------------------ function Get_Parameter (Job : in Abstract_Job_Type; Name : in String) return String is Value : constant Util.Beans.Objects.Object := Job.Get_Parameter (Name); begin return Util.Beans.Objects.To_String (Value); end Get_Parameter; -- ------------------------------ -- Get the job parameter identified by the <b>Name</b> and return it as a typed object. -- ------------------------------ function Get_Parameter (Job : in Abstract_Job_Type; Name : in String) return Util.Beans.Objects.Object is begin return Job.Props.Element (Name); end Get_Parameter; -- ------------------------------ -- Get the job status. -- ------------------------------ function Get_Status (Job : in Abstract_Job_Type) return AWA.Jobs.Models.Job_Status_Type is begin return Job.Job.Get_Status; end Get_Status; -- ------------------------------ -- Set the job status. -- When the job is terminated, it is closed and the job parameters or results cannot be -- changed. -- ------------------------------ procedure Set_Status (Job : in out Abstract_Job_Type; Status : in AWA.Jobs.Models.Job_Status_Type) is begin case Job.Job.Get_Status is when AWA.Jobs.Models.CANCELED | Models.FAILED | Models.TERMINATED => raise Closed_Error; when Models.SCHEDULED | Models.RUNNING => Job.Job.Set_Status (Status); end case; end Set_Status; -- ------------------------------ -- Save the job information in the database. Use the database session defined by <b>DB</b> -- to save the job. -- ------------------------------ procedure Save (Job : in out Abstract_Job_Type; DB : in out ADO.Sessions.Master_Session'Class) is begin if Job.Results_Modified then Job.Job.Set_Results (Util.Serialize.Tools.To_JSON (Job.Results)); Job.Results_Modified := False; end if; Job.Job.Save (DB); end Save; -- Schedule the job. procedure Schedule (Job : in out Abstract_Job_Type; Definition : in Job_Factory'Class) is procedure Set_Event (Manager : in out AWA.Events.Services.Event_Manager); Ctx : constant AWA.Services.Contexts.Service_Context_Access := AWA.Services.Contexts.Current; DB : ADO.Sessions.Master_Session := AWA.Services.Contexts.Get_Master_Session (Ctx); Msg : AWA.Events.Models.Message_Ref; User : constant AWA.Users.Models.User_Ref := Ctx.Get_User; Sess : constant AWA.Users.Models.Session_Ref := Ctx.Get_User_Session; App : constant AWA.Applications.Application_Access := Ctx.Get_Application; procedure Set_Event (Manager : in out AWA.Events.Services.Event_Manager) is begin Manager.Set_Message_Type (Msg, Job_Create_Event.Kind); Manager.Set_Event_Queue (Msg, "job-queue"); end Set_Event; begin if Job.Job.Is_Inserted then Log.Error ("Job is already scheduled"); raise Schedule_Error with "The job is already scheduled."; end if; AWA.Jobs.Modules.Create_Event (Msg); Job.Job.Set_Create_Date (Msg.Get_Create_Date); DB.Begin_Transaction; Job.Job.Set_Name (Definition.Get_Name); Job.Job.Set_User (User); Job.Job.Set_Session (Sess); Job.Save (DB); -- Create the event Msg.Set_Parameters (Util.Serialize.Tools.To_JSON (Job.Props)); App.Do_Event_Manager (Process => Set_Event'Access); Msg.Set_User (User); Msg.Set_Session (Sess); Msg.Set_Entity_Id (Job.Job.Get_Id); Msg.Set_Entity_Type (ADO.Sessions.Entities.Find_Entity_Type (Session => DB, Object => Job.Job.Get_Key)); Msg.Save (DB); Job.Job.Set_Event (Msg); Job.Job.Save (DB); DB.Commit; end Schedule; function Get_Name (Factory : in Job_Factory'Class) return String is begin return Ada.Tags.Expanded_Name (Factory'Tag); end Get_Name; procedure Set_Work (Job : in out Job_Type; Work : in Work_Factory'Class) is begin Job.Work := Work.Work; Job.Job.Set_Name (Work.Get_Name); end Set_Work; procedure Execute (Job : in out Job_Type) is begin Job.Work (Job); end Execute; overriding function Create (Factory : in Work_Factory) return Abstract_Job_Access is begin return new Job_Type '(Ada.Finalization.Limited_Controlled with Work => Factory.Work, others => <>); end Create; -- ------------------------------ -- Job Declaration -- ------------------------------ -- The <tt>Definition</tt> package must be instantiated with a given job type to -- register the new job definition. package body Definition is function Create (Factory : in Job_Type_Factory) return Abstract_Job_Access is pragma Unreferenced (Factory); begin return new T; end Create; end Definition; end AWA.Jobs.Services;
Fix creation of database job record
Fix creation of database job record
Ada
apache-2.0
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
07398ff97026cc3ebd7e77126133c59327b40600
awa/src/awa-components-wikis.ads
awa/src/awa-components-wikis.ads
----------------------------------------------------------------------- -- awa-components-wikis -- Wiki rendering component -- Copyright (C) 2011, 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 Util.Beans.Basic; with Util.Beans.Objects; with ASF.Contexts.Faces; with ASF.Components; with ASF.Components.Html; with Wiki.Strings; with Wiki.Render; with Wiki.Plugins; with Wiki.Render.Links; package AWA.Components.Wikis is use ASF.Contexts.Faces; -- The wiki format of the wiki text. The valid values are: -- dotclear, google, creole, phpbb, mediawiki FORMAT_NAME : constant String := "format"; VALUE_NAME : constant String := ASF.Components.VALUE_NAME; -- The link renderer bean that controls the generation of page and image links. LINKS_NAME : constant String := "links"; -- The plugin factory bean that must be used for Wiki plugins. PLUGINS_NAME : constant String := "plugins"; -- ------------------------------ -- Wiki component -- ------------------------------ -- -- <awa:wiki value="wiki-text" format="dotclear|google|creole|phpbb" styleClass="class"/> -- type UIWiki is new ASF.Components.Html.UIHtmlComponent with null record; type UIWiki_Access is access all UIWiki'Class; -- Get the wiki format style. The format style is obtained from the <b>format</b> -- attribute name. function Get_Wiki_Style (UI : in UIWiki; Context : in Faces_Context'Class) return Wiki.Wiki_Syntax; -- Get the links renderer that must be used to render image and page links. function Get_Links_Renderer (UI : in UIWiki; Context : in Faces_Context'Class) return Wiki.Render.Links.Link_Renderer_Access; -- Get the plugin factory that must be used by the Wiki parser. function Get_Plugin_Factory (UI : in UIWiki; Context : in Faces_Context'Class) return Wiki.Plugins.Plugin_Factory_Access; -- Render the wiki text overriding procedure Encode_Begin (UI : in UIWiki; Context : in out Faces_Context'Class); use Ada.Strings.Wide_Wide_Unbounded; IMAGE_PREFIX_ATTR : constant String := "image_prefix"; PAGE_PREFIX_ATTR : constant String := "page_prefix"; type Link_Renderer_Bean is new Util.Beans.Basic.Bean and Wiki.Render.Links.Link_Renderer with record Page_Prefix : Unbounded_Wide_Wide_String; Image_Prefix : Unbounded_Wide_Wide_String; end record; -- Make a link adding a prefix unless the link is already absolute. procedure Make_Link (Renderer : in Link_Renderer_Bean; Link : in Wiki.Strings.WString; Prefix : in Unbounded_Wide_Wide_String; URI : out Unbounded_Wide_Wide_String); -- Get the value identified by the name. overriding function Get_Value (From : in Link_Renderer_Bean; Name : in String) return Util.Beans.Objects.Object; -- Set the value identified by the name. overriding procedure Set_Value (From : in out Link_Renderer_Bean; Name : in String; Value : in Util.Beans.Objects.Object); -- Get the image link that must be rendered from the wiki image link. overriding procedure Make_Image_Link (Renderer : in out Link_Renderer_Bean; Link : in Wiki.Strings.WString; 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 out Link_Renderer_Bean; Link : in Wiki.Strings.WString; URI : out Unbounded_Wide_Wide_String; Exists : out Boolean); private function Starts_With (Content : in Unbounded_Wide_Wide_String; Item : in String) return Boolean; end AWA.Components.Wikis;
----------------------------------------------------------------------- -- awa-components-wikis -- Wiki rendering component -- Copyright (C) 2011, 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 Util.Beans.Basic; with Util.Beans.Objects; with ASF.Contexts.Faces; with ASF.Components; with ASF.Components.Html; with Wiki.Strings; with Wiki.Render; with Wiki.Plugins; with Wiki.Render.Links; package AWA.Components.Wikis is use ASF.Contexts.Faces; -- The wiki format of the wiki text. The valid values are: -- dotclear, google, creole, phpbb, mediawiki FORMAT_NAME : constant String := "format"; VALUE_NAME : constant String := ASF.Components.VALUE_NAME; -- The link renderer bean that controls the generation of page and image links. LINKS_NAME : constant String := "links"; -- The plugin factory bean that must be used for Wiki plugins. PLUGINS_NAME : constant String := "plugins"; -- Whether the TOC is rendered in the document. TOC_NAME : constant String := "toc"; -- ------------------------------ -- Wiki component -- ------------------------------ -- -- <awa:wiki value="wiki-text" format="dotclear|google|creole|phpbb" styleClass="class"/> -- type UIWiki is new ASF.Components.Html.UIHtmlComponent with null record; type UIWiki_Access is access all UIWiki'Class; -- Get the wiki format style. The format style is obtained from the <b>format</b> -- attribute name. function Get_Wiki_Style (UI : in UIWiki; Context : in Faces_Context'Class) return Wiki.Wiki_Syntax; -- Get the links renderer that must be used to render image and page links. function Get_Links_Renderer (UI : in UIWiki; Context : in Faces_Context'Class) return Wiki.Render.Links.Link_Renderer_Access; -- Get the plugin factory that must be used by the Wiki parser. function Get_Plugin_Factory (UI : in UIWiki; Context : in Faces_Context'Class) return Wiki.Plugins.Plugin_Factory_Access; -- Render the wiki text overriding procedure Encode_Begin (UI : in UIWiki; Context : in out Faces_Context'Class); use Ada.Strings.Wide_Wide_Unbounded; IMAGE_PREFIX_ATTR : constant String := "image_prefix"; PAGE_PREFIX_ATTR : constant String := "page_prefix"; type Link_Renderer_Bean is new Util.Beans.Basic.Bean and Wiki.Render.Links.Link_Renderer with record Page_Prefix : Unbounded_Wide_Wide_String; Image_Prefix : Unbounded_Wide_Wide_String; end record; -- Make a link adding a prefix unless the link is already absolute. procedure Make_Link (Renderer : in Link_Renderer_Bean; Link : in Wiki.Strings.WString; Prefix : in Unbounded_Wide_Wide_String; URI : out Unbounded_Wide_Wide_String); -- Get the value identified by the name. overriding function Get_Value (From : in Link_Renderer_Bean; Name : in String) return Util.Beans.Objects.Object; -- Set the value identified by the name. overriding procedure Set_Value (From : in out Link_Renderer_Bean; Name : in String; Value : in Util.Beans.Objects.Object); -- Get the image link that must be rendered from the wiki image link. overriding procedure Make_Image_Link (Renderer : in out Link_Renderer_Bean; Link : in Wiki.Strings.WString; 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 out Link_Renderer_Bean; Link : in Wiki.Strings.WString; URI : out Unbounded_Wide_Wide_String; Exists : out Boolean); private function Starts_With (Content : in Unbounded_Wide_Wide_String; Item : in String) return Boolean; end AWA.Components.Wikis;
Declare TOC_NAME constant
Declare TOC_NAME constant
Ada
apache-2.0
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
ad4edf0b020a44410f174a1055226bc34ed6785e
src/wiki-helpers.adb
src/wiki-helpers.adb
----------------------------------------------------------------------- -- wiki-helpers -- Helper operations for wiki parsers and renderer -- Copyright (C) 2016, 2020, 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.Wide_Wide_Characters.Handling; with Ada.Wide_Wide_Characters.Unicode; package body Wiki.Helpers is -- ------------------------------ -- Returns True if the character is a space or tab. -- ------------------------------ function Is_Space (C : in Wiki.Strings.WChar) return Boolean is begin return Ada.Wide_Wide_Characters.Handling.Is_Space (C) or C = HT or C = NBSP; end Is_Space; -- ------------------------------ -- Returns True if the character is a space, tab or a newline. -- ------------------------------ function Is_Space_Or_Newline (C : in Wiki.Strings.WChar) return Boolean is begin return Is_Space (C) or Ada.Wide_Wide_Characters.Handling.Is_Line_Terminator (C); end Is_Space_Or_Newline; -- ------------------------------ -- Returns True if the character is a punctuation character. -- ------------------------------ function Is_Punctuation (C : in Wiki.Strings.WChar) return Boolean is begin return Ada.Wide_Wide_Characters.Unicode.Is_Punctuation (C); end Is_Punctuation; -- ------------------------------ -- Returns True if the character is a line terminator. -- ------------------------------ function Is_Newline (C : in Wiki.Strings.WChar) return Boolean is begin return Ada.Wide_Wide_Characters.Handling.Is_Line_Terminator (C); end Is_Newline; -- ------------------------------ -- Returns True if the text is a valid URL -- ------------------------------ function Is_Url (Text : in Wiki.Strings.WString) return Boolean is begin if Text'Length <= 9 then return False; else return Text (Text'First .. Text'First + 6) = "http://" or Text (Text'First .. Text'First + 7) = "https://"; end if; end Is_Url; -- ------------------------------ -- Returns True if the extension part correspond to an image. -- Recognized extension are: .png, .gif, .jpg, .jpeg. -- The extension case is ignored. -- ------------------------------ function Is_Image_Extension (Ext : in Wiki.Strings.WString) return Boolean is S : constant Wiki.Strings.WString := Ada.Wide_Wide_Characters.Handling.To_Lower (Ext); begin return S = ".png" or S = ".jpg" or S = ".gif" or S = ".jpeg"; end Is_Image_Extension; -- ------------------------------ -- Given the current tag on the top of the stack and the new tag that will be pushed, -- decide whether the current tag must be closed or not. -- Returns True if the current tag must be closed. -- ------------------------------ function Need_Close (Tag : in Html_Tag; Current_Tag : in Html_Tag) return Boolean is begin if No_End_Tag (Current_Tag) then return True; elsif Current_Tag = Tag and Tag_Omission (Current_Tag) then return True; else case Current_Tag is when DT_TAG | DD_TAG => return Tag = DD_TAG or Tag = DL_TAG or Tag = DT_TAG; when TD_TAG => return Tag = TD_TAG or Tag = TR_TAG or Tag = TH_TAG; when TR_TAG => return False; when others => return False; end case; end if; end Need_Close; -- ------------------------------ -- Get the dimension represented by the string. The string has one of the following -- formats: -- original -> Width, Height := Natural'Last -- default -> Width := 800, Height := 0 -- upright -> Width := 800, Height := 0 -- <width>px -> Width := <width>, Height := 0 -- x<height>px -> Width := 0, Height := <height> -- <width>x<height>px -> Width := <width>, Height := <height> -- ------------------------------ procedure Get_Sizes (Dimension : in Wiki.Strings.WString; Width : out Natural; Height : out Natural) is Pos : Natural; Last : Natural; begin if Dimension = "original" then Width := Natural'Last; Height := Natural'Last; elsif Dimension = "default" or Dimension = "upright" then Width := 800; Height := 0; else Pos := Wiki.Strings.Index (Dimension, "x"); Last := Wiki.Strings.Index (Dimension, "px"); if Pos > Dimension'First and Last + 1 /= Pos then Width := Natural'Wide_Wide_Value (Dimension (Dimension'First .. Pos - 1)); elsif Last > 0 then Width := Natural'Wide_Wide_Value (Dimension (Dimension'First .. Last - 1)); else Width := 0; end if; if Pos < Dimension'Last then Height := Natural'Wide_Wide_Value (Dimension (Pos + 1 .. Last - 1)); else Height := 0; end if; end if; exception when Constraint_Error => Width := 0; Height := 0; end Get_Sizes; -- ------------------------------ -- Find the position of the first non space character in the text starting at the -- given position. Returns Text'Last + 1 if the text only contains spaces. -- ------------------------------ function Skip_Spaces (Text : in Wiki.Strings.Wstring; From : in Positive) return Positive is Pos : Positive := From; begin while Pos <= Text'Last and then Is_Space (Text (Pos)) loop Pos := Pos + 1; end loop; return Pos; end Skip_Spaces; end Wiki.Helpers;
----------------------------------------------------------------------- -- wiki-helpers -- Helper operations for wiki parsers and renderer -- Copyright (C) 2016, 2020, 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.Wide_Wide_Characters.Handling; with Ada.Wide_Wide_Characters.Unicode; package body Wiki.Helpers is -- ------------------------------ -- Returns True if the character is a space or tab. -- ------------------------------ function Is_Space (C : in Wiki.Strings.WChar) return Boolean is begin return Ada.Wide_Wide_Characters.Handling.Is_Space (C) or C = HT or C = NBSP; end Is_Space; -- ------------------------------ -- Returns True if the character is a space, tab or a newline. -- ------------------------------ function Is_Space_Or_Newline (C : in Wiki.Strings.WChar) return Boolean is begin return Is_Space (C) or Ada.Wide_Wide_Characters.Handling.Is_Line_Terminator (C); end Is_Space_Or_Newline; -- ------------------------------ -- Returns True if the character is a punctuation character. -- ------------------------------ function Is_Punctuation (C : in Wiki.Strings.WChar) return Boolean is begin return Ada.Wide_Wide_Characters.Unicode.Is_Punctuation (C); end Is_Punctuation; -- ------------------------------ -- Returns True if the character is a line terminator. -- ------------------------------ function Is_Newline (C : in Wiki.Strings.WChar) return Boolean is begin return Ada.Wide_Wide_Characters.Handling.Is_Line_Terminator (C); end Is_Newline; -- ------------------------------ -- Returns True if the text is a valid URL -- ------------------------------ function Is_Url (Text : in Wiki.Strings.WString) return Boolean is begin if Text'Length <= 9 then return False; else return Text (Text'First .. Text'First + 6) = "http://" or Text (Text'First .. Text'First + 7) = "https://"; end if; end Is_Url; -- ------------------------------ -- Returns True if the extension part correspond to an image. -- Recognized extension are: .png, .gif, .jpg, .jpeg. -- The extension case is ignored. -- ------------------------------ function Is_Image_Extension (Ext : in Wiki.Strings.WString) return Boolean is S : constant Wiki.Strings.WString := Ada.Wide_Wide_Characters.Handling.To_Lower (Ext); begin return S = ".png" or S = ".jpg" or S = ".gif" or S = ".jpeg"; end Is_Image_Extension; -- ------------------------------ -- Given the current tag on the top of the stack and the new tag that will be pushed, -- decide whether the current tag must be closed or not. -- Returns True if the current tag must be closed. -- ------------------------------ function Need_Close (Tag : in Html_Tag; Current_Tag : in Html_Tag) return Boolean is begin if No_End_Tag (Current_Tag) then return True; elsif Current_Tag = Tag and Tag_Omission (Current_Tag) then return True; else case Current_Tag is when DT_TAG | DD_TAG => return Tag = DD_TAG or Tag = DL_TAG or Tag = DT_TAG; when TD_TAG => return Tag = TD_TAG or Tag = TR_TAG or Tag = TH_TAG; when TR_TAG => return False; when others => return False; end case; end if; end Need_Close; -- ------------------------------ -- Get the dimension represented by the string. The string has one of the following -- formats: -- original -> Width, Height := Natural'Last -- default -> Width := 800, Height := 0 -- upright -> Width := 800, Height := 0 -- <width>px -> Width := <width>, Height := 0 -- x<height>px -> Width := 0, Height := <height> -- <width>x<height>px -> Width := <width>, Height := <height> -- ------------------------------ procedure Get_Sizes (Dimension : in Wiki.Strings.WString; Width : out Natural; Height : out Natural) is Pos : Natural; Last : Natural; begin if Dimension = "original" then Width := Natural'Last; Height := Natural'Last; elsif Dimension = "default" or Dimension = "upright" then Width := 800; Height := 0; else Pos := Wiki.Strings.Index (Dimension, "x"); Last := Wiki.Strings.Index (Dimension, "px"); if Pos > Dimension'First and Last + 1 /= Pos then Width := Natural'Wide_Wide_Value (Dimension (Dimension'First .. Pos - 1)); elsif Last > 0 then Width := Natural'Wide_Wide_Value (Dimension (Dimension'First .. Last - 1)); else Width := 0; end if; if Pos < Dimension'Last then Height := Natural'Wide_Wide_Value (Dimension (Pos + 1 .. Last - 1)); else Height := 0; end if; end if; exception when Constraint_Error => Width := 0; Height := 0; end Get_Sizes; -- ------------------------------ -- Find the position of the first non space character in the text starting at the -- given position. Returns Text'Last + 1 if the text only contains spaces. -- ------------------------------ function Skip_Spaces (Text : in Wiki.Strings.Wstring; From : in Positive) return Positive is Pos : Positive := From; begin while Pos <= Text'Last and then Is_Space (Text (Pos)) loop Pos := Pos + 1; end loop; return Pos; end Skip_Spaces; -- ------------------------------ -- Find the position of the last non space character scanning the text backward -- from the given position. Returns Text'First - 1 if the text only contains spaces. -- ------------------------------ function Trim_Spaces (Text : in Wiki.Strings.Wstring; From : in Positive) return Natural is Pos : Natural := From; begin while Pos >= Text'First and then Is_Space (Text (Pos)) loop Pos := Pos - 1; end loop; return Pos; end Trim_Spaces; end Wiki.Helpers;
Implement Trim_Spaces function
Implement Trim_Spaces function
Ada
apache-2.0
stcarrez/ada-wiki,stcarrez/ada-wiki
c9b3b3b6dd4e569539b721b7123b61b2b9975f4d
src/wiki-parsers.ads
src/wiki-parsers.ads
----------------------------------------------------------------------- -- wiki-parsers -- Wiki parser -- Copyright (C) 2011, 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.Attributes; with Wiki.Plugins; with Wiki.Filters; with Wiki.Strings; with Wiki.Documents; with Wiki.Streams; -- === Wiki Parsers === -- The <b>Wikis.Parsers</b> package implements a parser for several well known wiki formats -- but also for HTML. While reading the input, the parser populates a wiki <tt>Document</tt> -- instance with headers, paragraphs, links, and other elements. -- -- Doc : Wiki.Documents.Document; -- Engine : Wiki.Parsers.Parser; -- -- Before using the parser, it must be configured to choose the syntax by using the -- <tt>Set_Syntax</tt> procedure: -- -- Engine.Set_Syntax (Wiki.SYNTAX_HTML); -- -- The parser can be configured to use filters. A filter is added by using the -- <tt>Add_Filter</tt> procedure. A filter is added at begining of the chain so that -- the filter added last is called first. -- -- The <tt>Parse</tt> procedure is then used to parse either a string content or some stream -- represented by the <tt>Input_Stream</tt> interface. After the <tt>Parse</tt> procedure -- completes, the <tt>Document</tt> instance holds the wiki document. -- -- Engine.Parse (Some_Text, Doc); -- package Wiki.Parsers is pragma Preelaborate; type Parser is tagged limited private; -- Add the plugin to the wiki engine. procedure Add_Plugin (Engine : in out Parser; Name : in String; Plugin : in Wiki.Plugins.Wiki_Plugin_Access); -- Set the wiki syntax that the wiki engine must use. procedure Set_Syntax (Engine : in out Parser; Syntax : in Wiki_Syntax := SYNTAX_MIX); -- Add a filter in the wiki engine. procedure Add_Filter (Engine : in out Parser; Filter : in Wiki.Filters.Filter_Type_Access); -- Parse the wiki text contained in <b>Text</b> according to the wiki syntax -- defined on the parser. procedure Parse (Engine : in out Parser; Text : in Wiki.Strings.WString; Doc : in out Wiki.Documents.Document); -- Parse the wiki stream managed by <tt>Stream</tt> according to the wiki syntax configured -- on the wiki engine. procedure Parse (Engine : in out Parser; Stream : in Wiki.Streams.Input_Stream_Access; Doc : in out Wiki.Documents.Document); private type Parser_Handler is access procedure (P : in out Parser; Token : in Wiki.Strings.WChar); type Parser_Table is array (0 .. 127) of Parser_Handler; type Parser_Table_Access is access constant Parser_Table; type Parser is tagged limited record Pending : Wiki.Strings.WChar; Has_Pending : Boolean; Syntax : Wiki_Syntax; Previous_Syntax : Wiki_Syntax; Table : Parser_Table_Access; Document : Wiki.Documents.Document; Filters : Wiki.Filters.Filter_Chain; Format : Wiki.Format_Map; Text : Wiki.Strings.BString (512); Token : Wiki.Strings.BString (512); Empty_Line : Boolean := True; Is_Eof : Boolean := False; In_Paragraph : Boolean := False; In_List : Boolean := False; Need_Paragraph : Boolean := True; Link_Double_Bracket : Boolean := False; Is_Dotclear : Boolean := False; Link_Title_First : Boolean := False; Check_Image_Link : Boolean := False; Header_Offset : Integer := 0; Quote_Level : Natural := 0; Escape_Char : Wiki.Strings.WChar; List_Level : Natural := 0; Reader : Wiki.Streams.Input_Stream_Access := null; Attributes : Wiki.Attributes.Attribute_List; end record; -- Peek the next character from the wiki text buffer. procedure Peek (P : in out Parser; Token : out Wiki.Strings.WChar); -- Put back the character so that it will be returned by the next call to Peek. procedure Put_Back (P : in out Parser; Token : in Wiki.Strings.WChar); -- Skip all the spaces and tabs as well as end of the current line (CR+LF). procedure Skip_End_Of_Line (P : in out Parser); -- Skip white spaces and tabs. procedure Skip_Spaces (P : in out Parser); -- Flush the wiki text that was collected in the text buffer. procedure Flush_Text (P : in out Parser); -- Flush the wiki dl/dt/dd definition list. procedure Flush_List (P : in out Parser); -- Append a character to the wiki text buffer. procedure Parse_Text (P : in out Parser; Token : in Wiki.Strings.WChar); -- Check if the link refers to an image and must be rendered as an image. function Is_Image (P : in Parser; Link : in Wiki.Strings.WString) return Boolean; type String_Array is array (Positive range <>) of Wiki.String_Access; -- Extract a list of parameters separated by the given separator (ex: '|'). procedure Parse_Parameters (P : in out Parser; Separator : in Wiki.Strings.WChar; Terminator : in Wiki.Strings.WChar; Names : in String_Array); procedure Start_Element (P : in out Parser; Tag : in Wiki.Html_Tag; Attributes : in out Wiki.Attributes.Attribute_List); procedure End_Element (P : in out Parser; Tag : in Wiki.Html_Tag); procedure Parse_Token (P : in out Parser); end Wiki.Parsers;
----------------------------------------------------------------------- -- wiki-parsers -- Wiki parser -- Copyright (C) 2011, 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.Attributes; with Wiki.Plugins; with Wiki.Filters; with Wiki.Strings; with Wiki.Documents; with Wiki.Streams; -- === Wiki Parsers === -- The <b>Wikis.Parsers</b> package implements a parser for several well known wiki formats -- but also for HTML. While reading the input, the parser populates a wiki <tt>Document</tt> -- instance with headers, paragraphs, links, and other elements. -- -- Doc : Wiki.Documents.Document; -- Engine : Wiki.Parsers.Parser; -- -- Before using the parser, it must be configured to choose the syntax by using the -- <tt>Set_Syntax</tt> procedure: -- -- Engine.Set_Syntax (Wiki.SYNTAX_HTML); -- -- The parser can be configured to use filters. A filter is added by using the -- <tt>Add_Filter</tt> procedure. A filter is added at begining of the chain so that -- the filter added last is called first. -- -- The <tt>Parse</tt> procedure is then used to parse either a string content or some stream -- represented by the <tt>Input_Stream</tt> interface. After the <tt>Parse</tt> procedure -- completes, the <tt>Document</tt> instance holds the wiki document. -- -- Engine.Parse (Some_Text, Doc); -- package Wiki.Parsers is pragma Preelaborate; type Parser is tagged limited private; -- Add the plugin to the wiki engine. procedure Add_Plugin (Engine : in out Parser; Name : in String; Plugin : in Wiki.Plugins.Wiki_Plugin_Access); -- Set the wiki syntax that the wiki engine must use. procedure Set_Syntax (Engine : in out Parser; Syntax : in Wiki_Syntax := SYNTAX_MIX); -- Add a filter in the wiki engine. procedure Add_Filter (Engine : in out Parser; Filter : in Wiki.Filters.Filter_Type_Access); -- Parse the wiki text contained in <b>Text</b> according to the wiki syntax -- defined on the parser. procedure Parse (Engine : in out Parser; Text : in Wiki.Strings.WString; Doc : in out Wiki.Documents.Document); -- Parse the wiki stream managed by <tt>Stream</tt> according to the wiki syntax configured -- on the wiki engine. procedure Parse (Engine : in out Parser; Stream : in Wiki.Streams.Input_Stream_Access; Doc : in out Wiki.Documents.Document); private type Parser_Handler is access procedure (P : in out Parser; Token : in Wiki.Strings.WChar); type Parser_Table is array (0 .. 127) of Parser_Handler; type Parser_Table_Access is access constant Parser_Table; type Parser is tagged limited record Pending : Wiki.Strings.WChar; Has_Pending : Boolean; Syntax : Wiki_Syntax; Previous_Syntax : Wiki_Syntax; Table : Parser_Table_Access; Document : Wiki.Documents.Document; Filters : Wiki.Filters.Filter_Chain; Format : Wiki.Format_Map; Text : Wiki.Strings.BString (512); Token : Wiki.Strings.BString (512); Empty_Line : Boolean := True; Is_Eof : Boolean := False; In_Paragraph : Boolean := False; In_List : Boolean := False; Need_Paragraph : Boolean := True; Link_Double_Bracket : Boolean := False; Link_No_Space : Boolean := False; Is_Dotclear : Boolean := False; Link_Title_First : Boolean := False; Check_Image_Link : Boolean := False; Header_Offset : Integer := 0; Quote_Level : Natural := 0; Escape_Char : Wiki.Strings.WChar; List_Level : Natural := 0; Reader : Wiki.Streams.Input_Stream_Access := null; Attributes : Wiki.Attributes.Attribute_List; end record; -- Peek the next character from the wiki text buffer. procedure Peek (P : in out Parser; Token : out Wiki.Strings.WChar); -- Put back the character so that it will be returned by the next call to Peek. procedure Put_Back (P : in out Parser; Token : in Wiki.Strings.WChar); -- Skip all the spaces and tabs as well as end of the current line (CR+LF). procedure Skip_End_Of_Line (P : in out Parser); -- Skip white spaces and tabs. procedure Skip_Spaces (P : in out Parser); -- Flush the wiki text that was collected in the text buffer. procedure Flush_Text (P : in out Parser); -- Flush the wiki dl/dt/dd definition list. procedure Flush_List (P : in out Parser); -- Append a character to the wiki text buffer. procedure Parse_Text (P : in out Parser; Token : in Wiki.Strings.WChar); -- Check if the link refers to an image and must be rendered as an image. function Is_Image (P : in Parser; Link : in Wiki.Strings.WString) return Boolean; type String_Array is array (Positive range <>) of Wiki.String_Access; -- Extract a list of parameters separated by the given separator (ex: '|'). procedure Parse_Parameters (P : in out Parser; Separator : in Wiki.Strings.WChar; Terminator : in Wiki.Strings.WChar; Names : in String_Array); procedure Start_Element (P : in out Parser; Tag : in Wiki.Html_Tag; Attributes : in out Wiki.Attributes.Attribute_List); procedure End_Element (P : in out Parser; Tag : in Wiki.Html_Tag); procedure Parse_Token (P : in out Parser); end Wiki.Parsers;
Add Link_No_Space flag
Add Link_No_Space flag
Ada
apache-2.0
stcarrez/ada-wiki,stcarrez/ada-wiki
316196a260391614c9263e106882475e858c00d9
src/wiki-filters.ads
src/wiki-filters.ads
----------------------------------------------------------------------- -- wiki-filters -- Wiki filters -- 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 Ada.Finalization; with Wiki.Attributes; with Wiki.Documents; with Wiki.Nodes; with Wiki.Strings; -- == Filters == -- The <b>Wiki.Filters</b> package provides a simple filter framework that allows to plug -- specific filters when a wiki document is parsed and processed. The <tt>Filter_Type</tt> -- implements the <tt>Document_Reader</tt> interface to catch all the wiki document operations -- and it forwards the different calls to a next wiki document instance. A filter can do some -- operations while calls are made so that it can: -- -- * Get the text content and filter it by looking at forbidden words in some dictionary, -- * Ignore some formatting construct (for example to forbid the use of links), -- * Verify and do some corrections on HTML content embedded in wiki text, -- * Expand some plugins, specific links to complex content. -- -- To implement a new filter, the <tt>Filter_Type</tt> type must be used as a base type -- and some of the operations have to be overriden. The default <tt>Filter_Type</tt> operations -- just propagate the call to the attached wiki document instance (ie, a kind of pass -- through filter). -- package Wiki.Filters is pragma Preelaborate; use Ada.Strings.Wide_Wide_Unbounded; -- ------------------------------ -- Filter type -- ------------------------------ type Filter_Type is new Ada.Finalization.Limited_Controlled with private; type Filter_Type_Access is access all Filter_Type'Class; -- Add a simple node such as N_LINE_BREAK, N_HORIZONTAL_RULE or N_PARAGRAPH to the document. procedure Add_Node (Filter : in out Filter_Type; Document : in out Wiki.Nodes.Document; Kind : in Wiki.Nodes.Simple_Node_Kind); -- Add a text content with the given format to the document. procedure Add_Text (Filter : in out Filter_Type; Document : in out Wiki.Nodes.Document; Text : in Wiki.Strings.WString; Format : in Wiki.Nodes.Format_Map); -- Add a section header with the given level in the document. procedure Add_Header (Filter : in out Filter_Type; Document : in out Wiki.Nodes.Document; Header : in Wiki.Strings.WString; Level : in Natural); -- Push a HTML node with the given tag to the document. procedure Push_Node (Filter : in out Filter_Type; Document : in out Wiki.Nodes.Document; Tag : in Wiki.Nodes.Html_Tag_Type; Attributes : in out Wiki.Attributes.Attribute_List_Type); -- Pop a HTML node with the given tag. procedure Pop_Node (Filter : in out Filter_Type; Document : in out Wiki.Nodes.Document; Tag : in Wiki.Nodes.Html_Tag_Type); -- Add a blockquote (<blockquote>). The level indicates the blockquote nested level. -- The blockquote must be closed at the next header. procedure Add_Blockquote (Document : in out Filter_Type; Level : in Natural); -- 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 (Document : in out Filter_Type; Level : in Positive; Ordered : in Boolean); -- Add a link. procedure Add_Link (Filter : in out Filter_Type; Document : in out Wiki.Nodes.Document; Name : in Wiki.Strings.WString; Attributes : in out Wiki.Attributes.Attribute_List_Type); -- Add an image. procedure Add_Image (Filter : in out Filter_Type; Document : in out Wiki.Nodes.Document; Name : in Wiki.Strings.WString; Attributes : in out Wiki.Attributes.Attribute_List_Type); -- Add a quote. procedure Add_Quote (Document : in out Filter_Type; Quote : in Unbounded_Wide_Wide_String; Link : in Unbounded_Wide_Wide_String; Language : in Unbounded_Wide_Wide_String); -- Add a text block that is pre-formatted. procedure Add_Preformatted (Document : in out Filter_Type; Text : in Unbounded_Wide_Wide_String; Format : in Unbounded_Wide_Wide_String); -- Finish the document after complete wiki text has been parsed. procedure Finish (Document : in out Filter_Type); private type Filter_Type is new Ada.Finalization.Limited_Controlled with record Next : Filter_Type_Access; end record; end Wiki.Filters;
----------------------------------------------------------------------- -- wiki-filters -- Wiki filters -- 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 Ada.Finalization; with Wiki.Attributes; with Wiki.Documents; with Wiki.Nodes; with Wiki.Strings; -- == Filters == -- The <b>Wiki.Filters</b> package provides a simple filter framework that allows to plug -- specific filters when a wiki document is parsed and processed. The <tt>Filter_Type</tt> -- implements the <tt>Document_Reader</tt> interface to catch all the wiki document operations -- and it forwards the different calls to a next wiki document instance. A filter can do some -- operations while calls are made so that it can: -- -- * Get the text content and filter it by looking at forbidden words in some dictionary, -- * Ignore some formatting construct (for example to forbid the use of links), -- * Verify and do some corrections on HTML content embedded in wiki text, -- * Expand some plugins, specific links to complex content. -- -- To implement a new filter, the <tt>Filter_Type</tt> type must be used as a base type -- and some of the operations have to be overriden. The default <tt>Filter_Type</tt> operations -- just propagate the call to the attached wiki document instance (ie, a kind of pass -- through filter). -- package Wiki.Filters is pragma Preelaborate; use Ada.Strings.Wide_Wide_Unbounded; -- ------------------------------ -- Filter type -- ------------------------------ type Filter_Type is new Ada.Finalization.Limited_Controlled with private; type Filter_Type_Access is access all Filter_Type'Class; -- Add a simple node such as N_LINE_BREAK, N_HORIZONTAL_RULE or N_PARAGRAPH to the document. procedure Add_Node (Filter : in out Filter_Type; Document : in out Wiki.Nodes.Document; Kind : in Wiki.Nodes.Simple_Node_Kind); -- Add a text content with the given format to the document. procedure Add_Text (Filter : in out Filter_Type; Document : in out Wiki.Nodes.Document; Text : in Wiki.Strings.WString; Format : in Wiki.Nodes.Format_Map); -- Add a section header with the given level in the document. procedure Add_Header (Filter : in out Filter_Type; Document : in out Wiki.Nodes.Document; Header : in Wiki.Strings.WString; Level : in Natural); -- Push a HTML node with the given tag to the document. procedure Push_Node (Filter : in out Filter_Type; Document : in out Wiki.Nodes.Document; Tag : in Wiki.Nodes.Html_Tag_Type; Attributes : in out Wiki.Attributes.Attribute_List_Type); -- Pop a HTML node with the given tag. procedure Pop_Node (Filter : in out Filter_Type; Document : in out Wiki.Nodes.Document; Tag : in Wiki.Nodes.Html_Tag_Type); -- Add a blockquote (<blockquote>). The level indicates the blockquote nested level. -- The blockquote must be closed at the next header. procedure Add_Blockquote (Document : in out Filter_Type; Level : in Natural); -- 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 (Document : in out Filter_Type; Level : in Positive; Ordered : in Boolean); -- Add a link. procedure Add_Link (Filter : in out Filter_Type; Document : in out Wiki.Nodes.Document; Name : in Wiki.Strings.WString; Attributes : in out Wiki.Attributes.Attribute_List_Type); -- Add an image. procedure Add_Image (Filter : in out Filter_Type; Document : in out Wiki.Nodes.Document; Name : in Wiki.Strings.WString; Attributes : in out Wiki.Attributes.Attribute_List_Type); -- Add a quote. procedure Add_Quote (Filter : in out Filter_Type; Document : in out Wiki.Nodes.Document; Name : in Wiki.Strings.WString; Attributes : in out Wiki.Attributes.Attribute_List_Type); -- Add a text block that is pre-formatted. procedure Add_Preformatted (Document : in out Filter_Type; Text : in Unbounded_Wide_Wide_String; Format : in Unbounded_Wide_Wide_String); -- Finish the document after complete wiki text has been parsed. procedure Finish (Document : in out Filter_Type); private type Filter_Type is new Ada.Finalization.Limited_Controlled with record Next : Filter_Type_Access; end record; end Wiki.Filters;
Update the Add_Quote procedure definition
Update the Add_Quote procedure definition
Ada
apache-2.0
stcarrez/ada-wiki,stcarrez/ada-wiki
28eaddfcf65bee61dbb24a43cf7970bb850a7d2f
src/wiki-parsers.ads
src/wiki-parsers.ads
----------------------------------------------------------------------- -- wiki-parsers -- Wiki parser -- Copyright (C) 2011, 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.Attributes; with Wiki.Plugins; with Wiki.Filters; with Wiki.Strings; with Wiki.Documents; with Wiki.Streams; -- === Wiki Parsers === -- The <b>Wikis.Parsers</b> package implements a parser for several well known wiki formats -- but also for HTML. While reading the input, the parser populates a wiki <tt>Document</tt> -- instance with headers, paragraphs, links, and other elements. -- -- Engine : Wiki.Parsers.Parser; -- -- Before using the parser, it must be configured to choose the syntax by using the -- <tt>Set_Syntax</tt> procedure: -- -- Engine.Set_Syntax (Wiki.SYNTAX_HTML); -- -- The parser can be configured to use filters. A filter is added by using the -- <tt>Add_Filter</tt> procedure. A filter is added at begining of the chain so that -- the filter added last is called first. The wiki <tt>Document</tt> is always built through -- the filter chain so this allows filters to change or alter the content that was parsed. -- -- Engine.Add_Filter (TOC'Unchecked_Access); -- Engine.Add_Filter (Filter'Unchecked_Access); -- -- The <tt>Parse</tt> procedure is then used to parse either a string content or some stream -- represented by the <tt>Input_Stream</tt> interface. After the <tt>Parse</tt> procedure -- completes, the <tt>Document</tt> instance holds the wiki document. -- -- Engine.Parse (Some_Text, Doc); -- package Wiki.Parsers is pragma Preelaborate; type Parser is tagged limited private; -- Set the plugin factory to find and use plugins. procedure Set_Plugin_Factory (Engine : in out Parser; Factory : in Wiki.Plugins.Plugin_Factory_Access); -- Set the wiki syntax that the wiki engine must use. procedure Set_Syntax (Engine : in out Parser; Syntax : in Wiki_Syntax := SYNTAX_MIX); -- Add a filter in the wiki engine. procedure Add_Filter (Engine : in out Parser; Filter : in Wiki.Filters.Filter_Type_Access); -- Set the plugin context. procedure Set_Context (Engine : in out Parser; Context : in Wiki.Plugins.Plugin_Context); -- Parse the wiki text contained in <b>Text</b> according to the wiki syntax -- defined on the parser. procedure Parse (Engine : in out Parser; Text : in Wiki.Strings.WString; Doc : in out Wiki.Documents.Document); -- Parse the wiki text contained in <b>Text</b> according to the wiki syntax -- defined on the parser. procedure Parse (Engine : in out Parser; Text : in Wiki.Strings.UString; Doc : in out Wiki.Documents.Document); -- Parse the wiki stream managed by <tt>Stream</tt> according to the wiki syntax configured -- on the wiki engine. procedure Parse (Engine : in out Parser; Stream : in Wiki.Streams.Input_Stream_Access; Doc : in out Wiki.Documents.Document); private type Parser_Handler is access procedure (P : in out Parser; Token : in Wiki.Strings.WChar); type Parser_Table is array (0 .. 127) of Parser_Handler; type Parser_Table_Access is access constant Parser_Table; type Parser is tagged limited record Context : Wiki.Plugins.Plugin_Context; Pending : Wiki.Strings.WChar; Has_Pending : Boolean; Previous_Syntax : Wiki_Syntax; Table : Parser_Table_Access; Document : Wiki.Documents.Document; Format : Wiki.Format_Map; Text : Wiki.Strings.BString (512); Empty_Line : Boolean := True; Is_Eof : Boolean := False; In_Paragraph : Boolean := False; In_List : Boolean := False; Need_Paragraph : Boolean := True; Link_Double_Bracket : Boolean := False; Link_No_Space : Boolean := False; Is_Dotclear : Boolean := False; Link_Title_First : Boolean := False; Check_Image_Link : Boolean := False; Is_Hidden : Boolean := False; Header_Offset : Integer := 0; Quote_Level : Natural := 0; Escape_Char : Wiki.Strings.WChar; Param_Char : Wiki.Strings.WChar; List_Level : Natural := 0; Reader : Wiki.Streams.Input_Stream_Access := null; Attributes : Wiki.Attributes.Attribute_List; end record; -- Peek the next character from the wiki text buffer. procedure Peek (P : in out Parser; Token : out Wiki.Strings.WChar); -- Put back the character so that it will be returned by the next call to Peek. procedure Put_Back (P : in out Parser; Token : in Wiki.Strings.WChar); -- Skip all the spaces and tabs as well as end of the current line (CR+LF). procedure Skip_End_Of_Line (P : in out Parser); -- Skip white spaces and tabs. procedure Skip_Spaces (P : in out Parser); -- Flush the wiki text that was collected in the text buffer. procedure Flush_Text (P : in out Parser); -- Flush the wiki dl/dt/dd definition list. procedure Flush_List (P : in out Parser); -- Append a character to the wiki text buffer. procedure Parse_Text (P : in out Parser; Token : in Wiki.Strings.WChar); -- Check if the link refers to an image and must be rendered as an image. function Is_Image (P : in Parser; Link : in Wiki.Strings.WString) return Boolean; -- Find the plugin with the given name. -- Returns null if there is no such plugin. function Find (P : in Parser; Name : in Wiki.Strings.WString) return Wiki.Plugins.Wiki_Plugin_Access; type String_Array is array (Positive range <>) of Wiki.String_Access; -- Extract a list of parameters separated by the given separator (ex: '|'). procedure Parse_Parameters (P : in out Parser; Separator : in Wiki.Strings.WChar; Terminator : in Wiki.Strings.WChar; Names : in String_Array; Max : in Positive := 200); procedure Start_Element (P : in out Parser; Tag : in Wiki.Html_Tag; Attributes : in out Wiki.Attributes.Attribute_List); procedure End_Element (P : in out Parser; Tag : in Wiki.Html_Tag); procedure Parse_Token (P : in out Parser); end Wiki.Parsers;
----------------------------------------------------------------------- -- wiki-parsers -- Wiki parser -- Copyright (C) 2011, 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.Attributes; with Wiki.Plugins; with Wiki.Filters; with Wiki.Strings; with Wiki.Documents; with Wiki.Streams; -- === Wiki Parsers === -- The <b>Wikis.Parsers</b> package implements a parser for several well known wiki formats -- but also for HTML. While reading the input, the parser populates a wiki <tt>Document</tt> -- instance with headers, paragraphs, links, and other elements. -- -- Engine : Wiki.Parsers.Parser; -- -- Before using the parser, it must be configured to choose the syntax by using the -- <tt>Set_Syntax</tt> procedure: -- -- Engine.Set_Syntax (Wiki.SYNTAX_HTML); -- -- The parser can be configured to use filters. A filter is added by using the -- <tt>Add_Filter</tt> procedure. A filter is added at begining of the chain so that -- the filter added last is called first. The wiki <tt>Document</tt> is always built through -- the filter chain so this allows filters to change or alter the content that was parsed. -- -- Engine.Add_Filter (TOC'Unchecked_Access); -- Engine.Add_Filter (Filter'Unchecked_Access); -- -- The <tt>Parse</tt> procedure is then used to parse either a string content or some stream -- represented by the <tt>Input_Stream</tt> interface. After the <tt>Parse</tt> procedure -- completes, the <tt>Document</tt> instance holds the wiki document. -- -- Engine.Parse (Some_Text, Doc); -- package Wiki.Parsers is pragma Preelaborate; type Parser is tagged limited private; -- Set the plugin factory to find and use plugins. procedure Set_Plugin_Factory (Engine : in out Parser; Factory : in Wiki.Plugins.Plugin_Factory_Access); -- Set the wiki syntax that the wiki engine must use. procedure Set_Syntax (Engine : in out Parser; Syntax : in Wiki_Syntax := SYNTAX_MIX); -- Add a filter in the wiki engine. procedure Add_Filter (Engine : in out Parser; Filter : in Wiki.Filters.Filter_Type_Access); -- Set the plugin context. procedure Set_Context (Engine : in out Parser; Context : in Wiki.Plugins.Plugin_Context); -- Parse the wiki text contained in <b>Text</b> according to the wiki syntax -- defined on the parser. procedure Parse (Engine : in out Parser; Text : in Wiki.Strings.WString; Doc : in out Wiki.Documents.Document); -- Parse the wiki text contained in <b>Text</b> according to the wiki syntax -- defined on the parser. procedure Parse (Engine : in out Parser; Text : in Wiki.Strings.UString; Doc : in out Wiki.Documents.Document); -- Parse the wiki stream managed by <tt>Stream</tt> according to the wiki syntax configured -- on the wiki engine. procedure Parse (Engine : in out Parser; Stream : in Wiki.Streams.Input_Stream_Access; Doc : in out Wiki.Documents.Document); private type Parser_Handler is access procedure (P : in out Parser; Token : in Wiki.Strings.WChar); type Parser_Table is array (0 .. 127) of Parser_Handler; type Parser_Table_Access is access constant Parser_Table; type Parser is tagged limited record Context : Wiki.Plugins.Plugin_Context; Pending : Wiki.Strings.WChar; Has_Pending : Boolean; Previous_Syntax : Wiki_Syntax; Table : Parser_Table_Access; Document : Wiki.Documents.Document; Format : Wiki.Format_Map; Text : Wiki.Strings.BString (512); Empty_Line : Boolean := True; Is_Eof : Boolean := False; In_Paragraph : Boolean := False; In_List : Boolean := False; Need_Paragraph : Boolean := True; Link_Double_Bracket : Boolean := False; Link_No_Space : Boolean := False; Is_Dotclear : Boolean := False; Link_Title_First : Boolean := False; Check_Image_Link : Boolean := False; Is_Hidden : Boolean := False; Header_Offset : Integer := 0; Quote_Level : Natural := 0; Escape_Char : Wiki.Strings.WChar; Param_Char : Wiki.Strings.WChar; List_Level : Natural := 0; Reader : Wiki.Streams.Input_Stream_Access := null; Attributes : Wiki.Attributes.Attribute_List; end record; -- Peek the next character from the wiki text buffer. procedure Peek (P : in out Parser; Token : out Wiki.Strings.WChar); -- Put back the character so that it will be returned by the next call to Peek. procedure Put_Back (P : in out Parser; Token : in Wiki.Strings.WChar); -- Skip all the spaces and tabs as well as end of the current line (CR+LF). procedure Skip_End_Of_Line (P : in out Parser); -- Skip white spaces and tabs. procedure Skip_Spaces (P : in out Parser); -- Flush the wiki text that was collected in the text buffer. procedure Flush_Text (P : in out Parser); -- Flush the wiki dl/dt/dd definition list. procedure Flush_List (P : in out Parser); -- Append a character to the wiki text buffer. procedure Parse_Text (P : in out Parser; Token : in Wiki.Strings.WChar); -- Check if the link refers to an image and must be rendered as an image. -- Returns a positive index of the start the the image link. function Is_Image (P : in Parser; Link : in Wiki.Strings.WString) return Natural; -- Find the plugin with the given name. -- Returns null if there is no such plugin. function Find (P : in Parser; Name : in Wiki.Strings.WString) return Wiki.Plugins.Wiki_Plugin_Access; type String_Array is array (Positive range <>) of Wiki.String_Access; -- Extract a list of parameters separated by the given separator (ex: '|'). procedure Parse_Parameters (P : in out Parser; Separator : in Wiki.Strings.WChar; Terminator : in Wiki.Strings.WChar; Names : in String_Array; Max : in Positive := 200); procedure Start_Element (P : in out Parser; Tag : in Wiki.Html_Tag; Attributes : in out Wiki.Attributes.Attribute_List); procedure End_Element (P : in out Parser; Tag : in Wiki.Html_Tag); procedure Parse_Token (P : in out Parser); end Wiki.Parsers;
Change Is_Image to return the image start position offset
Change Is_Image to return the image start position offset
Ada
apache-2.0
stcarrez/ada-wiki,stcarrez/ada-wiki
9df9dc48a49703f57c94a9946190a316df777f27
src/ado-datasets.adb
src/ado-datasets.adb
----------------------------------------------------------------------- -- ado-datasets -- Datasets -- Copyright (C) 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.Beans.Objects.Time; with ADO.Schemas; with ADO.Statements; package body ADO.Datasets is -- ------------------------------ -- Execute the SQL query on the database session and populate the dataset. -- The column names are used to setup the dataset row bean definition. -- ------------------------------ procedure List (Into : in out Dataset; Session : in out ADO.Sessions.Session'Class; Query : in ADO.Queries.Context'Class) is procedure Fill (Data : in out Util.Beans.Objects.Datasets.Object_Array); Stmt : ADO.Statements.Query_Statement := Session.Create_Statement (Query); procedure Fill (Data : in out Util.Beans.Objects.Datasets.Object_Array) is use ADO.Schemas; begin for I in Data'Range loop case Stmt.Get_Column_Type (I - 1) is -- Boolean column when T_BOOLEAN => Data (I) := Util.Beans.Objects.To_Object (Stmt.Get_Boolean (I - 1)); when T_TINYINT | T_SMALLINT | T_INTEGER | T_LONG_INTEGER | T_YEAR => Data (I) := Util.Beans.Objects.To_Object (Stmt.Get_Integer (I - 1)); when T_FLOAT | T_DOUBLE | T_DECIMAL => Data (I) := Util.Beans.Objects.Null_Object; when T_ENUM => Data (I) := Util.Beans.Objects.To_Object (Stmt.Get_String (I - 1)); when T_TIME | T_DATE | T_DATE_TIME | T_TIMESTAMP => Data (I) := Util.Beans.Objects.Time.To_Object (Stmt.Get_Time (I - 1)); when T_CHAR | T_VARCHAR => Data (I) := Util.Beans.Objects.To_Object (Stmt.Get_String (I - 1)); when T_BLOB => Data (I) := Util.Beans.Objects.Null_Object; when T_SET | T_UNKNOWN | T_NULL => Data (I) := Util.Beans.Objects.Null_Object; end case; end loop; end Fill; begin Stmt.Execute; Into.Clear; if Stmt.Has_Elements then for I in 1 .. Stmt.Get_Column_Count loop Into.Add_Column (Stmt.Get_Column_Name (I - 1)); end loop; while Stmt.Has_Elements loop Into.Append (Fill'Access); Stmt.Next; end loop; end if; end List; -- ------------------------------ -- Get the number of items in a list by executing an SQL query. -- ------------------------------ function Get_Count (Session : in ADO.Sessions.Session'Class; Query : in ADO.Queries.Context'Class) return Natural is Stmt : ADO.Statements.Query_Statement := Session.Create_Statement (Query); begin Stmt.Execute; return Stmt.Get_Result_Integer; end Get_Count; end ADO.Datasets;
----------------------------------------------------------------------- -- ado-datasets -- Datasets -- Copyright (C) 2013, 2014, 2018 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Beans.Objects.Time; with ADO.Schemas; with ADO.Statements; package body ADO.Datasets is -- ------------------------------ -- Execute the SQL query on the database session and populate the dataset. -- The column names are used to setup the dataset row bean definition. -- ------------------------------ procedure List (Into : in out Dataset; Session : in out ADO.Sessions.Session'Class; Query : in ADO.Queries.Context'Class) is procedure Fill (Data : in out Util.Beans.Objects.Datasets.Object_Array); Stmt : ADO.Statements.Query_Statement := Session.Create_Statement (Query); procedure Fill (Data : in out Util.Beans.Objects.Datasets.Object_Array) is use ADO.Schemas; begin for I in Data'Range loop if Stmt.Is_Null (I - 1) then Data (I) := Util.Beans.Objects.Null_Object; else case Stmt.Get_Column_Type (I - 1) is -- Boolean column when T_BOOLEAN => Data (I) := Util.Beans.Objects.To_Object (Stmt.Get_Boolean (I - 1)); when T_TINYINT | T_SMALLINT | T_INTEGER | T_LONG_INTEGER | T_YEAR => Data (I) := Util.Beans.Objects.To_Object (Stmt.Get_Integer (I - 1)); when T_FLOAT | T_DOUBLE | T_DECIMAL => Data (I) := Util.Beans.Objects.Null_Object; when T_ENUM => Data (I) := Util.Beans.Objects.To_Object (Stmt.Get_String (I - 1)); when T_TIME | T_DATE | T_DATE_TIME | T_TIMESTAMP => Data (I) := Util.Beans.Objects.Time.To_Object (Stmt.Get_Time (I - 1)); when T_CHAR | T_VARCHAR => Data (I) := Util.Beans.Objects.To_Object (Stmt.Get_String (I - 1)); when T_BLOB => Data (I) := Util.Beans.Objects.Null_Object; when T_SET | T_UNKNOWN | T_NULL => Data (I) := Util.Beans.Objects.Null_Object; end case; end if; end loop; end Fill; begin Stmt.Execute; Into.Clear; if Stmt.Has_Elements then for I in 1 .. Stmt.Get_Column_Count loop Into.Add_Column (Stmt.Get_Column_Name (I - 1)); end loop; while Stmt.Has_Elements loop Into.Append (Fill'Access); Stmt.Next; end loop; end if; end List; -- ------------------------------ -- Get the number of items in a list by executing an SQL query. -- ------------------------------ function Get_Count (Session : in ADO.Sessions.Session'Class; Query : in ADO.Queries.Context'Class) return Natural is Stmt : ADO.Statements.Query_Statement := Session.Create_Statement (Query); begin Stmt.Execute; return Stmt.Get_Result_Integer; end Get_Count; end ADO.Datasets;
Check for a NULL column and set the value to a Null_Object
Check for a NULL column and set the value to a Null_Object
Ada
apache-2.0
stcarrez/ada-ado
1f3583c652b0f5f72a67dc0984313744174c8459
src/gen-commands-docs.adb
src/gen-commands-docs.adb
----------------------------------------------------------------------- -- gen-commands-docs -- Extract and generate documentation for the project -- Copyright (C) 2012 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with GNAT.Command_Line; with Ada.Text_IO; with Gen.Artifacts.Docs; with Gen.Model.Packages; package body Gen.Commands.Docs is use GNAT.Command_Line; -- ------------------------------ -- Execute the command with the arguments. -- ------------------------------ procedure Execute (Cmd : in Command; Generator : in out Gen.Generator.Handler) is pragma Unreferenced (Cmd); Doc : Gen.Artifacts.Docs.Artifact; M : Gen.Model.Packages.Model_Definition; begin Generator.Read_Project ("dynamo.xml", False); -- Setup the target directory where the distribution is created. declare Target_Dir : constant String := Get_Argument; begin if Target_Dir'Length = 0 then Generator.Error ("Missing target directory"); return; end if; Generator.Set_Result_Directory (Target_Dir); end; -- -- -- Read the package description. -- declare -- Package_File : constant String := Get_Argument; -- begin -- if Package_File'Length > 0 then -- Gen.Generator.Read_Package (Generator, Package_File); -- else -- Gen.Generator.Read_Package (Generator, "package.xml"); -- end if; -- end; Doc.Prepare (M, Generator); -- -- 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. -- ------------------------------ procedure Help (Cmd : in Command; Generator : in out Gen.Generator.Handler) is pragma Unreferenced (Cmd, Generator); use Ada.Text_IO; begin Put_Line ("build-doc: Extract and generate the project documentation"); Put_Line ("Usage: build-doc"); New_Line; Put_Line (" Extract the documentation from the project source files and generate the"); Put_Line (" project documentation. The following files are scanned:"); Put_Line (" - Ada specifications (src/*.ads)"); Put_Line (" - XML configuration files (config/*.xml)"); Put_Line (" - XML database model files (db/*.xml)"); end Help; end Gen.Commands.Docs;
----------------------------------------------------------------------- -- gen-commands-docs -- Extract and generate documentation for the project -- Copyright (C) 2012 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with GNAT.Command_Line; with Ada.Text_IO; with Gen.Artifacts.Docs; with Gen.Model.Packages; package body Gen.Commands.Docs is use GNAT.Command_Line; -- ------------------------------ -- Execute the command with the arguments. -- ------------------------------ procedure Execute (Cmd : in Command; Generator : in out Gen.Generator.Handler) is pragma Unreferenced (Cmd); Doc : Gen.Artifacts.Docs.Artifact; M : Gen.Model.Packages.Model_Definition; begin Generator.Read_Project ("dynamo.xml", False); -- Setup the target directory where the distribution is created. declare Target_Dir : constant String := Get_Argument; begin if Target_Dir'Length = 0 then Generator.Error ("Missing target directory"); return; end if; Generator.Set_Result_Directory (Target_Dir); end; Doc.Prepare (M, Generator); 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 ("build-doc: Extract and generate the project documentation"); Put_Line ("Usage: build-doc"); New_Line; Put_Line (" Extract the documentation from the project source files and generate the"); Put_Line (" project documentation. The following files are scanned:"); Put_Line (" - Ada specifications (src/*.ads)"); Put_Line (" - XML configuration files (config/*.xml)"); Put_Line (" - XML database model files (db/*.xml)"); end Help; end Gen.Commands.Docs;
Remove unused commented code
Remove unused commented code
Ada
apache-2.0
Letractively/ada-gen,Letractively/ada-gen,Letractively/ada-gen,Letractively/ada-gen
5f7e48e4dc3f82a77e43b6db1a7e68a0bde198a3
src/el-expressions-nodes.ads
src/el-expressions-nodes.ads
----------------------------------------------------------------------- -- EL.Expressions -- Expression Nodes -- Copyright (C) 2009, 2010, 2011, 2012, 2013, 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. ----------------------------------------------------------------------- -- The 'ELNode' describes an expression that can later be evaluated -- on an expression context. Expressions are parsed and translated -- to a read-only tree. with EL.Functions; with Ada.Strings.Wide_Wide_Unbounded; with Ada.Strings.Unbounded; with Util.Concurrent.Counters; private package EL.Expressions.Nodes is pragma Preelaborate; use EL.Functions; use Ada.Strings.Wide_Wide_Unbounded; use Ada.Strings.Unbounded; type Reduction; type ELNode is abstract tagged limited record Ref_Counter : Util.Concurrent.Counters.Counter; end record; type ELNode_Access is access all ELNode'Class; type Reduction is record Node : ELNode_Access; Value : EL.Objects.Object; end record; -- Evaluate a node on a given context. If function Get_Safe_Value (Expr : in ELNode; Context : in ELContext'Class) return Object; -- Evaluate a node on a given context. function Get_Value (Expr : in ELNode; Context : in ELContext'Class) return Object is abstract; -- Reduce the expression by eliminating variables which are known -- and computing constant expressions. Returns either a new expression -- tree or a constant value. function Reduce (Expr : access ELNode; Context : in ELContext'Class) return Reduction is abstract; -- Delete the expression tree (calls Delete (ELNode_Access) recursively). procedure Delete (Node : in out ELNode) is abstract; -- Delete the expression tree. Free the memory allocated by nodes -- of the expression tree. Clears the node pointer. procedure Delete (Node : in out ELNode_Access); -- ------------------------------ -- Unary expression node -- ------------------------------ type ELUnary is new ELNode with private; type Unary_Node is (EL_VOID, EL_NOT, EL_MINUS, EL_EMPTY); -- Evaluate a node on a given context. overriding function Get_Value (Expr : ELUnary; Context : ELContext'Class) return Object; -- Reduce the expression by eliminating variables which are known -- and computing constant expressions. Returns either a new expression -- tree or a constant value. overriding function Reduce (Expr : access ELUnary; Context : in ELContext'Class) return Reduction; overriding procedure Delete (Node : in out ELUnary); -- ------------------------------ -- Binary expression node -- ------------------------------ type ELBinary is new ELNode with private; type Binary_Node is (EL_EQ, EL_NE, EL_LE, EL_LT, EL_GE, EL_GT, EL_ADD, EL_SUB, EL_MUL, EL_DIV, EL_MOD, EL_AND, EL_OR, EL_LAND, EL_LOR, EL_CONCAT); -- Evaluate a node on a given context. overriding function Get_Value (Expr : ELBinary; Context : ELContext'Class) return Object; -- Reduce the expression by eliminating variables which are known -- and computing constant expressions. Returns either a new expression -- tree or a constant value. overriding function Reduce (Expr : access ELBinary; Context : in ELContext'Class) return Reduction; overriding procedure Delete (Node : in out ELBinary); -- ------------------------------ -- Ternary expression node -- ------------------------------ type ELTernary is new ELNode with private; -- Evaluate a node on a given context. overriding function Get_Value (Expr : ELTernary; Context : ELContext'Class) return Object; -- Reduce the expression by eliminating variables which are known -- and computing constant expressions. Returns either a new expression -- tree or a constant value. overriding function Reduce (Expr : access ELTernary; Context : in ELContext'Class) return Reduction; overriding procedure Delete (Node : in out ELTernary); -- ------------------------------ -- Variable to be looked at in the expression context -- ------------------------------ type ELVariable is new ELNode with private; -- Evaluate a node on a given context. overriding function Get_Value (Expr : ELVariable; Context : ELContext'Class) return Object; -- Reduce the expression by eliminating variables which are known -- and computing constant expressions. Returns either a new expression -- tree or a constant value. overriding function Reduce (Expr : access ELVariable; Context : in ELContext'Class) return Reduction; overriding procedure Delete (Node : in out ELVariable); -- ------------------------------ -- Value property referring to a variable -- ------------------------------ type ELValue (Len : Natural) is new ELNode with private; type ELValue_Access is access all ELValue'Class; -- Check if the target bean is a readonly bean. function Is_Readonly (Node : in ELValue; Context : in ELContext'Class) return Boolean; -- Get the variable name. function Get_Variable_Name (Node : in ELValue) return String; -- Evaluate the node and return a method info with -- the bean object and the method binding. function Get_Method_Info (Node : in ELValue; Context : in ELContext'Class) return Method_Info; -- Evaluate a node on a given context. overriding function Get_Value (Expr : ELValue; Context : ELContext'Class) return Object; -- Evaluate the node and set the value on the associated bean. -- Raises Invalid_Variable if the target object is not a bean. -- Raises Invalid_Expression if the target bean is not writeable. procedure Set_Value (Node : in ELValue; Context : in ELContext'Class; Value : in Objects.Object); -- Reduce the expression by eliminating variables which are known -- and computing constant expressions. Returns either a new expression -- tree or a constant value. overriding function Reduce (Expr : access ELValue; Context : in ELContext'Class) return Reduction; overriding procedure Delete (Node : in out ELValue); -- ------------------------------ -- Literal object (integer, boolean, float, string) -- ------------------------------ type ELObject is new ELNode with private; -- Evaluate a node on a given context. overriding function Get_Value (Expr : ELObject; Context : ELContext'Class) return Object; -- Reduce the expression by eliminating variables which are known -- and computing constant expressions. Returns either a new expression -- tree or a constant value. overriding function Reduce (Expr : access ELObject; Context : in ELContext'Class) return Reduction; overriding procedure Delete (Node : in out ELObject); -- ------------------------------ -- Function call with up to 4 arguments -- ------------------------------ type ELFunction is new ELNode with private; -- Evaluate a node on a given context. overriding function Get_Value (Expr : ELFunction; Context : ELContext'Class) return Object; -- Reduce the expression by eliminating variables which are known -- and computing constant expressions. Returns either a new expression -- tree or a constant value. overriding function Reduce (Expr : access ELFunction; Context : in ELContext'Class) return Reduction; overriding procedure Delete (Node : in out ELFunction); -- Create constant nodes function Create_Node (Value : Boolean) return ELNode_Access; function Create_Node (Value : Long_Long_Integer) return ELNode_Access; function Create_Node (Value : String) return ELNode_Access; function Create_Node (Value : Wide_Wide_String) return ELNode_Access; function Create_Node (Value : Long_Float) return ELNode_Access; function Create_Node (Value : Unbounded_Wide_Wide_String) return ELNode_Access; function Create_Variable (Name : in Wide_Wide_String) return ELNode_Access; function Create_Value (Variable : in ELNode_Access; Name : in Wide_Wide_String) return ELNode_Access; -- Create unary expressions function Create_Node (Of_Type : Unary_Node; Expr : ELNode_Access) return ELNode_Access; -- Create binary expressions function Create_Node (Of_Type : Binary_Node; Left : ELNode_Access; Right : ELNode_Access) return ELNode_Access; -- Create a ternary expression. function Create_Node (Cond : ELNode_Access; Left : ELNode_Access; Right : ELNode_Access) return ELNode_Access; -- Create a function call function Create_Node (Func : EL.Functions.Function_Access; Arg1 : ELNode_Access) return ELNode_Access; -- Create a function call function Create_Node (Func : EL.Functions.Function_Access; Arg1 : ELNode_Access; Arg2 : ELNode_Access) return ELNode_Access; -- Create a function call function Create_Node (Func : EL.Functions.Function_Access; Arg1 : ELNode_Access; Arg2 : ELNode_Access; Arg3 : ELNode_Access) return ELNode_Access; -- Create a function call function Create_Node (Func : EL.Functions.Function_Access; Arg1 : ELNode_Access; Arg2 : ELNode_Access; Arg3 : ELNode_Access; Arg4 : ELNode_Access) return ELNode_Access; private type ELUnary is new ELNode with record Kind : Unary_Node; Node : ELNode_Access; end record; -- ------------------------------ -- Binary nodes -- ------------------------------ type ELBinary is new ELNode with record Kind : Binary_Node; Left : ELNode_Access; Right : ELNode_Access; end record; -- ------------------------------ -- Ternary expression -- ------------------------------ type ELTernary is new ELNode with record Cond : ELNode_Access; Left : ELNode_Access; Right : ELNode_Access; end record; -- #{bean.name} - Bean name, Bean property -- #{bean[12]} - Bean name, -- Variable to be looked at in the expression context type ELVariable is new ELNode with record Name : Unbounded_String; end record; type ELVariable_Access is access all ELVariable; type ELValue (Len : Natural) is new ELNode with record Variable : ELNode_Access; Name : String (1 .. Len); end record; -- A literal object (integer, boolean, float, String) type ELObject is new ELNode with record Value : Object; end record; -- A function call with up to 4 arguments. type ELFunction is new ELNode with record Func : EL.Functions.Function_Access; Arg1 : ELNode_Access; Arg2 : ELNode_Access; Arg3 : ELNode_Access; Arg4 : ELNode_Access; end record; end EL.Expressions.Nodes;
----------------------------------------------------------------------- -- el-expressions-nodes -- Expression Nodes -- Copyright (C) 2009, 2010, 2011, 2012, 2013, 2020, 2021 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- -- The 'ELNode' describes an expression that can later be evaluated -- on an expression context. Expressions are parsed and translated -- to a read-only tree. with EL.Functions; with Ada.Strings.Wide_Wide_Unbounded; private with Ada.Strings.Unbounded; with Util.Concurrent.Counters; private package EL.Expressions.Nodes is pragma Preelaborate; use EL.Functions; use Ada.Strings.Wide_Wide_Unbounded; use Ada.Strings.Unbounded; type Reduction; type ELNode is abstract tagged limited record Ref_Counter : Util.Concurrent.Counters.Counter; end record; type ELNode_Access is access all ELNode'Class; type Reduction is record Node : ELNode_Access; Value : EL.Objects.Object; end record; -- Evaluate a node on a given context. If function Get_Safe_Value (Expr : in ELNode; Context : in ELContext'Class) return Object; -- Evaluate a node on a given context. function Get_Value (Expr : in ELNode; Context : in ELContext'Class) return Object is abstract; -- Reduce the expression by eliminating variables which are known -- and computing constant expressions. Returns either a new expression -- tree or a constant value. function Reduce (Expr : access ELNode; Context : in ELContext'Class) return Reduction is abstract; -- Delete the expression tree (calls Delete (ELNode_Access) recursively). procedure Delete (Node : in out ELNode) is abstract; -- Delete the expression tree. Free the memory allocated by nodes -- of the expression tree. Clears the node pointer. procedure Delete (Node : in out ELNode_Access); -- ------------------------------ -- Unary expression node -- ------------------------------ type ELUnary is new ELNode with private; type Unary_Node is (EL_VOID, EL_NOT, EL_MINUS, EL_EMPTY); -- Evaluate a node on a given context. overriding function Get_Value (Expr : ELUnary; Context : ELContext'Class) return Object; -- Reduce the expression by eliminating variables which are known -- and computing constant expressions. Returns either a new expression -- tree or a constant value. overriding function Reduce (Expr : access ELUnary; Context : in ELContext'Class) return Reduction; overriding procedure Delete (Node : in out ELUnary); -- ------------------------------ -- Binary expression node -- ------------------------------ type ELBinary is new ELNode with private; type Binary_Node is (EL_EQ, EL_NE, EL_LE, EL_LT, EL_GE, EL_GT, EL_ADD, EL_SUB, EL_MUL, EL_DIV, EL_MOD, EL_AND, EL_OR, EL_LAND, EL_LOR, EL_CONCAT); -- Evaluate a node on a given context. overriding function Get_Value (Expr : ELBinary; Context : ELContext'Class) return Object; -- Reduce the expression by eliminating variables which are known -- and computing constant expressions. Returns either a new expression -- tree or a constant value. overriding function Reduce (Expr : access ELBinary; Context : in ELContext'Class) return Reduction; overriding procedure Delete (Node : in out ELBinary); -- ------------------------------ -- Ternary expression node -- ------------------------------ type ELTernary is new ELNode with private; -- Evaluate a node on a given context. overriding function Get_Value (Expr : ELTernary; Context : ELContext'Class) return Object; -- Reduce the expression by eliminating variables which are known -- and computing constant expressions. Returns either a new expression -- tree or a constant value. overriding function Reduce (Expr : access ELTernary; Context : in ELContext'Class) return Reduction; overriding procedure Delete (Node : in out ELTernary); -- ------------------------------ -- Variable to be looked at in the expression context -- ------------------------------ type ELVariable is new ELNode with private; -- Evaluate a node on a given context. overriding function Get_Value (Expr : ELVariable; Context : ELContext'Class) return Object; -- Reduce the expression by eliminating variables which are known -- and computing constant expressions. Returns either a new expression -- tree or a constant value. overriding function Reduce (Expr : access ELVariable; Context : in ELContext'Class) return Reduction; overriding procedure Delete (Node : in out ELVariable); -- ------------------------------ -- Value property referring to a variable -- ------------------------------ type ELValue (Len : Natural) is new ELNode with private; type ELValue_Access is access all ELValue'Class; -- Check if the target bean is a readonly bean. function Is_Readonly (Node : in ELValue; Context : in ELContext'Class) return Boolean; -- Get the variable name. function Get_Variable_Name (Node : in ELValue) return String; -- Evaluate the node and return a method info with -- the bean object and the method binding. function Get_Method_Info (Node : in ELValue; Context : in ELContext'Class) return Method_Info; -- Evaluate a node on a given context. overriding function Get_Value (Expr : ELValue; Context : ELContext'Class) return Object; -- Evaluate the node and set the value on the associated bean. -- Raises Invalid_Variable if the target object is not a bean. -- Raises Invalid_Expression if the target bean is not writeable. procedure Set_Value (Node : in ELValue; Context : in ELContext'Class; Value : in Objects.Object); -- Reduce the expression by eliminating variables which are known -- and computing constant expressions. Returns either a new expression -- tree or a constant value. overriding function Reduce (Expr : access ELValue; Context : in ELContext'Class) return Reduction; overriding procedure Delete (Node : in out ELValue); -- ------------------------------ -- Literal object (integer, boolean, float, string) -- ------------------------------ type ELObject is new ELNode with private; -- Evaluate a node on a given context. overriding function Get_Value (Expr : ELObject; Context : ELContext'Class) return Object; -- Reduce the expression by eliminating variables which are known -- and computing constant expressions. Returns either a new expression -- tree or a constant value. overriding function Reduce (Expr : access ELObject; Context : in ELContext'Class) return Reduction; overriding procedure Delete (Node : in out ELObject); -- ------------------------------ -- Function call with up to 4 arguments -- ------------------------------ type ELFunction is new ELNode with private; -- Evaluate a node on a given context. overriding function Get_Value (Expr : ELFunction; Context : ELContext'Class) return Object; -- Reduce the expression by eliminating variables which are known -- and computing constant expressions. Returns either a new expression -- tree or a constant value. overriding function Reduce (Expr : access ELFunction; Context : in ELContext'Class) return Reduction; overriding procedure Delete (Node : in out ELFunction); -- Create constant nodes function Create_Node (Value : Boolean) return ELNode_Access; function Create_Node (Value : Long_Long_Integer) return ELNode_Access; function Create_Node (Value : String) return ELNode_Access; function Create_Node (Value : Wide_Wide_String) return ELNode_Access; function Create_Node (Value : Long_Float) return ELNode_Access; function Create_Node (Value : Unbounded_Wide_Wide_String) return ELNode_Access; function Create_Variable (Name : in Wide_Wide_String) return ELNode_Access; function Create_Value (Variable : in ELNode_Access; Name : in Wide_Wide_String) return ELNode_Access; -- Create unary expressions function Create_Node (Of_Type : Unary_Node; Expr : ELNode_Access) return ELNode_Access; -- Create binary expressions function Create_Node (Of_Type : Binary_Node; Left : ELNode_Access; Right : ELNode_Access) return ELNode_Access; -- Create a ternary expression. function Create_Node (Cond : ELNode_Access; Left : ELNode_Access; Right : ELNode_Access) return ELNode_Access; -- Create a function call function Create_Node (Func : EL.Functions.Function_Access; Arg1 : ELNode_Access) return ELNode_Access; -- Create a function call function Create_Node (Func : EL.Functions.Function_Access; Arg1 : ELNode_Access; Arg2 : ELNode_Access) return ELNode_Access; -- Create a function call function Create_Node (Func : EL.Functions.Function_Access; Arg1 : ELNode_Access; Arg2 : ELNode_Access; Arg3 : ELNode_Access) return ELNode_Access; -- Create a function call function Create_Node (Func : EL.Functions.Function_Access; Arg1 : ELNode_Access; Arg2 : ELNode_Access; Arg3 : ELNode_Access; Arg4 : ELNode_Access) return ELNode_Access; private type ELUnary is new ELNode with record Kind : Unary_Node; Node : ELNode_Access; end record; -- ------------------------------ -- Binary nodes -- ------------------------------ type ELBinary is new ELNode with record Kind : Binary_Node; Left : ELNode_Access; Right : ELNode_Access; end record; -- ------------------------------ -- Ternary expression -- ------------------------------ type ELTernary is new ELNode with record Cond : ELNode_Access; Left : ELNode_Access; Right : ELNode_Access; end record; -- #{bean.name} - Bean name, Bean property -- #{bean[12]} - Bean name, -- Variable to be looked at in the expression context type ELVariable is new ELNode with record Name : Unbounded_String; end record; type ELVariable_Access is access all ELVariable; type ELValue (Len : Natural) is new ELNode with record Variable : ELNode_Access; Name : String (1 .. Len); end record; -- A literal object (integer, boolean, float, String) type ELObject is new ELNode with record Value : Object; end record; -- A function call with up to 4 arguments. type ELFunction is new ELNode with record Func : EL.Functions.Function_Access; Arg1 : ELNode_Access; Arg2 : ELNode_Access; Arg3 : ELNode_Access; Arg4 : ELNode_Access; end record; end EL.Expressions.Nodes;
Change with clause to private with for the Unbounded package
Change with clause to private with for the Unbounded package
Ada
apache-2.0
stcarrez/ada-el
7da0f7fd0a2a61cef09796e8029f7f5de0e79761
awa/plugins/awa-tags/src/awa-tags.ads
awa/plugins/awa-tags/src/awa-tags.ads
----------------------------------------------------------------------- -- awa-tags -- Tags management -- 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. ----------------------------------------------------------------------- package AWA.Tags is pragma Pure; end AWA.Tags;
----------------------------------------------------------------------- -- awa-tags -- Tags management -- 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. ----------------------------------------------------------------------- -- == Introduction == -- The <b>Tags</b> module allows to associate general purpose tags to any database entity. -- -- == Model == -- [http://ada-awa.googlecode.com/svn/wiki/awa_tags_model.png] -- -- @include awa-tags-modules.ads package AWA.Tags is pragma Pure; end AWA.Tags;
Add some documentation
Add some documentation
Ada
apache-2.0
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
5905c7dff2bc6a814ba8296de0bd781a6e160dcf
src/wiki-nodes.adb
src/wiki-nodes.adb
----------------------------------------------------------------------- -- wiki-nodes -- Wiki Document Internal representation -- 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. ----------------------------------------------------------------------- package body Wiki.Nodes is type Tag_Array is array (Html_Tag_Type) of String_Access; HTML_TAG_NAME : aliased constant String := "html"; HEAD_TAG_NAME : aliased constant String := "head"; TITLE_TAG_NAME : aliased constant String := "title"; BASE_TAG_NAME : aliased constant String := "base"; LINK_TAG_NAME : aliased constant String := "link"; META_TAG_NAME : aliased constant String := "meta"; STYLE_TAG_NAME : aliased constant String := "style"; BODY_TAG_NAME : aliased constant String := "body"; ARTICLE_TAG_NAME : aliased constant String := "article"; SECTION_TAG_NAME : aliased constant String := "section"; NAV_TAG_NAME : aliased constant String := "nav"; ASIDE_TAG_NAME : aliased constant String := "aside"; Tag_Names : constant Tag_Array := ( HTML_TAG => HTML_TAG_NAME'Access, HEAD_TAG => HEAD_TAG_NAME'Access, TITLE_TAG => TITLE_TAG_NAME'Access, BASE_TAG => BASE_TAG_NAME'Access, LINK_TAG => LINK_TAG_NAME'Access, META_TAG => META_TAG_NAME'Access, STYLE_TAG => STYLE_TAG_NAME'Access, BODY_TAG => BODY_TAG_NAME'Access, ARTICLE_TAG => ARTICLE_TAG_NAME'Access, SECTION_TAG => SECTION_TAG_NAME'Access, NAV_TAG => NAV_TAG_NAME'Access, ASIDE_TAG => ASIDE_TAG_NAME'Access, others => null ); -- ------------------------------ -- Get the HTML tag name. -- ------------------------------ function Get_Tag_Name (Tag : in Html_Tag_Type) return String_Access is begin return Tag_Names (Tag); end Get_Tag_Name; -- ------------------------------ -- Create a text node. -- ------------------------------ function Create_Text (Text : in WString) return Node_Type_Access is begin return new Node_Type '(Kind => N_TEXT, Len => Text'Length, Text => Text, others => <>); end Create_Text; -- ------------------------------ -- 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) is Node : constant Node_Type_Access := new Node_Type '(Kind => N_TAG_START, Len => 0, Tag_Start => Tag, Attributes => Attributes, Children => null, Parent => Document.Current); begin Append (Document.Nodes, Node); Document.Current := Node; end Add_Tag; procedure End_Tag (Document : in out Wiki.Nodes.Document; Tag : in Html_Tag_Type) is begin if Document.Current /= null then Document.Current := Document.Current.Parent; end if; end End_Tag; -- ------------------------------ -- Append a node to the document. -- ------------------------------ procedure Append (Into : in out Document; Node : in Node_Type_Access) is begin if Into.Current = null then Append (Into.Nodes, Node); else if Into.Current.Children = null then Into.Current.Children := new Node_List; end if; Append (Into.Current.Children.all, Node); end if; end Append; -- ------------------------------ -- 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) is begin case Kind is when N_LINE_BREAK => Append (Into, new Node_Type '(Kind => N_LINE_BREAK, Len => 0)); when N_HORIZONTAL_RULE => Append (Into, new Node_Type '(Kind => N_HORIZONTAL_RULE, Len => 0)); when N_PARAGRAPH => Append (Into, new Node_Type '(Kind => N_PARAGRAPH, Len => 0)); end case; end Append; -- ------------------------------ -- Append a node to the node list. -- ------------------------------ procedure Append (Into : in out Node_List; Node : in Node_Type_Access) is Block : Node_List_Block_Access := Into.Current; begin if Block.Last = Block.Max then Block.Next := new Node_List_Block (Into.Length); Block := Block.Next; Into.Current := Block; end if; Block.Last := Block.Last + 1; Block.List (Block.Last) := Node; Into.Length := Into.Length + 1; end Append; end Wiki.Nodes;
----------------------------------------------------------------------- -- wiki-nodes -- Wiki Document Internal representation -- 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. ----------------------------------------------------------------------- package body Wiki.Nodes is type Tag_Array is array (Html_Tag_Type) of String_Access; HTML_TAG_NAME : aliased constant String := "html"; HEAD_TAG_NAME : aliased constant String := "head"; TITLE_TAG_NAME : aliased constant String := "title"; BASE_TAG_NAME : aliased constant String := "base"; LINK_TAG_NAME : aliased constant String := "link"; META_TAG_NAME : aliased constant String := "meta"; STYLE_TAG_NAME : aliased constant String := "style"; BODY_TAG_NAME : aliased constant String := "body"; ARTICLE_TAG_NAME : aliased constant String := "article"; SECTION_TAG_NAME : aliased constant String := "section"; NAV_TAG_NAME : aliased constant String := "nav"; ASIDE_TAG_NAME : aliased constant String := "aside"; Tag_Names : constant Tag_Array := ( HTML_TAG => HTML_TAG_NAME'Access, HEAD_TAG => HEAD_TAG_NAME'Access, TITLE_TAG => TITLE_TAG_NAME'Access, BASE_TAG => BASE_TAG_NAME'Access, LINK_TAG => LINK_TAG_NAME'Access, META_TAG => META_TAG_NAME'Access, STYLE_TAG => STYLE_TAG_NAME'Access, BODY_TAG => BODY_TAG_NAME'Access, ARTICLE_TAG => ARTICLE_TAG_NAME'Access, SECTION_TAG => SECTION_TAG_NAME'Access, NAV_TAG => NAV_TAG_NAME'Access, ASIDE_TAG => ASIDE_TAG_NAME'Access, others => null ); -- ------------------------------ -- Get the HTML tag name. -- ------------------------------ function Get_Tag_Name (Tag : in Html_Tag_Type) return String_Access is begin return Tag_Names (Tag); end Get_Tag_Name; -- ------------------------------ -- Find the tag from the tag name. -- ------------------------------ function Find_Tag (Name : in Wide_Wide_String) return Html_Tag_Type is begin -- The list of possible tags is well known and will not change very often. -- The tag lookup is implemented to be efficient with 2 or 3 embedded cases that -- reduce the comparison to the minimum. The result is a large case statement that -- becomes unreadable. case Name'Length is when 0 => return UNKNOWN_TAG; when 1 => case Name (Name'First) is when 'a' | 'A' => return A_TAG; when 'b' | 'B' => return B_TAG; when 'i' | 'I' => return I_TAG; when 'p' | 'P' => return P_TAG; when 'q' | 'Q' => return Q_TAG; when 's' | 'S' => return S_TAG; when 'u' | 'U' => return U_TAG; when others => return UNKNOWN_TAG; end case; when 2 => case Name (Name'First) is when 'b' | 'B' => case Name (Name'Last) is when 'r' | 'R' => return BR_TAG; when others => return UNKNOWN_TAG; end case; when 'd' | 'D' => case Name (Name'Last) is when 'l' | 'L' => return DL_TAG; when 't' | 'T' => return DT_TAG; when 'd' | 'D' => return DD_TAG; when others => return UNKNOWN_TAG; end case; when 'e' | 'E' => case Name (Name'Last) is when 'm' | 'M' => return EM_TAG; when others => return UNKNOWN_TAG; end case; when 'h' | 'H' => case Name (Name'Last) is when '1' => return H1_TAG; when '2' => return H2_TAG; when '3' => return H3_TAG; when '4' => return H4_TAG; when '5' => return H5_TAG; when '6' => return H6_TAG; when 'r' | 'R' => return HR_TAG; when others => return UNKNOWN_TAG; end case; when 'l' | 'L' => case Name (Name'Last) is when 'i' | 'I' => return LI_TAG; when others => return UNKNOWN_TAG; end case; when 'o' | 'O' => case Name (Name'Last) is when 'l' | 'L' => return OL_TAG; when others => return UNKNOWN_TAG; end case; when 'r' | 'R' => case Name (Name'Last) is when 'b' | 'B' => return RB_TAG; when 'p' | 'P' => return RP_TAG; when 't' | 'T' => return RT_TAG; when others => return UNKNOWN_TAG; end case; when 't' | 'T' => case Name (Name'Last) is when 'r' | 'R' => return TR_TAG; when 'd' | 'D' => return TD_TAG; when 'h' | 'H' => return TH_TAG; when others => return UNKNOWN_TAG; end case; when 'u' | 'U' => case Name (Name'Last) is when 'l' | 'L' => return UL_TAG; when others => return UNKNOWN_TAG; end case; when others => return UNKNOWN_TAG; end case; when 3 => case Name (Name'First) is when 'b' | 'B' => case Name (Name'Last) is when 'i' | 'I' => return Tag (Name, "bdi", BDI_TAG); when 'o' | 'O' => return Tag (Name, "bdo", BDO_TAG); when others => return UNKNOWN_TAG; end case; when 'c' | 'C' => return Tag (Name, "col", COL_TAG); when 'd' | 'D' => case Name (Name'First + 1) is when 'i' | 'I' => return Tag (Name, "div", DIV_TAG); when 'f' | 'F' => return Tag (Name, "dfn", DFN_TAG); when 'e' | 'E' => return Tag (Name, "del", DEL_TAG); when others => return UNKNOWN_TAG; end case; when 'i' | 'I' => case Name (Name'Last) is when 'g' | 'G' => return Tag (Name, "img", IMG_TAG); when 's' | 'S' => return Tag (Name, "ins", INS_TAG); when others => return UNKNOWN_TAG; end case; when 'k' | 'K' => return Tag (Name, "kbd", KBD_TAG); when 'm' | 'M' => return Tag (Name, "map", MAP_TAG); when 'n' | 'N' => return Tag (Name, "nav", NAV_TAG); when 'p' | 'P' => return Tag (Name, "pre", PRE_TAG); when 'r' | 'R' => return Tag (Name, "rtc", RTC_TAG); when 's' | 'S' => case Name (Name'Last) is when 'b' | 'B' => return Tag (Name, "sub", SUB_TAG); when 'n' | 'N' => return SPAN_TAG; when 'p' | 'P' => return Tag (Name, "sup", SUP_TAG); when others => return UNKNOWN_TAG; end case; when 'v' | 'V' => return Tag (Name, "var", VAR_TAG); when 'w' | 'W' => return Tag (Name, "wbr", WBR_TAG); when others => return UNKNOWN_TAG; end case; when 4 => case Name (Name'First) is when 'a' | 'A' => case Name (Name'First + 1) is when 'b' | 'B' => return Tag (Name, "abbr", ABBR_TAG); when 'r' | 'R' => return Tag (Name, "area", AREA_TAG); when others => return UNKNOWN_TAG; end case; when 'b' | 'B' => case Name (Name'First + 1) is when 'a' | 'A' => return Tag (Name, "base", BASE_TAG); when 'o' | 'O' => return Tag (Name, "body", BODY_TAG); when others => return UNKNOWN_TAG; end case; when 'c' | 'C' => case Name (Name'First + 1) is when 'i' | 'I' => return Tag (Name, "cite", CITE_TAG); when 'o' | 'O' => return Tag (Name, "code", CODE_TAG); when others => return UNKNOWN_TAG; end case; when 'd' | 'D' => return Tag (Name, "data", DATA_TAG); when 'f' | 'F' => return Tag (Name, "form", FORM_TAG); when 'h' | 'H' => case Name (Name'First + 1) is when 't' | 'T' => return Tag (Name, "html", HTML_TAG); when 'e' | 'E' => return Tag (Name, "head", HEAD_TAG); when others => return UNKNOWN_TAG; end case; when 'l' | 'L' => return Tag (Name, "link", LINK_TAG); when 'm' | 'M' => case Name (Name'Last) is when 'a' | 'A' => return Tag (Name, "meta", META_TAG); when 'n' | 'N' => return Tag (Name, "main", MAIN_TAG); when 'k' | 'K' => return Tag (Name, "mark", MARK_TAG); when others => return UNKNOWN_TAG; end case; when 'r' | 'R' => return Tag (Name, "ruby", RUBY_TAG); when 's' | 'S' => case Name (Name'First + 1) is when 'p' | 'P' => return Tag (Name, "span", SPAN_TAG); when 'a' | 'A' => return Tag (Name, "samp", SAMP_TAG); when others => return UNKNOWN_TAG; end case; when 't' | 'T' => return Tag (Name, "time", TIME_TAG); when others => return UNKNOWN_TAG; end case; when 5 => case Name (Name'First) is when 'a' | 'A' => case Name (Name'First + 1) is when 's' | 'S' => return Tag (Name, "aside", ASIDE_TAG); when 'u' | 'U' => return Tag (Name, "audio", AUDIO_TAG); when others => return UNKNOWN_TAG; end case; when 'e' | 'E' => return Tag (Name, "embed", EMBED_TAG); when 'i' | 'I' => return Tag (Name, "input", INPUT_TAG); when 'l' | 'L' => return Tag (Name, "label", LABEL_TAG); when 'm' | 'M' => return Tag (Name, "meter", METER_TAG); when 'p' | 'P' => return Tag (Name, "param", PARAM_TAG); when 's' | 'S' => case Name (Name'First + 1) is when 't' | 'T' => return Tag (Name, "style", STYLE_TAG); when 'm' | 'M' => return Tag (Name, "small", SMALL_TAG); when others => return UNKNOWN_TAG; end case; when 't' | 'T' => case Name (Name'First + 1) is when 'i' | 'I' => return Tag (Name, "title", TITLE_TAG); when 'r' | 'R' => return Tag (Name, "track", TRACK_TAG); when 'a' | 'A' => return Tag (Name, "table", TABLE_TAG); when 'b' | 'B' => return Tag (Name, "tbody", TBODY_TAG); when 'h' | 'H' => return Tag (Name, "thead", THEAD_TAG); when 'f' | 'F' => return Tag (Name, "tfoot", TFOOT_TAG); when others => return UNKNOWN_TAG; end case; when 'v' | 'V' => return Tag (Name, "video", VIDEO_TAG); when others => return UNKNOWN_TAG; end case; when others => case Name (Name'First) is when 'a' | 'A' => case Name (Name'First + 1) is when 'r' | 'R' => return Tag (Name, "article", ARTICLE_TAG); when 'd' | 'D' => return Tag (Name, "address", ADDRESS_TAG); when others => return UNKNOWN_TAG; end case; when 'b' | 'B' => case Name (Name'First + 1) is when 'l' | 'L' => return Tag (Name, "blockquote", BLOCKQUOTE_TAG); when 'u' | 'U' => return Tag (Name, "button", BUTTON_TAG); when others => return UNKNOWN_TAG; end case; when 'c' | 'C' => case Name (Name'First + 2) is when 'p' | 'P' => return Tag (Name, "caption", CAPTION_TAG); when 'l' | 'L' => return Tag (Name, "colgroup", COLGROUP_TAG); when 'n' | 'N' => return Tag (Name, "canvas", CANVAS_TAG); when others => return UNKNOWN_TAG; end case; when 'd' | 'D' => return Tag (Name, "datalist", DATALIST_TAG); when 'f' | 'F' => case Name (Name'Last) is when 'r' | 'R' => return Tag (Name, "footer", FOOTER_TAG); when 'e' | 'E' => return Tag (Name, "figure", FIGURE_TAG); when 'n' | 'N' => return Tag (Name, "figcaption", FIGCAPTION_TAG); when 't' | 'T' => return Tag (Name, "fieldset", FIELDSET_TAG); when others => return UNKNOWN_TAG; end case; when 'h' | 'H' => return Tag (Name, "header", HEADER_TAG); when 'i' | 'I' => return Tag (Name, "iframe", IFRAME_TAG); when 'k' | 'K' => return Tag (Name, "keygen", KEYGEN_TAG); when 'l' | 'L' => return Tag (Name, "legend", LEGEND_TAG); when 'n' | 'N' => return Tag (Name, "noscript", NOSCRIPT_TAG); when 'o' | 'O' => case Name (Name'First + 3) is when 'e' | 'E' => return Tag (Name, "object", OBJECT_TAG); when 'g' | 'G' => return Tag (Name, "optgroup", OPTGROUP_TAG); when 'i' | 'I' => return Tag (Name, "option", OPTION_TAG); when 'p' | 'P' => return Tag (Name, "output", OUTPUT_TAG); when others => return UNKNOWN_TAG; end case; when 'p' | 'P' => return Tag (Name, "progress", PROGRESS_TAG); when 's' | 'S' => case Name (Name'First + 3) is when 't' | 'T' => return Tag (Name, "section", SECTION_TAG); when 'o' | 'O' => return Tag (Name, "strong", STRONG_TAG); when 'r' | 'R' => return Tag (Name, "source", SOURCE_TAG); when 'e' | 'E' => return Tag (Name, "select", SELECT_TAG); when 'i' | 'I' => return Tag (Name, "script", SCRIPT_TAG); when others => return UNKNOWN_TAG; end case; when 't' | 'T' => case Name (Name'Last) is when 'a' | 'A' => return Tag (Name, "textarea", TEXTAREA_TAG); when 'e' | 'E' => return Tag (Name, "template", TEMPLATE_TAG); when others => return UNKNOWN_TAG; end case; when others => return UNKNOWN_TAG; end case; end case; end Find_Tag; -- ------------------------------ -- Create a text node. -- ------------------------------ function Create_Text (Text : in WString) return Node_Type_Access is begin return new Node_Type '(Kind => N_TEXT, Len => Text'Length, Text => Text, others => <>); end Create_Text; -- ------------------------------ -- 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) is Node : constant Node_Type_Access := new Node_Type '(Kind => N_TAG_START, Len => 0, Tag_Start => Tag, Attributes => Attributes, Children => null, Parent => Document.Current); begin Append (Document.Nodes, Node); Document.Current := Node; end Add_Tag; procedure End_Tag (Document : in out Wiki.Nodes.Document; Tag : in Html_Tag_Type) is begin if Document.Current /= null then Document.Current := Document.Current.Parent; end if; end End_Tag; -- ------------------------------ -- Append a node to the document. -- ------------------------------ procedure Append (Into : in out Document; Node : in Node_Type_Access) is begin if Into.Current = null then Append (Into.Nodes, Node); else if Into.Current.Children = null then Into.Current.Children := new Node_List; end if; Append (Into.Current.Children.all, Node); end if; end Append; -- ------------------------------ -- 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) is begin case Kind is when N_LINE_BREAK => Append (Into, new Node_Type '(Kind => N_LINE_BREAK, Len => 0)); when N_HORIZONTAL_RULE => Append (Into, new Node_Type '(Kind => N_HORIZONTAL_RULE, Len => 0)); when N_PARAGRAPH => Append (Into, new Node_Type '(Kind => N_PARAGRAPH, Len => 0)); end case; end Append; -- ------------------------------ -- Append a node to the node list. -- ------------------------------ procedure Append (Into : in out Node_List; Node : in Node_Type_Access) is Block : Node_List_Block_Access := Into.Current; begin if Block.Last = Block.Max then Block.Next := new Node_List_Block (Into.Length); Block := Block.Next; Into.Current := Block; end if; Block.Last := Block.Last + 1; Block.List (Block.Last) := Node; Into.Length := Into.Length + 1; end Append; end Wiki.Nodes;
Implement Find_Tag procedure (from Wiki.Filters.Html package)
Implement Find_Tag procedure (from Wiki.Filters.Html package)
Ada
apache-2.0
stcarrez/ada-wiki,stcarrez/ada-wiki
a81b1665c741970730e4ae00e8cfc6a54e2ebdd0
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 subtype Format_Map is Wiki.Documents.Format_Map; subtype WString is Wide_Wide_String; type Node_Kind is (N_HEADER, N_LINE_BREAK, N_HORIZONTAL_RULE, N_PARAGRAPH, N_BLOCKQUOTE, N_QUOTE, N_TAG_START, N_TAG_END, N_INDENT, N_TEXT, N_LINK, N_IMAGE); -- 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 Node_List is limited private; type Node_List_Access is access all Node_List; 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 : Wiki.Attributes.Attribute_List_Type; when N_QUOTE => Quote : WString (1 .. Len); when N_TAG_START => Tag_Start : Html_Tag_Type; Attributes : Wiki.Attributes.Attribute_List_Type; Children : Node_List_Access; when N_TAG_END => Tag_End : Html_Tag_Type; when others => null; end case; end record; type Node_Type_Access is access all Node_Type; type Document_Node_Access is private; type Document is limited private; -- Create a text node. function Create_Text (Text : in WString) return Node_Type_Access; -- 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_Node; type Document_Node_Access is access all Document_Node; type Document_Node (Kind : Node_Kind; Len : Natural) is limited record Next : Document_Node_Access; Prev : Document_Node_Access; Data : Node_Type (Kind, Len); end record; type Document is limited record First : Document_Node_Access; Last : Document_Node_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 subtype Format_Map is Wiki.Documents.Format_Map; subtype WString is Wide_Wide_String; type Node_Kind is (N_HEADER, N_LINE_BREAK, N_HORIZONTAL_RULE, N_PARAGRAPH, N_BLOCKQUOTE, N_QUOTE, N_TAG_START, N_TAG_END, N_INDENT, N_TEXT, N_LINK, N_IMAGE); -- 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 Node_List is limited private; type Node_List_Access is access all Node_List; 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 : Wiki.Attributes.Attribute_List_Type; when N_QUOTE => Quote : WString (1 .. Len); when N_TAG_START => Tag_Start : Html_Tag_Type; Attributes : Wiki.Attributes.Attribute_List_Type; Children : Node_List_Access; when N_TAG_END => Tag_End : Html_Tag_Type; when others => null; end case; end record; type Node_Type_Access is access all Node_Type; -- Create a text node. function Create_Text (Text : in WString) return Node_Type_Access; -- 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; end record; end Wiki.Nodes;
Remove Document_Node type and use the Node_List for the Document type
Remove Document_Node type and use the Node_List for the Document type
Ada
apache-2.0
stcarrez/ada-wiki,stcarrez/ada-wiki
fce3c4215f2288d770733561b0ff3b32b79a6e12
mat/src/matp.adb
mat/src/matp.adb
----------------------------------------------------------------------- -- mat-types -- Global types -- 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.IO_Exceptions; with MAT.Commands; with MAT.Targets; with MAT.Consoles.Text; with MAT.Readers.Streams.Sockets; procedure Matp is Target : MAT.Targets.Target_Type; Options : MAT.Commands.Options_Type; Console : aliased MAT.Consoles.Text.Console_Type; Server : MAT.Readers.Streams.Sockets.Socket_Listener_Type; begin Target.Console (Console'Unchecked_Access); MAT.Commands.Initialize_Options (Target, Options); MAT.Commands.Initialize_Files (Target); Server.Start (Options.Address); MAT.Commands.Interactive (Target); Server.Stop; exception when Ada.IO_Exceptions.End_Error | MAT.Commands.Usage_Error => Server.Stop; end Matp;
----------------------------------------------------------------------- -- mat-types -- Global types -- 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.IO_Exceptions; with MAT.Commands; with MAT.Targets; with MAT.Consoles.Text; with MAT.Readers.Streams.Sockets; procedure Matp is Target : MAT.Targets.Target_Type; Console : aliased MAT.Consoles.Text.Console_Type; Server : MAT.Readers.Streams.Sockets.Socket_Listener_Type; begin Target.Console (Console'Unchecked_Access); Target.Initialize_Options; MAT.Commands.Initialize_Files (Target); Server.Start (Options.Address); MAT.Commands.Interactive (Target); Server.Stop; exception when Ada.IO_Exceptions.End_Error | MAT.Targets.Usage_Error => Server.Stop; end Matp;
Update to use the target Initialize_Options procedure
Update to use the target Initialize_Options procedure
Ada
apache-2.0
stcarrez/mat,stcarrez/mat,stcarrez/mat
62c258cd3d17eeff14d77c3d8a426eafc556c9a9
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 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES 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.Applications; with ADO; with AWA.Modules; with AWA.Blogs.Models; with Security.Permissions; -- The <b>Blogs.Module</b> manages the creation, update, removal of blog posts in an application. -- package AWA.Blogs.Modules is NAME : constant String := "blogs"; -- 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"); 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); -- 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; Workspace_Id : in ADO.Identifier; 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; 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; 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); private type Blog_Module is new AWA.Modules.Module with null record; end AWA.Blogs.Modules;
----------------------------------------------------------------------- -- awa-blogs-module -- Blog and post management module -- 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 ASF.Applications; with ADO; with AWA.Modules; with AWA.Blogs.Models; with Security.Permissions; -- The <b>Blogs.Module</b> manages the creation, update, removal of blog posts in an application. -- package AWA.Blogs.Modules is NAME : constant String := "blogs"; -- 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"); 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); -- 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; Workspace_Id : in ADO.Identifier; 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); private type Blog_Module is new AWA.Modules.Module with null record; end AWA.Blogs.Modules;
Add a parameter to setup the allow comment flag
Add a parameter to setup the allow comment flag
Ada
apache-2.0
tectronics/ada-awa,tectronics/ada-awa,tectronics/ada-awa,Letractively/ada-awa,Letractively/ada-awa,Letractively/ada-awa
241ef6a7b2fa42ec2ef02d60440b88db03e804bf
src/asf-components-core-views.ads
src/asf-components-core-views.ads
----------------------------------------------------------------------- -- components-core-views -- ASF View Components -- Copyright (C) 2009, 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.Beans.Objects; with Util.Locales; with ASF.Events.Faces; with ASF.Lifecycles; with ASF.Components.Html.Forms; with ASF.Components.Core; with ASF.Views.Nodes; private with Ada.Containers.Vectors; package ASF.Components.Core.Views is -- Name of the facet that holds the metadata information -- (we use the same name as JSF 2 specification). METADATA_FACET_NAME : constant String := "javax_faces_metadata"; -- ------------------------------ -- View component -- ------------------------------ type UIView is new Core.UIComponentBase with private; type UIView_Access is access all UIView'Class; -- Get the content type returned by the view. function Get_Content_Type (UI : in UIView; Context : in Faces_Context'Class) return String; -- Set the content type returned by the view. procedure Set_Content_Type (UI : in out UIView; Value : in String); -- Get the locale to be used when rendering messages in the view. -- If a locale was set explicitly, return it. -- If the view component defines a <b>locale</b> attribute, evaluate and return its value. -- If the locale is empty, calculate the locale by using the request context and the view -- handler. function Get_Locale (UI : in UIView; Context : in Faces_Context'Class) return Util.Locales.Locale; -- Set the locale to be used when rendering messages in the view. procedure Set_Locale (UI : in out UIView; Locale : in Util.Locales.Locale); -- Encode the begining of the view. Set the response content type. overriding procedure Encode_Begin (UI : in UIView; Context : in out Faces_Context'Class); -- Encode the end of the view. overriding procedure Encode_End (UI : in UIView; Context : in out Faces_Context'Class); -- Decode any new state of the specified component from the request contained -- in the specified context and store that state on the component. -- -- During decoding, events may be enqueued for later processing -- (by event listeners that have registered an interest), by calling -- the <b>Queue_Event</b> on the associated component. overriding procedure Process_Decodes (UI : in out UIView; Context : in out Faces_Context'Class); -- Perform the component tree processing required by the <b>Process Validations</b> -- phase of the request processing lifecycle for all facets of this component, -- all children of this component, and this component itself, as follows: -- <ul> -- <li>If this component <b>rendered</b> property is false, skip further processing. -- <li>Call the <b>Process_Validators</b> of all facets and children. -- <ul> overriding procedure Process_Validators (UI : in out UIView; Context : in out Faces_Context'Class); -- Perform the component tree processing required by the <b>Update Model Values</b> -- phase of the request processing lifecycle for all facets of this component, -- all children of this component, and this component itself, as follows. -- <ul> -- <li>If this component <b>rendered</b> property is false, skip further processing. -- <li>Call the <b>Process_Updates/b> of all facets and children. -- <ul> overriding procedure Process_Updates (UI : in out UIView; Context : in out Faces_Context'Class); -- Broadcast any events that have been queued for the <b>Invoke Application</b> -- phase of the request processing lifecycle and to clear out any events -- for later phases if the event processing for this phase caused -- <b>renderResponse</b> or <b>responseComplete</b> to be called. procedure Process_Application (UI : in out UIView; Context : in out Faces_Context'Class); -- Queue an event for broadcast at the end of the current request -- processing lifecycle phase. The event object -- will be freed after being dispatched. procedure Queue_Event (UI : in out UIView; Event : not null access ASF.Events.Faces.Faces_Event'Class); -- Broadcast the events after the specified lifecycle phase. -- Events that were queued will be freed. procedure Broadcast (UI : in out UIView; Phase : in ASF.Lifecycles.Phase_Type; Context : in out Faces_Context'Class); -- Clear the events that were queued. procedure Clear_Events (UI : in out UIView); -- Set the component tree that must be rendered before this view. -- This is an internal method used by Steal_Root_Component exclusively. procedure Set_Before_View (UI : in out UIView'Class; Tree : in Base.UIComponent_Access); -- Set the component tree that must be rendered after this view. -- This is an internal method used by Steal_Root_Component exclusively. procedure Set_After_View (UI : in out UIView'Class; Tree : in Base.UIComponent_Access); -- Finalize the object. overriding procedure Finalize (UI : in out UIView); -- ------------------------------ -- View Parameter Component -- ------------------------------ -- The <b>UIViewParameter</b> component represents a request parameter that must be mapped -- to a backed bean object. This component does not participate in the rendering. type UIViewParameter is new Html.Forms.UIInput with private; type UIViewParameter_Access is access all UIViewParameter'Class; -- Get the input parameter from the submitted context. This operation is called by -- <tt>Process_Decodes</tt> to retrieve the request parameter associated with the component. overriding function Get_Parameter (UI : in UIViewParameter; Context : in Faces_Context'Class) return String; -- ------------------------------ -- View Action Component -- ------------------------------ -- The <b>UIViewAction</b> component implements the view action tag defined by Jave Server -- Faces 2.2. This action defined by that tag will be called type UIViewAction is new Html.Forms.UICommand with private; type UIViewAction_Access is access all UIViewAction'Class; -- Decode the request and prepare for the execution for the view action. overriding procedure Process_Decodes (UI : in out UIViewAction; Context : in out Faces_Context'Class); -- ------------------------------ -- View Metadata Component -- ------------------------------ -- The <b>UIViewMetaData</b> component defines the view meta data components. -- These components defines how to handle some request parameters for a GET request -- as well as some actions that must be made upon reception of a request. -- -- From ASF lifecycle management, if the request is a GET, this component is used -- as the root of the component tree. The APPLY_REQUESTS .. INVOKE_APPLICATION actions -- are called on that component tree. It is also used for the RENDER_RESPONSE, and -- we have to propagate the rendering on the real view root. Therefore, the Encode_XXX -- operations are overriden to propagate on the real root. type UIViewMetaData is new UIView with private; type UIViewMetaData_Access is access all UIViewMetaData'Class; -- Start encoding the UIComponent. overriding procedure Encode_Begin (UI : in UIViewMetaData; Context : in out Faces_Context'Class); -- Encode the children of this component. overriding procedure Encode_Children (UI : in UIViewMetaData; Context : in out Faces_Context'Class); -- Finish encoding the component. overriding procedure Encode_End (UI : in UIViewMetaData; Context : in out Faces_Context'Class); -- Queue an event for broadcast at the end of the current request -- processing lifecycle phase. The event object -- will be freed after being dispatched. overriding procedure Queue_Event (UI : in out UIViewMetaData; Event : not null access ASF.Events.Faces.Faces_Event'Class); -- Broadcast the events after the specified lifecycle phase. -- Events that were queued will be freed. overriding procedure Broadcast (UI : in out UIViewMetaData; Phase : in ASF.Lifecycles.Phase_Type; Context : in out Faces_Context'Class); -- Clear the events that were queued. overriding procedure Clear_Events (UI : in out UIViewMetaData); -- Get the root component. function Get_Root (UI : in UIViewMetaData) return Base.UIComponent_Access; -- Set the metadata facet on the UIView component. procedure Set_Metadata (UI : in out UIView; Meta : in UIViewMetaData_Access; Tag : access ASF.Views.Nodes.Tag_Node'Class); private use ASF.Lifecycles; type Faces_Event_Access is access all ASF.Events.Faces.Faces_Event'Class; package Event_Vectors is new Ada.Containers.Vectors (Index_Type => Natural, Element_Type => Faces_Event_Access); type Event_Queues is array (Phase_Type) of Event_Vectors.Vector; type UIView is new Core.UIComponentBase with record Content_Type : Util.Beans.Objects.Object; Phase_Events : Event_Queues; Meta : UIViewMetaData_Access := null; Locale : Util.Locales.Locale := Util.Locales.NULL_LOCALE; Left_Tree : Base.UIComponent_Access := null; Right_Tree : Base.UIComponent_Access := null; end record; type UIViewParameter is new Html.Forms.UIInput with record Name : Ada.Strings.Unbounded.Unbounded_String; end record; type UIViewAction is new Html.Forms.UICommand with null record; type UIViewMetaData is new UIView with record Root : UIView_Access := null; end record; end ASF.Components.Core.Views;
----------------------------------------------------------------------- -- components-core-views -- ASF View Components -- Copyright (C) 2009, 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.Beans.Objects; with Util.Locales; with ASF.Events.Faces; with ASF.Lifecycles; with ASF.Components.Html.Forms; with ASF.Components.Core; with ASF.Views.Nodes; private with Ada.Containers.Vectors; package ASF.Components.Core.Views is -- Name of the facet that holds the metadata information -- (we use the same name as JSF 2 specification). METADATA_FACET_NAME : constant String := "javax_faces_metadata"; type UIViewMetaData; type UIViewMetaData_Access is access all UIViewMetaData'Class; -- ------------------------------ -- View component -- ------------------------------ type UIView is new Core.UIComponentBase with private; type UIView_Access is access all UIView'Class; -- Get the content type returned by the view. function Get_Content_Type (UI : in UIView; Context : in Faces_Context'Class) return String; -- Set the content type returned by the view. procedure Set_Content_Type (UI : in out UIView; Value : in String); -- Get the locale to be used when rendering messages in the view. -- If a locale was set explicitly, return it. -- If the view component defines a <b>locale</b> attribute, evaluate and return its value. -- If the locale is empty, calculate the locale by using the request context and the view -- handler. function Get_Locale (UI : in UIView; Context : in Faces_Context'Class) return Util.Locales.Locale; -- Set the locale to be used when rendering messages in the view. procedure Set_Locale (UI : in out UIView; Locale : in Util.Locales.Locale); -- Encode the begining of the view. Set the response content type. overriding procedure Encode_Begin (UI : in UIView; Context : in out Faces_Context'Class); -- Encode the end of the view. overriding procedure Encode_End (UI : in UIView; Context : in out Faces_Context'Class); -- Decode any new state of the specified component from the request contained -- in the specified context and store that state on the component. -- -- During decoding, events may be enqueued for later processing -- (by event listeners that have registered an interest), by calling -- the <b>Queue_Event</b> on the associated component. overriding procedure Process_Decodes (UI : in out UIView; Context : in out Faces_Context'Class); -- Perform the component tree processing required by the <b>Process Validations</b> -- phase of the request processing lifecycle for all facets of this component, -- all children of this component, and this component itself, as follows: -- <ul> -- <li>If this component <b>rendered</b> property is false, skip further processing. -- <li>Call the <b>Process_Validators</b> of all facets and children. -- <ul> overriding procedure Process_Validators (UI : in out UIView; Context : in out Faces_Context'Class); -- Perform the component tree processing required by the <b>Update Model Values</b> -- phase of the request processing lifecycle for all facets of this component, -- all children of this component, and this component itself, as follows. -- <ul> -- <li>If this component <b>rendered</b> property is false, skip further processing. -- <li>Call the <b>Process_Updates/b> of all facets and children. -- <ul> overriding procedure Process_Updates (UI : in out UIView; Context : in out Faces_Context'Class); -- Broadcast any events that have been queued for the <b>Invoke Application</b> -- phase of the request processing lifecycle and to clear out any events -- for later phases if the event processing for this phase caused -- <b>renderResponse</b> or <b>responseComplete</b> to be called. procedure Process_Application (UI : in out UIView; Context : in out Faces_Context'Class); -- Queue an event for broadcast at the end of the current request -- processing lifecycle phase. The event object -- will be freed after being dispatched. procedure Queue_Event (UI : in out UIView; Event : not null access ASF.Events.Faces.Faces_Event'Class); -- Broadcast the events after the specified lifecycle phase. -- Events that were queued will be freed. procedure Broadcast (UI : in out UIView; Phase : in ASF.Lifecycles.Phase_Type; Context : in out Faces_Context'Class); -- Clear the events that were queued. procedure Clear_Events (UI : in out UIView); -- Set the component tree that must be rendered before this view. -- This is an internal method used by Steal_Root_Component exclusively. procedure Set_Before_View (UI : in out UIView'Class; Tree : in Base.UIComponent_Access); -- Set the component tree that must be rendered after this view. -- This is an internal method used by Steal_Root_Component exclusively. procedure Set_After_View (UI : in out UIView'Class; Tree : in Base.UIComponent_Access); -- Set the metadata facet on the UIView component. procedure Set_Metadata (UI : in out UIView; Meta : in UIViewMetaData_Access; Tag : access ASF.Views.Nodes.Tag_Node'Class); -- Finalize the object. overriding procedure Finalize (UI : in out UIView); -- ------------------------------ -- View Parameter Component -- ------------------------------ -- The <b>UIViewParameter</b> component represents a request parameter that must be mapped -- to a backed bean object. This component does not participate in the rendering. type UIViewParameter is new Html.Forms.UIInput with private; type UIViewParameter_Access is access all UIViewParameter'Class; -- Get the input parameter from the submitted context. This operation is called by -- <tt>Process_Decodes</tt> to retrieve the request parameter associated with the component. overriding function Get_Parameter (UI : in UIViewParameter; Context : in Faces_Context'Class) return String; -- ------------------------------ -- View Action Component -- ------------------------------ -- The <b>UIViewAction</b> component implements the view action tag defined by Jave Server -- Faces 2.2. This action defined by that tag will be called type UIViewAction is new Html.Forms.UICommand with private; type UIViewAction_Access is access all UIViewAction'Class; -- Decode the request and prepare for the execution for the view action. overriding procedure Process_Decodes (UI : in out UIViewAction; Context : in out Faces_Context'Class); -- ------------------------------ -- View Metadata Component -- ------------------------------ -- The <b>UIViewMetaData</b> component defines the view meta data components. -- These components defines how to handle some request parameters for a GET request -- as well as some actions that must be made upon reception of a request. -- -- From ASF lifecycle management, if the request is a GET, this component is used -- as the root of the component tree. The APPLY_REQUESTS .. INVOKE_APPLICATION actions -- are called on that component tree. It is also used for the RENDER_RESPONSE, and -- we have to propagate the rendering on the real view root. Therefore, the Encode_XXX -- operations are overriden to propagate on the real root. type UIViewMetaData is new UIView with private; -- Start encoding the UIComponent. overriding procedure Encode_Begin (UI : in UIViewMetaData; Context : in out Faces_Context'Class); -- Encode the children of this component. overriding procedure Encode_Children (UI : in UIViewMetaData; Context : in out Faces_Context'Class); -- Finish encoding the component. overriding procedure Encode_End (UI : in UIViewMetaData; Context : in out Faces_Context'Class); -- Queue an event for broadcast at the end of the current request -- processing lifecycle phase. The event object -- will be freed after being dispatched. overriding procedure Queue_Event (UI : in out UIViewMetaData; Event : not null access ASF.Events.Faces.Faces_Event'Class); -- Broadcast the events after the specified lifecycle phase. -- Events that were queued will be freed. overriding procedure Broadcast (UI : in out UIViewMetaData; Phase : in ASF.Lifecycles.Phase_Type; Context : in out Faces_Context'Class); -- Clear the events that were queued. overriding procedure Clear_Events (UI : in out UIViewMetaData); -- Get the root component. function Get_Root (UI : in UIViewMetaData) return Base.UIComponent_Access; private use ASF.Lifecycles; type Faces_Event_Access is access all ASF.Events.Faces.Faces_Event'Class; package Event_Vectors is new Ada.Containers.Vectors (Index_Type => Natural, Element_Type => Faces_Event_Access); type Event_Queues is array (Phase_Type) of Event_Vectors.Vector; type UIView is new Core.UIComponentBase with record Content_Type : Util.Beans.Objects.Object; Phase_Events : Event_Queues; Meta : UIViewMetaData_Access := null; Locale : Util.Locales.Locale := Util.Locales.NULL_LOCALE; Left_Tree : Base.UIComponent_Access := null; Right_Tree : Base.UIComponent_Access := null; end record; type UIViewParameter is new Html.Forms.UIInput with record Name : Ada.Strings.Unbounded.Unbounded_String; end record; type UIViewAction is new Html.Forms.UICommand with null record; type UIViewMetaData is new UIView with record Root : UIView_Access := null; end record; end ASF.Components.Core.Views;
Declare Set_Metadata procedure before overriding the tagged type
Declare Set_Metadata procedure before overriding the tagged type
Ada
apache-2.0
stcarrez/ada-asf,stcarrez/ada-asf,stcarrez/ada-asf
e814512c876482417ae6eb42f53df455563644a0
src/wiki-render-wiki.ads
src/wiki-render-wiki.ads
----------------------------------------------------------------------- -- wiki-render-wiki -- Wiki to 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_Maps; with Ada.Strings.Wide_Wide_Unbounded; with Wiki.Documents; with Wiki.Attributes; with Wiki.Streams; with Wiki.Strings; -- == Wiki Renderer == -- The <tt>Wiki_Renderer</tt> allows to render a wiki document into another wiki content. -- The formatting rules are ignored except for the paragraphs and sections. package Wiki.Render.Wiki is use Standard.Wiki.Attributes; -- ------------------------------ -- Wiki to HTML writer -- ------------------------------ type Wiki_Renderer is new Renderer with private; -- Set the output stream. procedure Set_Output_Stream (Engine : in out Wiki_Renderer; Stream : in Streams.Output_Stream_Access; Format : in Wiki_Syntax); -- Render the node instance from the document. overriding procedure Render (Engine : in out Wiki_Renderer; Doc : in Documents.Document; Node : in Nodes.Node_Type); -- Add a section header in the document. procedure Render_Header (Engine : in out Wiki_Renderer; Header : in Wide_Wide_String; Level : in Positive); -- Add a paragraph (<p>). Close the previous paragraph if any. -- The paragraph must be closed at the next paragraph or next header. procedure Add_Paragraph (Engine : in out Wiki_Renderer); -- Add a blockquote (<blockquote>). The level indicates the blockquote nested level. -- The blockquote must be closed at the next header. procedure Add_Blockquote (Engine : in out Wiki_Renderer; Level : in Natural); -- 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 (Engine : in out Wiki_Renderer; Level : in Positive; Ordered : in Boolean); -- Render a link. procedure Render_Link (Engine : in out Wiki_Renderer; Name : in Strings.WString; Attrs : in Attributes.Attribute_List); -- Render an image. procedure Render_Image (Engine : in out Wiki_Renderer; Link : in Strings.WString; Attrs : in Attributes.Attribute_List); -- Render a quote. procedure Render_Quote (Engine : in out Wiki_Renderer; Title : in Strings.WString; Attrs : in Attributes.Attribute_List); -- Add a text block with the given format. procedure Render_Text (Engine : in out Wiki_Renderer; Text : in Wide_Wide_String; Format : in Format_Map); -- Render a text block that is pre-formatted. procedure Render_Preformatted (Engine : in out Wiki_Renderer; Text : in Strings.WString; Format : in Strings.WString); procedure Render_Tag (Engine : in out Wiki_Renderer; Doc : in Documents.Document; Node : in Nodes.Node_Type); -- Finish the document after complete wiki text has been parsed. procedure Finish (Engine : in out Wiki_Renderer; Doc : in Documents.Document); -- Set the text style format. procedure Set_Format (Engine : in out Wiki_Renderer; Format : in Format_Map); private use Ada.Strings.Wide_Wide_Unbounded; type Wide_String_Access is access constant Wide_Wide_String; type Wiki_Tag_Type is (Header_Start, Header_End, Img_Start, Img_End, Link_Start, Link_End, Link_Separator, Preformat_Start, Preformat_End, List_Start, List_Item, List_Ordered_Item, Line_Break, Escape_Rule, Horizontal_Rule, Blockquote_Start, Blockquote_End); type Wiki_Tag_Array is array (Wiki_Tag_Type) of Wide_String_Access; type Wiki_Format_Array is array (Format_Type) of Wide_String_Access; -- Emit a new line. procedure New_Line (Engine : in out Wiki_Renderer); procedure Close_Paragraph (Engine : in out Wiki_Renderer); procedure Open_Paragraph (Engine : in out Wiki_Renderer); procedure Start_Keep_Content (Engine : in out Wiki_Renderer); type List_Style_Array is array (1 .. 32) of Boolean; EMPTY_TAG : aliased constant Wide_Wide_String := ""; type Wiki_Renderer is new Renderer with record Output : Streams.Output_Stream_Access := null; Syntax : Wiki_Syntax := SYNTAX_CREOLE; Format : Format_Map := (others => False); Tags : Wiki_Tag_Array := (others => EMPTY_TAG'Access); Style_Start_Tags : Wiki_Format_Array := (others => EMPTY_TAG'Access); Style_End_Tags : Wiki_Format_Array := (others => EMPTY_TAG'Access); Escape_Set : Ada.Strings.Wide_Wide_Maps.Wide_Wide_Character_Set; Has_Paragraph : Boolean := False; Has_Item : Boolean := False; Need_Paragraph : Boolean := False; Empty_Line : Boolean := True; Keep_Content : Boolean := False; In_List : Boolean := False; Invert_Header_Level : Boolean := False; Allow_Link_Language : Boolean := False; Current_Level : Natural := 0; Quote_Level : Natural := 0; UL_List_Level : Natural := 0; OL_List_Level : Natural := 0; Current_Style : Format_Map := (others => False); Content : Unbounded_Wide_Wide_String; Link_Href : Unbounded_Wide_Wide_String; Link_Title : Unbounded_Wide_Wide_String; Link_Lang : Unbounded_Wide_Wide_String; end record; end Wiki.Render.Wiki;
----------------------------------------------------------------------- -- wiki-render-wiki -- Wiki to Wiki renderer -- Copyright (C) 2015, 2016, 2020 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Strings.Wide_Wide_Maps; with Ada.Strings.Wide_Wide_Unbounded; with Wiki.Documents; with Wiki.Attributes; with Wiki.Streams; with Wiki.Strings; -- == Wiki Renderer == -- The <tt>Wiki_Renderer</tt> allows to render a wiki document into another wiki content. -- The formatting rules are ignored except for the paragraphs and sections. package Wiki.Render.Wiki is use Standard.Wiki.Attributes; -- ------------------------------ -- Wiki to HTML writer -- ------------------------------ type Wiki_Renderer is new Renderer with private; -- Set the output stream. procedure Set_Output_Stream (Engine : in out Wiki_Renderer; Stream : in Streams.Output_Stream_Access; Format : in Wiki_Syntax); -- Render the node instance from the document. overriding procedure Render (Engine : in out Wiki_Renderer; Doc : in Documents.Document; Node : in Nodes.Node_Type); -- Add a section header in the document. procedure Render_Header (Engine : in out Wiki_Renderer; Header : in Wide_Wide_String; Level : in Positive); -- Add a paragraph (<p>). Close the previous paragraph if any. -- The paragraph must be closed at the next paragraph or next header. procedure Add_Paragraph (Engine : in out Wiki_Renderer); -- Add a blockquote (<blockquote>). The level indicates the blockquote nested level. -- The blockquote must be closed at the next header. procedure Add_Blockquote (Engine : in out Wiki_Renderer; Level : in Natural); -- 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 (Engine : in out Wiki_Renderer; Level : in Positive; Ordered : in Boolean); -- Render a link. procedure Render_Link (Engine : in out Wiki_Renderer; Name : in Strings.WString; Attrs : in Attributes.Attribute_List); -- Render an image. procedure Render_Image (Engine : in out Wiki_Renderer; Link : in Strings.WString; Attrs : in Attributes.Attribute_List); -- Render a quote. procedure Render_Quote (Engine : in out Wiki_Renderer; Title : in Strings.WString; Attrs : in Attributes.Attribute_List); -- Add a text block with the given format. procedure Render_Text (Engine : in out Wiki_Renderer; Text : in Wide_Wide_String; Format : in Format_Map); -- Render a text block that is pre-formatted. procedure Render_Preformatted (Engine : in out Wiki_Renderer; Text : in Strings.WString; Format : in Strings.WString); procedure Render_Tag (Engine : in out Wiki_Renderer; Doc : in Documents.Document; Node : in Nodes.Node_Type); -- Finish the document after complete wiki text has been parsed. procedure Finish (Engine : in out Wiki_Renderer; Doc : in Documents.Document); -- Set the text style format. procedure Set_Format (Engine : in out Wiki_Renderer; Format : in Format_Map); private use Ada.Strings.Wide_Wide_Unbounded; type Wide_String_Access is access constant Wide_Wide_String; type Wiki_Tag_Type is (Header_Start, Header_End, Img_Start, Img_End, Link_Start, Link_End, Link_Separator, Quote_Start, Quote_End, Quote_Separator, Preformat_Start, Preformat_End, List_Start, List_Item, List_Ordered_Item, Line_Break, Escape_Rule, Horizontal_Rule, Blockquote_Start, Blockquote_End); type Wiki_Tag_Array is array (Wiki_Tag_Type) of Wide_String_Access; type Wiki_Format_Array is array (Format_Type) of Wide_String_Access; -- Emit a new line. procedure New_Line (Engine : in out Wiki_Renderer); procedure Close_Paragraph (Engine : in out Wiki_Renderer); procedure Open_Paragraph (Engine : in out Wiki_Renderer); procedure Start_Keep_Content (Engine : in out Wiki_Renderer); type List_Style_Array is array (1 .. 32) of Boolean; EMPTY_TAG : aliased constant Wide_Wide_String := ""; type Wiki_Renderer is new Renderer with record Output : Streams.Output_Stream_Access := null; Syntax : Wiki_Syntax := SYNTAX_CREOLE; Format : Format_Map := (others => False); Tags : Wiki_Tag_Array := (others => EMPTY_TAG'Access); Style_Start_Tags : Wiki_Format_Array := (others => EMPTY_TAG'Access); Style_End_Tags : Wiki_Format_Array := (others => EMPTY_TAG'Access); Escape_Set : Ada.Strings.Wide_Wide_Maps.Wide_Wide_Character_Set; Has_Paragraph : Boolean := False; Has_Item : Boolean := False; Need_Paragraph : Boolean := False; Empty_Line : Boolean := True; Keep_Content : Boolean := False; In_List : Boolean := False; Invert_Header_Level : Boolean := False; Allow_Link_Language : Boolean := False; Current_Level : Natural := 0; Quote_Level : Natural := 0; UL_List_Level : Natural := 0; OL_List_Level : Natural := 0; Current_Style : Format_Map := (others => False); Content : Unbounded_Wide_Wide_String; Link_Href : Unbounded_Wide_Wide_String; Link_Title : Unbounded_Wide_Wide_String; Link_Lang : Unbounded_Wide_Wide_String; end record; end Wiki.Render.Wiki;
Add Quote_Start, Quote_End and Quote_Separator
Add Quote_Start, Quote_End and Quote_Separator
Ada
apache-2.0
stcarrez/ada-wiki,stcarrez/ada-wiki
e8539aed4f50c7d13f53b338d355a1682e6fb337
src/wiki-render-wiki.ads
src/wiki-render-wiki.ads
----------------------------------------------------------------------- -- wiki-render-wiki -- Wiki to 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.Documents; with Wiki.Attributes; with Wiki.Writers; with Wiki.Parsers; -- == Wiki Renderer == -- The <tt>Wiki_Renderer</tt> allows to render a wiki document into another wiki content. -- The formatting rules are ignored except for the paragraphs and sections. package Wiki.Render.Wiki is use Standard.Wiki.Attributes; -- ------------------------------ -- Wiki to HTML writer -- ------------------------------ type Wiki_Renderer is new Standard.Wiki.Documents.Document_Reader with private; -- Set the output writer. procedure Set_Writer (Document : in out Wiki_Renderer; Writer : in Writers.Writer_Type_Access; Format : in Parsers.Wiki_Syntax_Type); -- Add a section header in the document. overriding procedure Add_Header (Document : in out Wiki_Renderer; Header : in Unbounded_Wide_Wide_String; Level : in Positive); -- Add a line break (<br>). overriding procedure Add_Line_Break (Document : in out Wiki_Renderer); -- Add a paragraph (<p>). Close the previous paragraph if any. -- The paragraph must be closed at the next paragraph or next header. overriding procedure Add_Paragraph (Document : in out Wiki_Renderer); -- Add a blockquote (<blockquote>). The level indicates the blockquote nested level. -- The blockquote must be closed at the next header. overriding procedure Add_Blockquote (Document : in out Wiki_Renderer; Level : in Natural); -- 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. overriding procedure Add_List_Item (Document : in out Wiki_Renderer; Level : in Positive; Ordered : in Boolean); -- Add an horizontal rule (<hr>). overriding procedure Add_Horizontal_Rule (Document : in out Wiki_Renderer); -- Add a link. overriding procedure Add_Link (Document : in out Wiki_Renderer; Name : in Unbounded_Wide_Wide_String; Link : in Unbounded_Wide_Wide_String; Language : in Unbounded_Wide_Wide_String; Title : in Unbounded_Wide_Wide_String); -- Add an image. overriding procedure Add_Image (Document : in out Wiki_Renderer; Link : in Unbounded_Wide_Wide_String; Alt : in Unbounded_Wide_Wide_String; Position : in Unbounded_Wide_Wide_String; Description : in Unbounded_Wide_Wide_String); -- Add a quote. overriding procedure Add_Quote (Document : in out Wiki_Renderer; Quote : in Unbounded_Wide_Wide_String; Link : in Unbounded_Wide_Wide_String; Language : in Unbounded_Wide_Wide_String); -- Add a text block with the given format. overriding procedure Add_Text (Document : in out Wiki_Renderer; Text : in Unbounded_Wide_Wide_String; Format : in Documents.Format_Map); -- Add a text block that is pre-formatted. procedure Add_Preformatted (Document : in out Wiki_Renderer; Text : in Unbounded_Wide_Wide_String; Format : in Unbounded_Wide_Wide_String); overriding procedure Start_Element (Document : in out Wiki_Renderer; Name : in Unbounded_Wide_Wide_String; Attributes : in Attribute_List_Type); overriding procedure End_Element (Document : in out Wiki_Renderer; Name : in Unbounded_Wide_Wide_String); -- Finish the document after complete wiki text has been parsed. overriding procedure Finish (Document : in out Wiki_Renderer); private type Wide_String_Access is access constant Wide_Wide_String; type Wiki_Tag_Type is (Bold_Start, Bold_End, Italic_Start, Italic_End, Underline_Start, Underline_End, Header_Start, Header_End, Img_Start, Img_End, Link_Start, Link_End, Link_Separator, Preformat_Start, Preformat_End, Line_Break, Horizontal_Rule, Blockquote_Start, Blockquote_End); type Wiki_Tag_Array is array (Wiki_Tag_Type) of Wide_String_Access; -- Emit a new line. procedure New_Line (Document : in out Wiki_Renderer); procedure Close_Paragraph (Document : in out Wiki_Renderer); procedure Open_Paragraph (Document : in out Wiki_Renderer); procedure Start_Keep_Content (Document : in out Wiki_Renderer); type List_Style_Array is array (1 .. 32) of Boolean; EMPTY_TAG : aliased constant Wide_Wide_String := ""; type Wiki_Renderer is new Documents.Document_Reader with record Writer : Writers.Writer_Type_Access := null; Syntax : Parsers.Wiki_Syntax_Type := Parsers.SYNTAX_CREOLE; Format : Documents.Format_Map := (others => False); Tags : Wiki_Tag_Array := (others => EMPTY_TAG'Access); Has_Paragraph : Boolean := False; Has_Item : Boolean := False; Need_Paragraph : Boolean := False; Empty_Line : Boolean := True; Keep_Content : Boolean := False; Invert_Header_Level : Boolean := False; Allow_Link_Language : Boolean := False; Current_Level : Natural := 0; Quote_Level : Natural := 0; Current_Style : Documents.Format_Map := (others => False); Content : Unbounded_Wide_Wide_String; Link_Href : Unbounded_Wide_Wide_String; Link_Title : Unbounded_Wide_Wide_String; Link_Lang : Unbounded_Wide_Wide_String; end record; end Wiki.Render.Wiki;
----------------------------------------------------------------------- -- wiki-render-wiki -- Wiki to 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.Documents; with Wiki.Attributes; with Wiki.Writers; with Wiki.Parsers; -- == Wiki Renderer == -- The <tt>Wiki_Renderer</tt> allows to render a wiki document into another wiki content. -- The formatting rules are ignored except for the paragraphs and sections. package Wiki.Render.Wiki is use Standard.Wiki.Attributes; -- ------------------------------ -- Wiki to HTML writer -- ------------------------------ type Wiki_Renderer is new Standard.Wiki.Documents.Document_Reader with private; -- Set the output writer. procedure Set_Writer (Document : in out Wiki_Renderer; Writer : in Writers.Writer_Type_Access; Format : in Parsers.Wiki_Syntax_Type); -- Add a section header in the document. overriding procedure Add_Header (Document : in out Wiki_Renderer; Header : in Unbounded_Wide_Wide_String; Level : in Positive); -- Add a line break (<br>). overriding procedure Add_Line_Break (Document : in out Wiki_Renderer); -- Add a paragraph (<p>). Close the previous paragraph if any. -- The paragraph must be closed at the next paragraph or next header. overriding procedure Add_Paragraph (Document : in out Wiki_Renderer); -- Add a blockquote (<blockquote>). The level indicates the blockquote nested level. -- The blockquote must be closed at the next header. overriding procedure Add_Blockquote (Document : in out Wiki_Renderer; Level : in Natural); -- 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. overriding procedure Add_List_Item (Document : in out Wiki_Renderer; Level : in Positive; Ordered : in Boolean); -- Add an horizontal rule (<hr>). overriding procedure Add_Horizontal_Rule (Document : in out Wiki_Renderer); -- Add a link. overriding procedure Add_Link (Document : in out Wiki_Renderer; Name : in Unbounded_Wide_Wide_String; Link : in Unbounded_Wide_Wide_String; Language : in Unbounded_Wide_Wide_String; Title : in Unbounded_Wide_Wide_String); -- Add an image. overriding procedure Add_Image (Document : in out Wiki_Renderer; Link : in Unbounded_Wide_Wide_String; Alt : in Unbounded_Wide_Wide_String; Position : in Unbounded_Wide_Wide_String; Description : in Unbounded_Wide_Wide_String); -- Add a quote. overriding procedure Add_Quote (Document : in out Wiki_Renderer; Quote : in Unbounded_Wide_Wide_String; Link : in Unbounded_Wide_Wide_String; Language : in Unbounded_Wide_Wide_String); -- Add a text block with the given format. overriding procedure Add_Text (Document : in out Wiki_Renderer; Text : in Unbounded_Wide_Wide_String; Format : in Documents.Format_Map); -- Add a text block that is pre-formatted. procedure Add_Preformatted (Document : in out Wiki_Renderer; Text : in Unbounded_Wide_Wide_String; Format : in Unbounded_Wide_Wide_String); overriding procedure Start_Element (Document : in out Wiki_Renderer; Name : in Unbounded_Wide_Wide_String; Attributes : in Attribute_List_Type); overriding procedure End_Element (Document : in out Wiki_Renderer; Name : in Unbounded_Wide_Wide_String); -- Finish the document after complete wiki text has been parsed. overriding procedure Finish (Document : in out Wiki_Renderer); private type Wide_String_Access is access constant Wide_Wide_String; type Wiki_Tag_Type is (Bold_Start, Bold_End, Italic_Start, Italic_End, Underline_Start, Underline_End, Header_Start, Header_End, Img_Start, Img_End, Link_Start, Link_End, Link_Separator, Preformat_Start, Preformat_End, List_Start, List_Item, List_Ordered_Item, Line_Break, Horizontal_Rule, Blockquote_Start, Blockquote_End); type Wiki_Tag_Array is array (Wiki_Tag_Type) of Wide_String_Access; -- Emit a new line. procedure New_Line (Document : in out Wiki_Renderer); procedure Close_Paragraph (Document : in out Wiki_Renderer); procedure Open_Paragraph (Document : in out Wiki_Renderer); procedure Start_Keep_Content (Document : in out Wiki_Renderer); type List_Style_Array is array (1 .. 32) of Boolean; EMPTY_TAG : aliased constant Wide_Wide_String := ""; type Wiki_Renderer is new Documents.Document_Reader with record Writer : Writers.Writer_Type_Access := null; Syntax : Parsers.Wiki_Syntax_Type := Parsers.SYNTAX_CREOLE; Format : Documents.Format_Map := (others => False); Tags : Wiki_Tag_Array := (others => EMPTY_TAG'Access); Has_Paragraph : Boolean := False; Has_Item : Boolean := False; Need_Paragraph : Boolean := False; Empty_Line : Boolean := True; Keep_Content : Boolean := False; In_List : Boolean := False; Invert_Header_Level : Boolean := False; Allow_Link_Language : Boolean := False; Current_Level : Natural := 0; Quote_Level : Natural := 0; UL_List_Level : Natural := 0; OL_List_Level : Natural := 0; Current_Style : Documents.Format_Map := (others => False); Content : Unbounded_Wide_Wide_String; Link_Href : Unbounded_Wide_Wide_String; Link_Title : Unbounded_Wide_Wide_String; Link_Lang : Unbounded_Wide_Wide_String; end record; end Wiki.Render.Wiki;
Add support for lists
Add support for lists
Ada
apache-2.0
stcarrez/ada-wiki,stcarrez/ada-wiki
0a3cfdb1c9ecb9338845db0a85aa4c7673112eb7
src/xml/util-serialize-io-xml.adb
src/xml/util-serialize-io-xml.adb
----------------------------------------------------------------------- -- util-serialize-io-xml -- XML Serialization Driver -- 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 Unicode; with Unicode.CES.Utf8; with Util.Log.Loggers; package body Util.Serialize.IO.XML is use Util.Log; use Sax.Readers; use Sax.Exceptions; use Sax.Locators; use Sax.Attributes; use Unicode; use Unicode.CES; use Ada.Strings.Unbounded; -- The logger Log : constant Loggers.Logger := Loggers.Create ("Util.Serialize.IO.XML"); -- ------------------------------ -- Warning -- ------------------------------ overriding procedure Warning (Handler : in out Xhtml_Reader; Except : Sax.Exceptions.Sax_Parse_Exception'Class) is pragma Warnings (Off, Handler); begin Log.Warn ("{0}: {1}", To_String (Get_Locator (Except)), Get_Message (Except)); end Warning; -- ------------------------------ -- Error -- ------------------------------ overriding procedure Error (Handler : in out Xhtml_Reader; Except : in Sax.Exceptions.Sax_Parse_Exception'Class) is pragma Warnings (Off, Handler); begin Log.Error ("{0}: {1}", To_String (Get_Locator (Except)), Get_Message (Except)); end Error; -- ------------------------------ -- Fatal_Error -- ------------------------------ overriding procedure Fatal_Error (Handler : in out Xhtml_Reader; Except : in Sax.Exceptions.Sax_Parse_Exception'Class) is pragma Unreferenced (Handler); begin Log.Error ("{0}: {1}", To_String (Get_Locator (Except)), Get_Message (Except)); end Fatal_Error; -- ------------------------------ -- Set_Document_Locator -- ------------------------------ overriding procedure Set_Document_Locator (Handler : in out Xhtml_Reader; Loc : in out Sax.Locators.Locator) is begin Handler.Locator := Loc; end Set_Document_Locator; -- ------------------------------ -- Start_Document -- ------------------------------ overriding procedure Start_Document (Handler : in out Xhtml_Reader) is begin null; end Start_Document; -- ------------------------------ -- End_Document -- ------------------------------ overriding procedure End_Document (Handler : in out Xhtml_Reader) is begin null; end End_Document; -- ------------------------------ -- Start_Prefix_Mapping -- ------------------------------ overriding procedure Start_Prefix_Mapping (Handler : in out Xhtml_Reader; Prefix : in Unicode.CES.Byte_Sequence; URI : in Unicode.CES.Byte_Sequence) is begin null; end Start_Prefix_Mapping; -- ------------------------------ -- End_Prefix_Mapping -- ------------------------------ overriding procedure End_Prefix_Mapping (Handler : in out Xhtml_Reader; Prefix : in Unicode.CES.Byte_Sequence) is begin null; end End_Prefix_Mapping; -- ------------------------------ -- Start_Element -- ------------------------------ 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) is pragma Unreferenced (Namespace_URI, Qname); Attr_Count : Natural; begin -- Handler.Line.Line := Sax.Locators.Get_Line_Number (Handler.Locator); -- Handler.Line.Column := Sax.Locators.Get_Column_Number (Handler.Locator); Log.Debug ("Start object {0}", Local_Name); Handler.Handler.Start_Object (Local_Name); Attr_Count := Get_Length (Atts); for I in 0 .. Attr_Count - 1 loop declare Name : constant String := Get_Qname (Atts, I); Value : constant String := Get_Value (Atts, I); begin Handler.Handler.Set_Member (Name => Name, Value => Util.Beans.Objects.To_Object (Value), Attribute => True); end; end loop; end Start_Element; -- ------------------------------ -- End_Element -- ------------------------------ 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 := "") is pragma Unreferenced (Namespace_URI, Qname); begin Handler.Handler.Finish_Object (Local_Name); if Length (Handler.Text) > 0 then Log.Debug ("Close object {0} -> {1}", Local_Name, To_String (Handler.Text)); Handler.Handler.Set_Member (Local_Name, Util.Beans.Objects.To_Object (Handler.Text)); Set_Unbounded_String (Handler.Text, ""); else Log.Debug ("Close object {0}", Local_Name); end if; end End_Element; procedure Collect_Text (Handler : in out Xhtml_Reader; Content : Unicode.CES.Byte_Sequence) is begin Append (Handler.Text, Content); end Collect_Text; -- ------------------------------ -- Characters -- ------------------------------ overriding procedure Characters (Handler : in out Xhtml_Reader; Ch : in Unicode.CES.Byte_Sequence) is begin Collect_Text (Handler, Ch); end Characters; -- ------------------------------ -- Ignorable_Whitespace -- ------------------------------ overriding procedure Ignorable_Whitespace (Handler : in out Xhtml_Reader; Ch : in Unicode.CES.Byte_Sequence) is begin if not Handler.Ignore_White_Spaces then Collect_Text (Handler, Ch); end if; end Ignorable_Whitespace; -- ------------------------------ -- Processing_Instruction -- ------------------------------ overriding procedure Processing_Instruction (Handler : in out Xhtml_Reader; Target : in Unicode.CES.Byte_Sequence; Data : in Unicode.CES.Byte_Sequence) is pragma Unreferenced (Handler); begin Log.Error ("Processing instruction: {0}: {1}", Target, Data); end Processing_Instruction; -- ------------------------------ -- Skipped_Entity -- ------------------------------ overriding procedure Skipped_Entity (Handler : in out Xhtml_Reader; Name : in Unicode.CES.Byte_Sequence) is pragma Unmodified (Handler); begin null; end Skipped_Entity; -- ------------------------------ -- Start_Cdata -- ------------------------------ overriding procedure Start_Cdata (Handler : in out Xhtml_Reader) is pragma Unmodified (Handler); begin Log.Info ("Start CDATA"); end Start_Cdata; -- ------------------------------ -- End_Cdata -- ------------------------------ overriding procedure End_Cdata (Handler : in out Xhtml_Reader) is pragma Unmodified (Handler); begin Log.Info ("End CDATA"); end End_Cdata; -- ------------------------------ -- Resolve_Entity -- ------------------------------ 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 is pragma Unreferenced (Handler); begin Log.Error ("Cannot resolve entity {0} - {1}", Public_Id, System_Id); return null; end Resolve_Entity; 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 := "") is begin null; end Start_DTD; -- ------------------------------ -- 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) is begin Reader.Ignore_White_Spaces := Value; end Set_Ignore_White_Spaces; -- ------------------------------ -- Set the XHTML reader to ignore empty lines. -- ------------------------------ procedure Set_Ignore_Empty_Lines (Reader : in out Parser; Value : in Boolean) is begin Reader.Ignore_Empty_Lines := Value; end Set_Ignore_Empty_Lines; -- ------------------------------ -- Parse an XML stream, and calls the appropriate SAX callbacks for each -- event. -- This is not re-entrant: you can not call Parse with the same Parser -- argument in one of the SAX callbacks. This has undefined behavior. -- ------------------------------ -- Parse the stream using the JSON parser. procedure Parse (Handler : in out Parser; Stream : in out Util.Streams.Buffered.Buffered_Stream'Class) is type String_Access is access all String (1 .. 32); type Stream_Input is new Input_Sources.Input_Source with record Index : Natural; Last : Natural; Encoding : Unicode.CES.Encoding_Scheme; Buffer : String_Access; end record; -- Return the next character in the string. procedure Next_Char (From : in out Stream_Input; C : out Unicode.Unicode_Char); -- True if From is past the last character in the string. function Eof (From : in Stream_Input) return Boolean; procedure Fill (From : in out Stream_Input'Class); procedure Fill (From : in out Stream_Input'Class) is begin -- Move to the buffer start if From.Last > From.Index and From.Index > From.Buffer'First then From.Buffer (From.Buffer'First .. From.Last - 1 - From.Index + From.Buffer'First) := From.Buffer (From.Index .. From.Last - 1); From.Last := From.Last - From.Index + From.Buffer'First; From.Index := From.Buffer'First; end if; if From.Index > From.Last then From.Index := From.Buffer'First; end if; begin loop Stream.Read (From.Buffer (From.Last)); From.Last := From.Last + 1; exit when From.Last > From.Buffer'Last; end loop; exception when others => null; end; end Fill; -- Return the next character in the string. procedure Next_Char (From : in out Stream_Input; C : out Unicode.Unicode_Char) is begin if From.Index + 6 >= From.Last then Fill (From); end if; From.Encoding.Read (From.Buffer.all, From.Index, C); end Next_Char; -- True if From is past the last character in the string. function Eof (From : in Stream_Input) return Boolean is begin if From.Index < From.Last then return False; end if; return Stream.Is_Eof; end Eof; Input : Stream_Input; Xml_Parser : Xhtml_Reader; Buf : aliased String (1 .. 32); begin Input.Buffer := Buf'Access; Input.Index := 2; Input.Last := 1; Input.Set_Encoding (Unicode.CES.Utf8.Utf8_Encoding); Input.Encoding := Unicode.CES.Utf8.Utf8_Encoding; Xml_Parser.Handler := Handler'Unchecked_Access; Xml_Parser.Ignore_White_Spaces := Handler.Ignore_White_Spaces; Xml_Parser.Ignore_Empty_Lines := Handler.Ignore_Empty_Lines; Sax.Readers.Reader (Xml_Parser).Parse (Input); end Parse; -- Close the current XML entity if an entity was started procedure Close_Current (Stream : in out Output_Stream'Class); -- ------------------------------ -- Close the current XML entity if an entity was started -- ------------------------------ procedure Close_Current (Stream : in out Output_Stream'Class) is begin if Stream.Close_Start then Stream.Write ('>'); Stream.Close_Start := False; end if; end Close_Current; -- ------------------------------ -- 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) is begin Close_Current (Stream); Stream.Write (Value); end Write_String; -- ------------------------------ -- Start a new XML object. -- ------------------------------ procedure Start_Entity (Stream : in out Output_Stream; Name : in String) is begin Close_Current (Stream); Stream.Close_Start := True; Stream.Write ('<'); Stream.Write (Name); end Start_Entity; -- ------------------------------ -- Terminates the current XML object. -- ------------------------------ procedure End_Entity (Stream : in out Output_Stream; Name : in String) is begin Close_Current (Stream); Stream.Write ("</"); Stream.Write (Name); Stream.Write ('>'); end End_Entity; -- ------------------------------ -- Write a XML name/value attribute. -- ------------------------------ procedure Write_Attribute (Stream : in out Output_Stream; Name : in String; Value : in Util.Beans.Objects.Object) is use Util.Beans.Objects; begin Stream.Write (' '); Stream.Write (Name); Stream.Write ("="""); case Util.Beans.Objects.Get_Type (Value) is when TYPE_NULL => null; when TYPE_BOOLEAN => if Util.Beans.Objects.To_Boolean (Value) then Stream.Write ("true"); else Stream.Write ("false"); end if; when TYPE_INTEGER => Stream.Write (Util.Beans.Objects.To_Long_Long_Integer (Value)); when others => Stream.Write_String (Util.Beans.Objects.To_String (Value)); end case; Stream.Write ('"'); end Write_Attribute; -- ------------------------------ -- 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) is use Util.Beans.Objects; begin Close_Current (Stream); Stream.Write ('<'); Stream.Write (Name); Stream.Write ('>'); case Util.Beans.Objects.Get_Type (Value) is when TYPE_NULL => null; when TYPE_BOOLEAN => if Util.Beans.Objects.To_Boolean (Value) then Stream.Write ("true"); else Stream.Write ("false"); end if; when TYPE_INTEGER => Stream.Write (Util.Beans.Objects.To_Long_Long_Integer (Value)); when others => Stream.Write_String (Util.Beans.Objects.To_String (Value)); end case; Stream.Write ("</"); Stream.Write (Name); Stream.Write ('>'); end Write_Entity; -- ------------------------------ -- Starts a XML array. -- ------------------------------ procedure Start_Array (Stream : in out Output_Stream; Length : in Ada.Containers.Count_Type) is begin null; end Start_Array; -- ------------------------------ -- Terminates a XML array. -- ------------------------------ procedure End_Array (Stream : in out Output_Stream) is begin null; end End_Array; end Util.Serialize.IO.XML;
----------------------------------------------------------------------- -- util-serialize-io-xml -- XML Serialization Driver -- 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 Unicode; with Unicode.CES.Utf8; with Util.Log.Loggers; package body Util.Serialize.IO.XML is use Util.Log; use Sax.Readers; use Sax.Exceptions; use Sax.Locators; use Sax.Attributes; use Unicode; use Unicode.CES; use Ada.Strings.Unbounded; -- The logger Log : constant Loggers.Logger := Loggers.Create ("Util.Serialize.IO.XML"); -- ------------------------------ -- Warning -- ------------------------------ overriding procedure Warning (Handler : in out Xhtml_Reader; Except : Sax.Exceptions.Sax_Parse_Exception'Class) is pragma Warnings (Off, Handler); begin Log.Warn ("{0}: {1}", To_String (Get_Locator (Except)), Get_Message (Except)); end Warning; -- ------------------------------ -- Error -- ------------------------------ overriding procedure Error (Handler : in out Xhtml_Reader; Except : in Sax.Exceptions.Sax_Parse_Exception'Class) is pragma Warnings (Off, Handler); begin Log.Error ("{0}: {1}", To_String (Get_Locator (Except)), Get_Message (Except)); end Error; -- ------------------------------ -- Fatal_Error -- ------------------------------ overriding procedure Fatal_Error (Handler : in out Xhtml_Reader; Except : in Sax.Exceptions.Sax_Parse_Exception'Class) is pragma Unreferenced (Handler); begin Log.Error ("{0}: {1}", To_String (Get_Locator (Except)), Get_Message (Except)); end Fatal_Error; -- ------------------------------ -- Set_Document_Locator -- ------------------------------ overriding procedure Set_Document_Locator (Handler : in out Xhtml_Reader; Loc : in out Sax.Locators.Locator) is begin Handler.Locator := Loc; end Set_Document_Locator; -- ------------------------------ -- Start_Document -- ------------------------------ overriding procedure Start_Document (Handler : in out Xhtml_Reader) is begin null; end Start_Document; -- ------------------------------ -- End_Document -- ------------------------------ overriding procedure End_Document (Handler : in out Xhtml_Reader) is begin null; end End_Document; -- ------------------------------ -- Start_Prefix_Mapping -- ------------------------------ overriding procedure Start_Prefix_Mapping (Handler : in out Xhtml_Reader; Prefix : in Unicode.CES.Byte_Sequence; URI : in Unicode.CES.Byte_Sequence) is begin null; end Start_Prefix_Mapping; -- ------------------------------ -- End_Prefix_Mapping -- ------------------------------ overriding procedure End_Prefix_Mapping (Handler : in out Xhtml_Reader; Prefix : in Unicode.CES.Byte_Sequence) is begin null; end End_Prefix_Mapping; -- ------------------------------ -- Start_Element -- ------------------------------ 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) is pragma Unreferenced (Namespace_URI, Qname); Attr_Count : Natural; begin -- Handler.Line.Line := Sax.Locators.Get_Line_Number (Handler.Locator); -- Handler.Line.Column := Sax.Locators.Get_Column_Number (Handler.Locator); Log.Debug ("Start object {0}", Local_Name); Handler.Handler.Start_Object (Local_Name); Attr_Count := Get_Length (Atts); for I in 0 .. Attr_Count - 1 loop declare Name : constant String := Get_Qname (Atts, I); Value : constant String := Get_Value (Atts, I); begin Handler.Handler.Set_Member (Name => Name, Value => Util.Beans.Objects.To_Object (Value), Attribute => True); end; end loop; end Start_Element; -- ------------------------------ -- End_Element -- ------------------------------ 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 := "") is pragma Unreferenced (Namespace_URI, Qname); begin Handler.Handler.Finish_Object (Local_Name); if Length (Handler.Text) > 0 then Log.Debug ("Close object {0} -> {1}", Local_Name, To_String (Handler.Text)); Handler.Handler.Set_Member (Local_Name, Util.Beans.Objects.To_Object (Handler.Text)); Set_Unbounded_String (Handler.Text, ""); else Log.Debug ("Close object {0}", Local_Name); end if; end End_Element; procedure Collect_Text (Handler : in out Xhtml_Reader; Content : Unicode.CES.Byte_Sequence) is begin Append (Handler.Text, Content); end Collect_Text; -- ------------------------------ -- Characters -- ------------------------------ overriding procedure Characters (Handler : in out Xhtml_Reader; Ch : in Unicode.CES.Byte_Sequence) is begin Collect_Text (Handler, Ch); end Characters; -- ------------------------------ -- Ignorable_Whitespace -- ------------------------------ overriding procedure Ignorable_Whitespace (Handler : in out Xhtml_Reader; Ch : in Unicode.CES.Byte_Sequence) is begin if not Handler.Ignore_White_Spaces then Collect_Text (Handler, Ch); end if; end Ignorable_Whitespace; -- ------------------------------ -- Processing_Instruction -- ------------------------------ overriding procedure Processing_Instruction (Handler : in out Xhtml_Reader; Target : in Unicode.CES.Byte_Sequence; Data : in Unicode.CES.Byte_Sequence) is pragma Unreferenced (Handler); begin Log.Error ("Processing instruction: {0}: {1}", Target, Data); end Processing_Instruction; -- ------------------------------ -- Skipped_Entity -- ------------------------------ overriding procedure Skipped_Entity (Handler : in out Xhtml_Reader; Name : in Unicode.CES.Byte_Sequence) is pragma Unmodified (Handler); begin null; end Skipped_Entity; -- ------------------------------ -- Start_Cdata -- ------------------------------ overriding procedure Start_Cdata (Handler : in out Xhtml_Reader) is pragma Unmodified (Handler); begin Log.Info ("Start CDATA"); end Start_Cdata; -- ------------------------------ -- End_Cdata -- ------------------------------ overriding procedure End_Cdata (Handler : in out Xhtml_Reader) is pragma Unmodified (Handler); begin Log.Info ("End CDATA"); end End_Cdata; -- ------------------------------ -- Resolve_Entity -- ------------------------------ 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 is pragma Unreferenced (Handler); begin Log.Error ("Cannot resolve entity {0} - {1}", Public_Id, System_Id); return null; end Resolve_Entity; 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 := "") is begin null; end Start_DTD; -- ------------------------------ -- 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) is begin Reader.Ignore_White_Spaces := Value; end Set_Ignore_White_Spaces; -- ------------------------------ -- Set the XHTML reader to ignore empty lines. -- ------------------------------ procedure Set_Ignore_Empty_Lines (Reader : in out Parser; Value : in Boolean) is begin Reader.Ignore_Empty_Lines := Value; end Set_Ignore_Empty_Lines; -- ------------------------------ -- Parse an XML stream, and calls the appropriate SAX callbacks for each -- event. -- This is not re-entrant: you can not call Parse with the same Parser -- argument in one of the SAX callbacks. This has undefined behavior. -- ------------------------------ -- Parse the stream using the JSON parser. procedure Parse (Handler : in out Parser; Stream : in out Util.Streams.Buffered.Buffered_Stream'Class) is type String_Access is access all String (1 .. 32); type Stream_Input is new Input_Sources.Input_Source with record Index : Natural; Last : Natural; Encoding : Unicode.CES.Encoding_Scheme; Buffer : String_Access; end record; -- Return the next character in the string. procedure Next_Char (From : in out Stream_Input; C : out Unicode.Unicode_Char); -- True if From is past the last character in the string. function Eof (From : in Stream_Input) return Boolean; procedure Fill (From : in out Stream_Input'Class); procedure Fill (From : in out Stream_Input'Class) is begin -- Move to the buffer start if From.Last > From.Index and From.Index > From.Buffer'First then From.Buffer (From.Buffer'First .. From.Last - 1 - From.Index + From.Buffer'First) := From.Buffer (From.Index .. From.Last - 1); From.Last := From.Last - From.Index + From.Buffer'First; From.Index := From.Buffer'First; end if; if From.Index > From.Last then From.Index := From.Buffer'First; end if; begin loop Stream.Read (From.Buffer (From.Last)); From.Last := From.Last + 1; exit when From.Last > From.Buffer'Last; end loop; exception when others => null; end; end Fill; -- Return the next character in the string. procedure Next_Char (From : in out Stream_Input; C : out Unicode.Unicode_Char) is begin if From.Index + 6 >= From.Last then Fill (From); end if; From.Encoding.Read (From.Buffer.all, From.Index, C); end Next_Char; -- True if From is past the last character in the string. function Eof (From : in Stream_Input) return Boolean is begin if From.Index < From.Last then return False; end if; return Stream.Is_Eof; end Eof; Input : Stream_Input; Xml_Parser : Xhtml_Reader; Buf : aliased String (1 .. 32); begin Input.Buffer := Buf'Access; Input.Index := 2; Input.Last := 1; Input.Set_Encoding (Unicode.CES.Utf8.Utf8_Encoding); Input.Encoding := Unicode.CES.Utf8.Utf8_Encoding; Xml_Parser.Handler := Handler'Unchecked_Access; Xml_Parser.Ignore_White_Spaces := Handler.Ignore_White_Spaces; Xml_Parser.Ignore_Empty_Lines := Handler.Ignore_Empty_Lines; Sax.Readers.Reader (Xml_Parser).Parse (Input); end Parse; -- Close the current XML entity if an entity was started procedure Close_Current (Stream : in out Output_Stream'Class); -- ------------------------------ -- Close the current XML entity if an entity was started -- ------------------------------ procedure Close_Current (Stream : in out Output_Stream'Class) is begin if Stream.Close_Start then Stream.Write ('>'); Stream.Close_Start := False; end if; end Close_Current; -- ------------------------------ -- 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) is begin Close_Current (Stream); Stream.Write (Value); end Write_String; -- ------------------------------ -- Start a new XML object. -- ------------------------------ procedure Start_Entity (Stream : in out Output_Stream; Name : in String) is begin Close_Current (Stream); Stream.Close_Start := True; Stream.Write ('<'); Stream.Write (Name); end Start_Entity; -- ------------------------------ -- Terminates the current XML object. -- ------------------------------ procedure End_Entity (Stream : in out Output_Stream; Name : in String) is begin Close_Current (Stream); Stream.Write ("</"); Stream.Write (Name); Stream.Write ('>'); end End_Entity; -- ------------------------------ -- Write a XML name/value attribute. -- ------------------------------ procedure Write_Attribute (Stream : in out Output_Stream; Name : in String; Value : in Util.Beans.Objects.Object) is use Util.Beans.Objects; begin Stream.Write (' '); Stream.Write (Name); Stream.Write ("="""); case Util.Beans.Objects.Get_Type (Value) is when TYPE_NULL => null; when TYPE_BOOLEAN => if Util.Beans.Objects.To_Boolean (Value) then Stream.Write ("true"); else Stream.Write ("false"); end if; when TYPE_INTEGER => Stream.Write (Util.Beans.Objects.To_Long_Long_Integer (Value)); when others => Stream.Write (Util.Beans.Objects.To_String (Value)); end case; Stream.Write ('"'); end Write_Attribute; -- ------------------------------ -- 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) is use Util.Beans.Objects; begin Close_Current (Stream); Stream.Write ('<'); Stream.Write (Name); Stream.Write ('>'); case Util.Beans.Objects.Get_Type (Value) is when TYPE_NULL => null; when TYPE_BOOLEAN => if Util.Beans.Objects.To_Boolean (Value) then Stream.Write ("true"); else Stream.Write ("false"); end if; when TYPE_INTEGER => Stream.Write (Util.Beans.Objects.To_Long_Long_Integer (Value)); when others => Stream.Write_String (Util.Beans.Objects.To_String (Value)); end case; Stream.Write ("</"); Stream.Write (Name); Stream.Write ('>'); end Write_Entity; -- ------------------------------ -- Starts a XML array. -- ------------------------------ procedure Start_Array (Stream : in out Output_Stream; Length : in Ada.Containers.Count_Type) is begin null; end Start_Array; -- ------------------------------ -- Terminates a XML array. -- ------------------------------ procedure End_Array (Stream : in out Output_Stream) is begin null; end End_Array; end Util.Serialize.IO.XML;
Use Stream.Write instead of Stream.Write_String to write the attribute value (otherwise we can close the current entity by writing the '>')
Use Stream.Write instead of Stream.Write_String to write the attribute value (otherwise we can close the current entity by writing the '>')
Ada
apache-2.0
stcarrez/ada-util,stcarrez/ada-util
a091904fff593b5fe25c8db2ecf7a177d99d7f99
regtests/security-policies-tests.adb
regtests/security-policies-tests.adb
----------------------------------------------------------------------- -- Security-policies-tests - Unit tests for Security.Permissions -- Copyright (C) 2011, 2012 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Tests; with Util.Files; with Util.Test_Caller; with Util.Measures; with Security.Contexts; with Security.Policies.Roles; package body Security.Policies.Tests is use Util.Tests; package Caller is new Util.Test_Caller (Test, "Security.Policies"); procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is begin Caller.Add_Test (Suite, "Test Security.Permissions.Create_Role", Test_Create_Role'Access); Caller.Add_Test (Suite, "Test Security.Permissions.Has_Permission", Test_Has_Permission'Access); Caller.Add_Test (Suite, "Test Security.Permissions.Read_Policy", Test_Read_Policy'Access); Caller.Add_Test (Suite, "Test Security.Policies.Roles.Set_Roles", Test_Set_Roles'Access); -- These tests are identical but registered under different names -- for the test documentation. Caller.Add_Test (Suite, "Test Security.Contexts.Has_Permission", Test_Role_Policy'Access); Caller.Add_Test (Suite, "Test Security.Controllers.Roles.Has_Permission", Test_Role_Policy'Access); Caller.Add_Test (Suite, "Test Security.Permissions.Role_Policy", Test_Role_Policy'Access); end Add_Tests; -- ------------------------------ -- Returns true if the given permission is stored in the user principal. -- ------------------------------ function Has_Role (User : in Test_Principal; Role : in Security.Policies.Roles.Role_Type) return Boolean is begin return User.Roles (Role); end Has_Role; -- ------------------------------ -- Get the principal name. -- ------------------------------ function Get_Name (From : in Test_Principal) return String is begin return Util.Strings.To_String (From.Name); end Get_Name; -- ------------------------------ -- Test Create_Role and Get_Role_Name -- ------------------------------ procedure Test_Create_Role (T : in out Test) is use Security.Policies.Roles; M : Security.Policies.Roles.Role_Policy; Role : Role_Type; begin M.Create_Role (Name => "admin", Role => Role); Assert_Equals (T, "admin", M.Get_Role_Name (Role), "Invalid name"); for I in Role + 1 .. Role_Type'Last loop declare Name : constant String := "admin-" & Role_Type'Image (I); Role2 : Role_Type; begin Role2 := M.Find_Role ("admin"); T.Assert (Role2 = Role, "Find_Role returned an invalid role"); M.Create_Role (Name => Name, Role => Role2); Assert_Equals (T, Name, M.Get_Role_Name (Role2), "Invalid name"); end; end loop; end Test_Create_Role; -- ------------------------------ -- Test Set_Roles -- ------------------------------ procedure Test_Set_Roles (T : in out Test) is use Security.Policies.Roles; M : Security.Policies.Roles.Role_Policy; Role : Role_Type; Map : Role_Map := (others => False); begin M.Create_Role (Name => "manager", Role => Role); M.Create_Role (Name => "admin", Role => Role); Assert_Equals (T, "admin", M.Get_Role_Name (Role), "Invalid name"); T.Assert (not Map (Role), "The admin role must not set in the map"); M.Set_Roles ("admin", Map); T.Assert (Map (Role), "The admin role is not set in the map"); end Test_Set_Roles; -- ------------------------------ -- Test Has_Permission -- ------------------------------ procedure Test_Has_Permission (T : in out Test) is M : Security.Policies.Policy_Manager (1); Perm : Permissions.Permission_Type; User : Test_Principal; begin -- T.Assert (not M.Has_Permission (User, 1), "User has a non-existing permission"); null; end Test_Has_Permission; -- ------------------------------ -- Test reading policy files -- ------------------------------ procedure Test_Read_Policy (T : in out Test) is M : aliased Security.Policies.Policy_Manager (Max_Policies => 2); Dir : constant String := "regtests/files/permissions/"; Path : constant String := Util.Tests.Get_Path (Dir); User : aliased Test_Principal; Admin_Perm : Policies.Roles.Role_Type; Manager_Perm : Policies.Roles.Role_Type; Context : aliased Security.Contexts.Security_Context; R : Security.Policies.Roles.Role_Policy_Access := new Roles.Role_Policy; begin M.Add_Policy (R.all'Access); M.Read_Policy (Util.Files.Compose (Path, "empty.xml")); R.Add_Role_Type (Name => "admin", Result => Admin_Perm); R.Add_Role_Type (Name => "manager", Result => Manager_Perm); M.Read_Policy (Util.Files.Compose (Path, "simple-policy.xml")); User.Roles (Admin_Perm) := True; Context.Set_Context (Manager => M'Unchecked_Access, Principal => User'Unchecked_Access); -- declare -- S : Util.Measures.Stamp; -- begin -- for I in 1 .. 1_000 loop -- declare -- URI : constant String := "/admin/home/" & Util.Strings.Image (I) & "/l.html"; -- P : constant URI_Permission (URI'Length) -- := URI_Permission '(Len => URI'Length, URI => URI); -- begin -- T.Assert (M.Has_Permission (Context => Context'Unchecked_Access, -- Permission => P), "Permission not granted"); -- end; -- end loop; -- Util.Measures.Report (S, "Has_Permission (1000 calls, cache miss)"); -- end; -- -- declare -- S : Util.Measures.Stamp; -- begin -- for I in 1 .. 1_000 loop -- declare -- URI : constant String := "/admin/home/list.html"; -- P : constant URI_Permission (URI'Length) -- := URI_Permission '(Len => URI'Length, URI => URI); -- begin -- T.Assert (M.Has_Permission (Context => Context'Unchecked_Access, -- Permission => P), "Permission not granted"); -- end; -- end loop; -- Util.Measures.Report (S, "Has_Permission (1000 calls, cache hit)"); -- end; end Test_Read_Policy; -- ------------------------------ -- Read the policy file <b>File</b> and perform a test on the given URI -- with a user having the given role. -- ------------------------------ procedure Check_Policy (T : in out Test; File : in String; Role : in String; URI : in String) is M : aliased Security.Policies.Policy_Manager (1); Dir : constant String := "regtests/files/permissions/"; Path : constant String := Util.Tests.Get_Path (Dir); User : aliased Test_Principal; Admin_Perm : Roles.Role_Type; Context : aliased Security.Contexts.Security_Context; begin M.Read_Policy (Util.Files.Compose (Path, File)); -- -- Admin_Perm := M.Find_Role (Role); -- -- Context.Set_Context (Manager => M'Unchecked_Access, -- Principal => User'Unchecked_Access); -- -- declare -- P : constant URI_Permission (URI'Length) -- := URI_Permission '(Len => URI'Length, URI => URI); -- begin -- -- A user without the role should not have the permission. -- T.Assert (not M.Has_Permission (Context => Context'Unchecked_Access, -- Permission => P), -- "Permission was granted for user without role. URI=" & URI); -- -- -- Set the role. -- User.Roles (Admin_Perm) := True; -- T.Assert (M.Has_Permission (Context => Context'Unchecked_Access, -- Permission => P), -- "Permission was not granted for user with role. URI=" & URI); -- end; end Check_Policy; -- ------------------------------ -- Test reading policy files and using the <role-permission> controller -- ------------------------------ procedure Test_Role_Policy (T : in out Test) is begin T.Check_Policy (File => "policy-with-role.xml", Role => "developer", URI => "/developer/user-should-have-developer-role"); T.Check_Policy (File => "policy-with-role.xml", Role => "manager", URI => "/developer/user-should-have-manager-role"); T.Check_Policy (File => "policy-with-role.xml", Role => "manager", URI => "/manager/user-should-have-manager-role"); T.Check_Policy (File => "policy-with-role.xml", Role => "admin", URI => "/manager/user-should-have-admin-role"); T.Check_Policy (File => "policy-with-role.xml", Role => "admin", URI => "/admin/user-should-have-admin-role"); end Test_Role_Policy; end Security.Policies.Tests;
----------------------------------------------------------------------- -- Security-policies-tests - Unit tests for Security.Permissions -- Copyright (C) 2011, 2012 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Tests; with Util.Files; with Util.Test_Caller; with Util.Measures; with Security.Contexts; with Security.Policies.Roles; package body Security.Policies.Tests is use Util.Tests; package Caller is new Util.Test_Caller (Test, "Security.Policies"); procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is begin Caller.Add_Test (Suite, "Test Security.Permissions.Create_Role", Test_Create_Role'Access); Caller.Add_Test (Suite, "Test Security.Permissions.Has_Permission", Test_Has_Permission'Access); Caller.Add_Test (Suite, "Test Security.Permissions.Read_Policy", Test_Read_Policy'Access); Caller.Add_Test (Suite, "Test Security.Policies.Roles.Set_Roles", Test_Set_Roles'Access); -- These tests are identical but registered under different names -- for the test documentation. Caller.Add_Test (Suite, "Test Security.Contexts.Has_Permission", Test_Role_Policy'Access); Caller.Add_Test (Suite, "Test Security.Controllers.Roles.Has_Permission", Test_Role_Policy'Access); Caller.Add_Test (Suite, "Test Security.Permissions.Role_Policy", Test_Role_Policy'Access); end Add_Tests; -- ------------------------------ -- Returns true if the given permission is stored in the user principal. -- ------------------------------ function Has_Role (User : in Test_Principal; Role : in Security.Policies.Roles.Role_Type) return Boolean is begin return User.Roles (Role); end Has_Role; -- ------------------------------ -- Get the principal name. -- ------------------------------ function Get_Name (From : in Test_Principal) return String is begin return Util.Strings.To_String (From.Name); end Get_Name; -- ------------------------------ -- Test Create_Role and Get_Role_Name -- ------------------------------ procedure Test_Create_Role (T : in out Test) is use Security.Policies.Roles; M : Security.Policies.Roles.Role_Policy; Role : Role_Type; begin M.Create_Role (Name => "admin", Role => Role); Assert_Equals (T, "admin", M.Get_Role_Name (Role), "Invalid name"); for I in Role + 1 .. Role_Type'Last loop declare Name : constant String := "admin-" & Role_Type'Image (I); Role2 : Role_Type; begin Role2 := M.Find_Role ("admin"); T.Assert (Role2 = Role, "Find_Role returned an invalid role"); M.Create_Role (Name => Name, Role => Role2); Assert_Equals (T, Name, M.Get_Role_Name (Role2), "Invalid name"); end; end loop; end Test_Create_Role; -- ------------------------------ -- Test Set_Roles -- ------------------------------ procedure Test_Set_Roles (T : in out Test) is use Security.Policies.Roles; M : Security.Policies.Roles.Role_Policy; Admin : Role_Type; Manager : Role_Type; Map : Role_Map := (others => False); begin M.Create_Role (Name => "manager", Role => Manager); M.Create_Role (Name => "admin", Role => Admin); Assert_Equals (T, "admin", M.Get_Role_Name (Admin), "Invalid name"); T.Assert (not Map (Admin), "The admin role must not set in the map"); M.Set_Roles ("admin", Map); T.Assert (Map (Admin), "The admin role is not set in the map"); T.Assert (not Map (Manager), "The manager role must not be set in the map"); Map := (others => False); M.Set_Roles ("manager,admin", Map); T.Assert (Map (Admin), "The admin role is not set in the map"); T.Assert (Map (Manager), "The manager role is not set in the map"); end Test_Set_Roles; -- ------------------------------ -- Test Has_Permission -- ------------------------------ procedure Test_Has_Permission (T : in out Test) is M : Security.Policies.Policy_Manager (1); Perm : Permissions.Permission_Type; User : Test_Principal; begin -- T.Assert (not M.Has_Permission (User, 1), "User has a non-existing permission"); null; end Test_Has_Permission; -- ------------------------------ -- Test reading policy files -- ------------------------------ procedure Test_Read_Policy (T : in out Test) is M : aliased Security.Policies.Policy_Manager (Max_Policies => 2); Dir : constant String := "regtests/files/permissions/"; Path : constant String := Util.Tests.Get_Path (Dir); User : aliased Test_Principal; Admin_Perm : Policies.Roles.Role_Type; Manager_Perm : Policies.Roles.Role_Type; Context : aliased Security.Contexts.Security_Context; R : Security.Policies.Roles.Role_Policy_Access := new Roles.Role_Policy; begin M.Add_Policy (R.all'Access); M.Read_Policy (Util.Files.Compose (Path, "empty.xml")); R.Add_Role_Type (Name => "admin", Result => Admin_Perm); R.Add_Role_Type (Name => "manager", Result => Manager_Perm); M.Read_Policy (Util.Files.Compose (Path, "simple-policy.xml")); User.Roles (Admin_Perm) := True; Context.Set_Context (Manager => M'Unchecked_Access, Principal => User'Unchecked_Access); -- declare -- S : Util.Measures.Stamp; -- begin -- for I in 1 .. 1_000 loop -- declare -- URI : constant String := "/admin/home/" & Util.Strings.Image (I) & "/l.html"; -- P : constant URI_Permission (URI'Length) -- := URI_Permission '(Len => URI'Length, URI => URI); -- begin -- T.Assert (M.Has_Permission (Context => Context'Unchecked_Access, -- Permission => P), "Permission not granted"); -- end; -- end loop; -- Util.Measures.Report (S, "Has_Permission (1000 calls, cache miss)"); -- end; -- -- declare -- S : Util.Measures.Stamp; -- begin -- for I in 1 .. 1_000 loop -- declare -- URI : constant String := "/admin/home/list.html"; -- P : constant URI_Permission (URI'Length) -- := URI_Permission '(Len => URI'Length, URI => URI); -- begin -- T.Assert (M.Has_Permission (Context => Context'Unchecked_Access, -- Permission => P), "Permission not granted"); -- end; -- end loop; -- Util.Measures.Report (S, "Has_Permission (1000 calls, cache hit)"); -- end; end Test_Read_Policy; -- ------------------------------ -- Read the policy file <b>File</b> and perform a test on the given URI -- with a user having the given role. -- ------------------------------ procedure Check_Policy (T : in out Test; File : in String; Role : in String; URI : in String) is M : aliased Security.Policies.Policy_Manager (1); Dir : constant String := "regtests/files/permissions/"; Path : constant String := Util.Tests.Get_Path (Dir); User : aliased Test_Principal; Admin_Perm : Roles.Role_Type; Context : aliased Security.Contexts.Security_Context; begin M.Read_Policy (Util.Files.Compose (Path, File)); -- -- Admin_Perm := M.Find_Role (Role); -- -- Context.Set_Context (Manager => M'Unchecked_Access, -- Principal => User'Unchecked_Access); -- -- declare -- P : constant URI_Permission (URI'Length) -- := URI_Permission '(Len => URI'Length, URI => URI); -- begin -- -- A user without the role should not have the permission. -- T.Assert (not M.Has_Permission (Context => Context'Unchecked_Access, -- Permission => P), -- "Permission was granted for user without role. URI=" & URI); -- -- -- Set the role. -- User.Roles (Admin_Perm) := True; -- T.Assert (M.Has_Permission (Context => Context'Unchecked_Access, -- Permission => P), -- "Permission was not granted for user with role. URI=" & URI); -- end; end Check_Policy; -- ------------------------------ -- Test reading policy files and using the <role-permission> controller -- ------------------------------ procedure Test_Role_Policy (T : in out Test) is begin T.Check_Policy (File => "policy-with-role.xml", Role => "developer", URI => "/developer/user-should-have-developer-role"); T.Check_Policy (File => "policy-with-role.xml", Role => "manager", URI => "/developer/user-should-have-manager-role"); T.Check_Policy (File => "policy-with-role.xml", Role => "manager", URI => "/manager/user-should-have-manager-role"); T.Check_Policy (File => "policy-with-role.xml", Role => "admin", URI => "/manager/user-should-have-admin-role"); T.Check_Policy (File => "policy-with-role.xml", Role => "admin", URI => "/admin/user-should-have-admin-role"); end Test_Role_Policy; end Security.Policies.Tests;
Check several roles in Set_Roles
Check several roles in Set_Roles
Ada
apache-2.0
stcarrez/ada-security
18f1f0a1756c5f43d97f2f11c0033b80dbc27fdd
awa/plugins/awa-wikis/src/awa-wikis-modules.ads
awa/plugins/awa-wikis/src/awa-wikis-modules.ads
----------------------------------------------------------------------- -- awa-wikis-modules -- Module wikis -- 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 ASF.Applications; with ADO; with AWA.Modules; with AWA.Wikis.Models; with Security.Permissions; with Awa.Wikis.Models; package AWA.Wikis.Modules is -- The name under which the module is registered. NAME : constant String := "wikis"; package ACL_Create_Wiki_Pages is new Security.Permissions.Definition ("wiki-page-create"); package ACL_Delete_Wiki_Pages is new Security.Permissions.Definition ("wiki-page-delete"); package ACL_Update_Wiki_Pages is new Security.Permissions.Definition ("wiki-page-update"); -- Define the permissions. package ACL_Create_Wiki_Space is new Security.Permissions.Definition ("wiki-space-create"); package ACL_Delete_Wiki_Space is new Security.Permissions.Definition ("wiki-space-delete"); package ACL_Update_Wiki_Space is new Security.Permissions.Definition ("wiki-space-update"); -- ------------------------------ -- Module wikis -- ------------------------------ type Wiki_Module is new AWA.Modules.Module with private; type Wiki_Module_Access is access all Wiki_Module'Class; -- Initialize the wikis module. overriding procedure Initialize (Plugin : in out Wiki_Module; App : in AWA.Modules.Application_Access; Props : in ASF.Applications.Config); -- Get the wikis module. function Get_Wiki_Module return Wiki_Module_Access; -- Create the wiki space. procedure Create_Wiki_Space (Module : in Wiki_Module; Wiki : in out AWA.Wikis.Models.Wiki_Space_Ref'Class); -- Save the wiki space. procedure Save_Wiki_Space (Module : in Wiki_Module; Wiki : in out AWA.Wikis.Models.Wiki_Space_Ref'Class); -- Load the wiki space. procedure Load_Wiki_Space (Module : in Wiki_Module; Wiki : in out AWA.Wikis.Models.Wiki_Space_Ref'Class; Id : in ADO.Identifier); -- Create the wiki page into the wiki space. procedure Create_Wiki_Page (Model : in Wiki_Module; Into : in AWA.Wikis.Models.Wiki_Space_Ref'Class; Page : in out Awa.Wikis.Models.Wiki_Page_Ref'Class); -- Save the wiki page. procedure Save (Model : in Wiki_Module; Page : in out Awa.Wikis.Models.Wiki_Page_Ref'Class); -- Create a new wiki content for the wiki page. procedure Create_Wiki_Content (Model : in Wiki_Module; Page : in out Awa.Wikis.Models.Wiki_Page_Ref'Class; Content : in out AWA.Wikis.Models.Wiki_Content_Ref'Class); private type Wiki_Module is new AWA.Modules.Module with null record; end AWA.Wikis.Modules;
----------------------------------------------------------------------- -- awa-wikis-modules -- Module wikis -- 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 ASF.Applications; with ADO; with AWA.Modules; with AWA.Wikis.Models; with Security.Permissions; with AWA.Wikis.Models; package AWA.Wikis.Modules is -- The name under which the module is registered. NAME : constant String := "wikis"; package ACL_Create_Wiki_Pages is new Security.Permissions.Definition ("wiki-page-create"); package ACL_Delete_Wiki_Pages is new Security.Permissions.Definition ("wiki-page-delete"); package ACL_Update_Wiki_Pages is new Security.Permissions.Definition ("wiki-page-update"); -- Define the permissions. package ACL_Create_Wiki_Space is new Security.Permissions.Definition ("wiki-space-create"); package ACL_Delete_Wiki_Space is new Security.Permissions.Definition ("wiki-space-delete"); package ACL_Update_Wiki_Space is new Security.Permissions.Definition ("wiki-space-update"); -- ------------------------------ -- Module wikis -- ------------------------------ type Wiki_Module is new AWA.Modules.Module with private; type Wiki_Module_Access is access all Wiki_Module'Class; -- Initialize the wikis module. overriding procedure Initialize (Plugin : in out Wiki_Module; App : in AWA.Modules.Application_Access; Props : in ASF.Applications.Config); -- Get the wikis module. function Get_Wiki_Module return Wiki_Module_Access; -- Create the wiki space. procedure Create_Wiki_Space (Module : in Wiki_Module; Wiki : in out AWA.Wikis.Models.Wiki_Space_Ref'Class); -- Save the wiki space. procedure Save_Wiki_Space (Module : in Wiki_Module; Wiki : in out AWA.Wikis.Models.Wiki_Space_Ref'Class); -- Load the wiki space. procedure Load_Wiki_Space (Module : in Wiki_Module; Wiki : in out AWA.Wikis.Models.Wiki_Space_Ref'Class; Id : in ADO.Identifier); -- Create the wiki page into the wiki space. procedure Create_Wiki_Page (Model : in Wiki_Module; Into : in AWA.Wikis.Models.Wiki_Space_Ref'Class; Page : in out AWA.Wikis.Models.Wiki_Page_Ref'Class); -- Save the wiki page. procedure Save (Model : in Wiki_Module; Page : in out Awa.Wikis.Models.Wiki_Page_Ref'Class); -- Create a new wiki content for the wiki page. procedure Create_Wiki_Content (Model : in Wiki_Module; Page : in out AWA.Wikis.Models.Wiki_Page_Ref'Class; Content : in out AWA.Wikis.Models.Wiki_Content_Ref'Class); private type Wiki_Module is new AWA.Modules.Module with null record; end AWA.Wikis.Modules;
Fix compilations warnings
Fix compilations warnings
Ada
apache-2.0
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
d725d5287e496b39cb70559bc0036c4ace043902
awa/plugins/awa-wikis/src/awa-wikis.ads
awa/plugins/awa-wikis/src/awa-wikis.ads
----------------------------------------------------------------------- -- awa-wikis -- Wiki module -- 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. ----------------------------------------------------------------------- -- = Wikis Module = -- The `Wikis` module provides a complete wiki system which allows users to create -- their own wiki environment with their wiki pages. -- -- @include awa-wikis-modules.ads -- -- @include awa-wikis-beans.ads -- -- == Queries == -- @include-query wiki-page.xml -- @include-query wiki-pages.xml -- @include-query wiki-history.xml -- @include-query wiki-list.xml -- -- == Data model == -- [images/awa_wikis_model.png] -- package AWA.Wikis is pragma Preelaborate; end AWA.Wikis;
----------------------------------------------------------------------- -- awa-wikis -- Wiki module -- 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. ----------------------------------------------------------------------- -- = Wikis Module = -- The `Wikis` module provides a complete wiki system which allows users to create -- their own wiki environment with their wiki pages. -- -- @include awa-wikis-modules.ads -- -- @include awa-wikis-beans.ads -- -- == Queries == -- @include-query wiki-page.xml -- @include-query wiki-pages.xml -- @include-query wiki-history.xml -- @include-query wiki-list.xml -- @include-query wiki-images.xml -- @include-query wiki-images-info.xml -- @include-query wiki-stat.xml -- -- == Data model == -- [images/awa_wikis_model.png] -- package AWA.Wikis is pragma Preelaborate; end AWA.Wikis;
Add more documentation
Add more documentation
Ada
apache-2.0
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
42bd4bae2c73923da54a89addc972e5c25a2d496
awa/src/awa-permissions-controllers.adb
awa/src/awa-permissions-controllers.adb
----------------------------------------------------------------------- -- awa-permissions-controllers -- Permission controllers -- 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 ADO.Sessions; with ADO.Statements; with Util.Log.Loggers; with AWA.Applications; with AWA.Users.Principals; with AWA.Permissions.Services; with AWA.Services.Contexts; package body AWA.Permissions.Controllers is use Util.Log; Log : constant Loggers.Logger := Loggers.Create ("AWA.Permissions.Controllers"); -- ------------------------------ -- Returns true if the user associated with the security context <b>Context</b> has -- the permission to access a database entity. The security context contains some -- information about the entity to check and the permission controller will use an -- SQL statement to verify the permission. -- ------------------------------ overriding function Has_Permission (Handler : in Entity_Controller; Context : in Security.Contexts.Security_Context'Class; Permission : in Security.Permissions.Permission'Class) return Boolean is use AWA.Permissions.Services; use AWA.Users.Principals; use type ADO.Identifier; Manager : constant Permission_Manager_Access := Get_Permission_Manager (Context); User_Id : constant ADO.Identifier := Get_User_Identifier (Context.Get_User_Principal); Entity_Id : ADO.Identifier; begin -- If there is no permission manager, permission is denied. if Manager = null or else User_Id = ADO.NO_IDENTIFIER then return False; end if; -- If the user is not logged, permission is denied. if Manager = null or else User_Id = ADO.NO_IDENTIFIER then Log.Info ("No user identifier in the security context. Permission is denied"); return False; end if; Entity_Id := Entity_Permission'Class (Permission).Entity; -- If the security context does not contain the entity identifier, permission is denied. if Entity_Id = ADO.NO_IDENTIFIER then Log.Info ("No entity identifier in the security context. Permission is denied"); return False; end if; declare function Get_Session return ADO.Sessions.Session; -- ------------------------------ -- Get a database session from the AWA application. -- There is no guarantee that a AWA.Services.Contexts be available. -- But if we are within a service context, we must use the current session so -- that we are part of the current transaction. -- ------------------------------ function Get_Session return ADO.Sessions.Session is package ASC renames AWA.Services.Contexts; use type ASC.Service_Context_Access; Ctx : constant ASC.Service_Context_Access := ASC.Current; begin if Ctx /= null then return AWA.Services.Contexts.Get_Session (Ctx); else return Manager.Get_Application.Get_Session; end if; end Get_Session; Session : constant ADO.Sessions.Session := Get_Session; Query : ADO.Statements.Query_Statement := Session.Create_Statement (Handler.SQL); Result : Integer; begin -- Build the query Query.Bind_Param (Name => "entity_type", Value => Handler.Entity); Query.Bind_Param (Name => "entity_id", Value => Entity_Id); Query.Bind_Param (Name => "user_id", Value => User_Id); -- Run the query. We must get a single row result and the value must be > 0. Query.Execute; Result := Query.Get_Result_Integer; if Result >= 0 and Query.Has_Elements then Log.Info ("Permission granted to {0} on entity {1}", ADO.Identifier'Image (User_Id), ADO.Identifier'Image (Entity_Id)); return True; else Log.Info ("Permission denied to {0} on entity {1}", ADO.Identifier'Image (User_Id), ADO.Identifier'Image (Entity_Id)); return False; end if; end; end Has_Permission; end AWA.Permissions.Controllers;
----------------------------------------------------------------------- -- awa-permissions-controllers -- Permission controllers -- 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 ADO.Sessions; with ADO.Statements; with Util.Log.Loggers; with Util.Strings; with AWA.Applications; with AWA.Users.Principals; with AWA.Permissions.Services; with AWA.Services.Contexts; package body AWA.Permissions.Controllers is use Util.Log; Log : constant Loggers.Logger := Loggers.Create ("AWA.Permissions.Controllers"); -- ------------------------------ -- Returns true if the user associated with the security context <b>Context</b> has -- the permission to access a database entity. The security context contains some -- information about the entity to check and the permission controller will use an -- SQL statement to verify the permission. -- ------------------------------ overriding function Has_Permission (Handler : in Entity_Controller; Context : in Security.Contexts.Security_Context'Class; Permission : in Security.Permissions.Permission'Class) return Boolean is use AWA.Permissions.Services; use AWA.Users.Principals; use type ADO.Identifier; use type ADO.Entity_Type; Manager : constant Permission_Manager_Access := Get_Permission_Manager (Context); User_Id : constant ADO.Identifier := Get_User_Identifier (Context.Get_User_Principal); Entity_Id : ADO.Identifier; begin -- If there is no permission manager, permission is denied. if Manager = null or else User_Id = ADO.NO_IDENTIFIER then return False; end if; -- If the user is not logged, permission is denied. if Manager = null or else User_Id = ADO.NO_IDENTIFIER then Log.Info ("No user identifier in the security context. Permission is denied"); return False; end if; Entity_Id := Entity_Permission'Class (Permission).Entity; -- If the security context does not contain the entity identifier, permission is denied. if Entity_Id = ADO.NO_IDENTIFIER then Log.Info ("No entity identifier in the security context. Permission is denied"); return False; end if; declare function Get_Session return ADO.Sessions.Session; -- ------------------------------ -- Get a database session from the AWA application. -- There is no guarantee that a AWA.Services.Contexts be available. -- But if we are within a service context, we must use the current session so -- that we are part of the current transaction. -- ------------------------------ function Get_Session return ADO.Sessions.Session is package ASC renames AWA.Services.Contexts; use type ASC.Service_Context_Access; Ctx : constant ASC.Service_Context_Access := ASC.Current; begin if Ctx /= null then return AWA.Services.Contexts.Get_Session (Ctx); else return Manager.Get_Application.Get_Session; end if; end Get_Session; Session : constant ADO.Sessions.Session := Get_Session; Query : ADO.Statements.Query_Statement := Session.Create_Statement (Handler.SQL); Result : Integer; begin -- Build the query Query.Bind_Param (Name => "entity_id", Value => Entity_Id); Query.Bind_Param (Name => "user_id", Value => User_Id); if Handler.Entities (2) /= ADO.NO_ENTITY_TYPE then for I in Handler.Entities'Range loop exit when Handler.Entities (I) = ADO.NO_ENTITY_TYPE; Query.Bind_Param (Name => "entity_type_" & Util.Strings.Image (I), Value => Handler.Entities (I)); end loop; else Query.Bind_Param (Name => "entity_type", Value => Handler.Entities (1)); end if; -- Run the query. We must get a single row result and the value must be > 0. Query.Execute; Result := Query.Get_Result_Integer; if Result >= 0 and Query.Has_Elements then Log.Info ("Permission granted to {0} on entity {1}", ADO.Identifier'Image (User_Id), ADO.Identifier'Image (Entity_Id)); return True; else Log.Info ("Permission denied to {0} on entity {1}", ADO.Identifier'Image (User_Id), ADO.Identifier'Image (Entity_Id)); return False; end if; end; end Has_Permission; end AWA.Permissions.Controllers;
Configure the SQL permission query according to a list of entity types
Configure the SQL permission query according to a list of entity types
Ada
apache-2.0
Letractively/ada-awa,Letractively/ada-awa,Letractively/ada-awa,tectronics/ada-awa,tectronics/ada-awa,tectronics/ada-awa
d71f94fba5b8b0c2bd92920c2b035e4e3c22b7e8
regtests/security-policies-tests.adb
regtests/security-policies-tests.adb
----------------------------------------------------------------------- -- Security-policies-tests - Unit tests for Security.Permissions -- Copyright (C) 2011, 2012 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Tests; with Util.Files; with Util.Test_Caller; with Util.Measures; with Security.Contexts; with Security.Policies.Roles; package body Security.Policies.Tests is use Util.Tests; package Caller is new Util.Test_Caller (Test, "Security.Policies"); procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is begin Caller.Add_Test (Suite, "Test Security.Permissions.Create_Role", Test_Create_Role'Access); Caller.Add_Test (Suite, "Test Security.Permissions.Has_Permission", Test_Has_Permission'Access); Caller.Add_Test (Suite, "Test Security.Permissions.Read_Policy", Test_Read_Policy'Access); -- These tests are identical but registered under different names -- for the test documentation. Caller.Add_Test (Suite, "Test Security.Contexts.Has_Permission", Test_Role_Policy'Access); Caller.Add_Test (Suite, "Test Security.Controllers.Roles.Has_Permission", Test_Role_Policy'Access); Caller.Add_Test (Suite, "Test Security.Permissions.Role_Policy", Test_Role_Policy'Access); end Add_Tests; -- ------------------------------ -- Returns true if the given permission is stored in the user principal. -- ------------------------------ function Has_Role (User : in Test_Principal; Role : in Security.Policies.Roles.Role_Type) return Boolean is begin return User.Roles (Role); end Has_Role; -- ------------------------------ -- Get the principal name. -- ------------------------------ function Get_Name (From : in Test_Principal) return String is begin return Util.Strings.To_String (From.Name); end Get_Name; -- ------------------------------ -- Test Create_Role and Get_Role_Name -- ------------------------------ procedure Test_Create_Role (T : in out Test) is use Security.Policies.Roles; M : Security.Policies.Roles.Role_Policy; Role : Role_Type; begin M.Create_Role (Name => "admin", Role => Role); Assert_Equals (T, "admin", M.Get_Role_Name (Role), "Invalid name"); for I in Role + 1 .. Role_Type'Last loop declare Name : constant String := "admin-" & Role_Type'Image (I); Role2 : Role_Type; begin Role2 := M.Find_Role ("admin"); T.Assert (Role2 = Role, "Find_Role returned an invalid role"); M.Create_Role (Name => Name, Role => Role2); Assert_Equals (T, Name, M.Get_Role_Name (Role2), "Invalid name"); end; end loop; end Test_Create_Role; -- ------------------------------ -- Test Has_Permission -- ------------------------------ procedure Test_Has_Permission (T : in out Test) is M : Security.Policies.Policy_Manager (1); Perm : Permissions.Permission_Type; User : Test_Principal; begin -- T.Assert (not M.Has_Permission (User, 1), "User has a non-existing permission"); null; end Test_Has_Permission; -- ------------------------------ -- Test reading policy files -- ------------------------------ procedure Test_Read_Policy (T : in out Test) is M : aliased Security.Policies.Policy_Manager (Max_Policies => 2); Dir : constant String := "regtests/files/permissions/"; Path : constant String := Util.Tests.Get_Path (Dir); User : aliased Test_Principal; Admin_Perm : Policies.Roles.Role_Type; Manager_Perm : Policies.Roles.Role_Type; Context : aliased Security.Contexts.Security_Context; R : Security.Policies.Roles.Role_Policy_Access := new Roles.Role_Policy; begin M.Add_Policy (R.all'Access); M.Read_Policy (Util.Files.Compose (Path, "empty.xml")); R.Add_Role_Type (Name => "admin", Result => Admin_Perm); R.Add_Role_Type (Name => "manager", Result => Manager_Perm); M.Read_Policy (Util.Files.Compose (Path, "simple-policy.xml")); User.Roles (Admin_Perm) := True; Context.Set_Context (Manager => M'Unchecked_Access, Principal => User'Unchecked_Access); -- declare -- S : Util.Measures.Stamp; -- begin -- for I in 1 .. 1_000 loop -- declare -- URI : constant String := "/admin/home/" & Util.Strings.Image (I) & "/l.html"; -- P : constant URI_Permission (URI'Length) -- := URI_Permission '(Len => URI'Length, URI => URI); -- begin -- T.Assert (M.Has_Permission (Context => Context'Unchecked_Access, -- Permission => P), "Permission not granted"); -- end; -- end loop; -- Util.Measures.Report (S, "Has_Permission (1000 calls, cache miss)"); -- end; -- -- declare -- S : Util.Measures.Stamp; -- begin -- for I in 1 .. 1_000 loop -- declare -- URI : constant String := "/admin/home/list.html"; -- P : constant URI_Permission (URI'Length) -- := URI_Permission '(Len => URI'Length, URI => URI); -- begin -- T.Assert (M.Has_Permission (Context => Context'Unchecked_Access, -- Permission => P), "Permission not granted"); -- end; -- end loop; -- Util.Measures.Report (S, "Has_Permission (1000 calls, cache hit)"); -- end; end Test_Read_Policy; -- ------------------------------ -- Read the policy file <b>File</b> and perform a test on the given URI -- with a user having the given role. -- ------------------------------ procedure Check_Policy (T : in out Test; File : in String; Role : in String; URI : in String) is M : aliased Security.Policies.Policy_Manager (1); Dir : constant String := "regtests/files/permissions/"; Path : constant String := Util.Tests.Get_Path (Dir); User : aliased Test_Principal; Admin_Perm : Roles.Role_Type; Context : aliased Security.Contexts.Security_Context; begin M.Read_Policy (Util.Files.Compose (Path, File)); -- -- Admin_Perm := M.Find_Role (Role); -- -- Context.Set_Context (Manager => M'Unchecked_Access, -- Principal => User'Unchecked_Access); -- -- declare -- P : constant URI_Permission (URI'Length) -- := URI_Permission '(Len => URI'Length, URI => URI); -- begin -- -- A user without the role should not have the permission. -- T.Assert (not M.Has_Permission (Context => Context'Unchecked_Access, -- Permission => P), -- "Permission was granted for user without role. URI=" & URI); -- -- -- Set the role. -- User.Roles (Admin_Perm) := True; -- T.Assert (M.Has_Permission (Context => Context'Unchecked_Access, -- Permission => P), -- "Permission was not granted for user with role. URI=" & URI); -- end; end Check_Policy; -- ------------------------------ -- Test reading policy files and using the <role-permission> controller -- ------------------------------ procedure Test_Role_Policy (T : in out Test) is begin T.Check_Policy (File => "policy-with-role.xml", Role => "developer", URI => "/developer/user-should-have-developer-role"); T.Check_Policy (File => "policy-with-role.xml", Role => "manager", URI => "/developer/user-should-have-manager-role"); T.Check_Policy (File => "policy-with-role.xml", Role => "manager", URI => "/manager/user-should-have-manager-role"); T.Check_Policy (File => "policy-with-role.xml", Role => "admin", URI => "/manager/user-should-have-admin-role"); T.Check_Policy (File => "policy-with-role.xml", Role => "admin", URI => "/admin/user-should-have-admin-role"); end Test_Role_Policy; end Security.Policies.Tests;
----------------------------------------------------------------------- -- Security-policies-tests - Unit tests for Security.Permissions -- Copyright (C) 2011, 2012 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Tests; with Util.Files; with Util.Test_Caller; with Util.Measures; with Security.Contexts; with Security.Policies.Roles; package body Security.Policies.Tests is use Util.Tests; package Caller is new Util.Test_Caller (Test, "Security.Policies"); procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is begin Caller.Add_Test (Suite, "Test Security.Permissions.Create_Role", Test_Create_Role'Access); Caller.Add_Test (Suite, "Test Security.Permissions.Has_Permission", Test_Has_Permission'Access); Caller.Add_Test (Suite, "Test Security.Permissions.Read_Policy", Test_Read_Policy'Access); Caller.Add_Test (Suite, "Test Security.Policies.Roles.Set_Roles", Test_Set_Roles'Access); -- These tests are identical but registered under different names -- for the test documentation. Caller.Add_Test (Suite, "Test Security.Contexts.Has_Permission", Test_Role_Policy'Access); Caller.Add_Test (Suite, "Test Security.Controllers.Roles.Has_Permission", Test_Role_Policy'Access); Caller.Add_Test (Suite, "Test Security.Permissions.Role_Policy", Test_Role_Policy'Access); end Add_Tests; -- ------------------------------ -- Returns true if the given permission is stored in the user principal. -- ------------------------------ function Has_Role (User : in Test_Principal; Role : in Security.Policies.Roles.Role_Type) return Boolean is begin return User.Roles (Role); end Has_Role; -- ------------------------------ -- Get the principal name. -- ------------------------------ function Get_Name (From : in Test_Principal) return String is begin return Util.Strings.To_String (From.Name); end Get_Name; -- ------------------------------ -- Test Create_Role and Get_Role_Name -- ------------------------------ procedure Test_Create_Role (T : in out Test) is use Security.Policies.Roles; M : Security.Policies.Roles.Role_Policy; Role : Role_Type; begin M.Create_Role (Name => "admin", Role => Role); Assert_Equals (T, "admin", M.Get_Role_Name (Role), "Invalid name"); for I in Role + 1 .. Role_Type'Last loop declare Name : constant String := "admin-" & Role_Type'Image (I); Role2 : Role_Type; begin Role2 := M.Find_Role ("admin"); T.Assert (Role2 = Role, "Find_Role returned an invalid role"); M.Create_Role (Name => Name, Role => Role2); Assert_Equals (T, Name, M.Get_Role_Name (Role2), "Invalid name"); end; end loop; end Test_Create_Role; -- ------------------------------ -- Test Set_Roles -- ------------------------------ procedure Test_Set_Roles (T : in out Test) is use Security.Policies.Roles; M : Security.Policies.Roles.Role_Policy; Role : Role_Type; Map : Role_Map; begin M.Create_Role (Name => "manager", Role => Role); M.Create_Role (Name => "admin", Role => Role); Assert_Equals (T, "admin", M.Get_Role_Name (Role), "Invalid name"); M.Set_Roles ("admin", Map); end Test_Set_Roles; -- ------------------------------ -- Test Has_Permission -- ------------------------------ procedure Test_Has_Permission (T : in out Test) is M : Security.Policies.Policy_Manager (1); Perm : Permissions.Permission_Type; User : Test_Principal; begin -- T.Assert (not M.Has_Permission (User, 1), "User has a non-existing permission"); null; end Test_Has_Permission; -- ------------------------------ -- Test reading policy files -- ------------------------------ procedure Test_Read_Policy (T : in out Test) is M : aliased Security.Policies.Policy_Manager (Max_Policies => 2); Dir : constant String := "regtests/files/permissions/"; Path : constant String := Util.Tests.Get_Path (Dir); User : aliased Test_Principal; Admin_Perm : Policies.Roles.Role_Type; Manager_Perm : Policies.Roles.Role_Type; Context : aliased Security.Contexts.Security_Context; R : Security.Policies.Roles.Role_Policy_Access := new Roles.Role_Policy; begin M.Add_Policy (R.all'Access); M.Read_Policy (Util.Files.Compose (Path, "empty.xml")); R.Add_Role_Type (Name => "admin", Result => Admin_Perm); R.Add_Role_Type (Name => "manager", Result => Manager_Perm); M.Read_Policy (Util.Files.Compose (Path, "simple-policy.xml")); User.Roles (Admin_Perm) := True; Context.Set_Context (Manager => M'Unchecked_Access, Principal => User'Unchecked_Access); -- declare -- S : Util.Measures.Stamp; -- begin -- for I in 1 .. 1_000 loop -- declare -- URI : constant String := "/admin/home/" & Util.Strings.Image (I) & "/l.html"; -- P : constant URI_Permission (URI'Length) -- := URI_Permission '(Len => URI'Length, URI => URI); -- begin -- T.Assert (M.Has_Permission (Context => Context'Unchecked_Access, -- Permission => P), "Permission not granted"); -- end; -- end loop; -- Util.Measures.Report (S, "Has_Permission (1000 calls, cache miss)"); -- end; -- -- declare -- S : Util.Measures.Stamp; -- begin -- for I in 1 .. 1_000 loop -- declare -- URI : constant String := "/admin/home/list.html"; -- P : constant URI_Permission (URI'Length) -- := URI_Permission '(Len => URI'Length, URI => URI); -- begin -- T.Assert (M.Has_Permission (Context => Context'Unchecked_Access, -- Permission => P), "Permission not granted"); -- end; -- end loop; -- Util.Measures.Report (S, "Has_Permission (1000 calls, cache hit)"); -- end; end Test_Read_Policy; -- ------------------------------ -- Read the policy file <b>File</b> and perform a test on the given URI -- with a user having the given role. -- ------------------------------ procedure Check_Policy (T : in out Test; File : in String; Role : in String; URI : in String) is M : aliased Security.Policies.Policy_Manager (1); Dir : constant String := "regtests/files/permissions/"; Path : constant String := Util.Tests.Get_Path (Dir); User : aliased Test_Principal; Admin_Perm : Roles.Role_Type; Context : aliased Security.Contexts.Security_Context; begin M.Read_Policy (Util.Files.Compose (Path, File)); -- -- Admin_Perm := M.Find_Role (Role); -- -- Context.Set_Context (Manager => M'Unchecked_Access, -- Principal => User'Unchecked_Access); -- -- declare -- P : constant URI_Permission (URI'Length) -- := URI_Permission '(Len => URI'Length, URI => URI); -- begin -- -- A user without the role should not have the permission. -- T.Assert (not M.Has_Permission (Context => Context'Unchecked_Access, -- Permission => P), -- "Permission was granted for user without role. URI=" & URI); -- -- -- Set the role. -- User.Roles (Admin_Perm) := True; -- T.Assert (M.Has_Permission (Context => Context'Unchecked_Access, -- Permission => P), -- "Permission was not granted for user with role. URI=" & URI); -- end; end Check_Policy; -- ------------------------------ -- Test reading policy files and using the <role-permission> controller -- ------------------------------ procedure Test_Role_Policy (T : in out Test) is begin T.Check_Policy (File => "policy-with-role.xml", Role => "developer", URI => "/developer/user-should-have-developer-role"); T.Check_Policy (File => "policy-with-role.xml", Role => "manager", URI => "/developer/user-should-have-manager-role"); T.Check_Policy (File => "policy-with-role.xml", Role => "manager", URI => "/manager/user-should-have-manager-role"); T.Check_Policy (File => "policy-with-role.xml", Role => "admin", URI => "/manager/user-should-have-admin-role"); T.Check_Policy (File => "policy-with-role.xml", Role => "admin", URI => "/admin/user-should-have-admin-role"); end Test_Role_Policy; end Security.Policies.Tests;
Implement the new unit test for Set_Roles
Implement the new unit test for Set_Roles
Ada
apache-2.0
stcarrez/ada-security
5549033a4509a6143bffffa8ebcebc51a4eabfb5
boards/crazyflie/src/stm32-board.ads
boards/crazyflie/src/stm32-board.ads
------------------------------------------------------------------------------ -- -- -- Copyright (C) 2015-2016, 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 STMicroelectronics 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. -- -- -- -- -- -- This file is based on: -- -- -- -- @file stm32f4_discovery.h -- -- @author MCD Application Team -- -- @version V1.1.0 -- -- @date 19-June-2014 -- -- @brief This file contains definitions for STM32F4-Discovery Kit -- -- LEDs, push-buttons hardware resources. -- -- -- -- COPYRIGHT(c) 2014 STMicroelectronics -- ------------------------------------------------------------------------------ -- This file provides declarations for devices on the STM32F4 Discovery kits -- manufactured by ST Microelectronics. with STM32.Device; use STM32.Device; with STM32.GPIO; use STM32.GPIO; with STM32.I2C; use STM32.I2C; with MPU9250; use MPU9250; with AK8963; use AK8963; package STM32.Board is pragma Elaborate_Body; subtype User_LED is GPIO_Point; LED_Blue_L : User_LED renames PD2; LED_Green_L : User_LED renames PC1; LED_Green_R : User_LED renames PC2; LED_Red_L : User_LED renames PC0; LED_Red_R : User_LED renames PC3; RG_LEDs : GPIO_Points := LED_Green_L & LED_Green_R & LED_Red_L & LED_Red_R; All_LEDs : GPIO_Points := RG_LEDs & LED_Blue_L; LCH_LED : GPIO_Point renames LED_Blue_L; procedure Initialize_LEDs; -- MUST be called prior to any use of the LEDs procedure Turn_On (This : in out User_LED); procedure Turn_Off (This : in out User_LED); function Is_On (This : User_LED) return Boolean; procedure All_LEDs_Off with Inline; procedure All_LEDs_On with Inline; procedure Toggle_LED (This : in out User_LED) renames STM32.GPIO.Toggle; procedure Toggle_LEDs (These : in out GPIO_Points) renames STM32.GPIO.Toggle; --------- -- I2C -- --------- procedure Initialize_I2C_GPIO (Port : in out I2C_Port) with -- I2C_2 is not accessible on this board Pre => As_Port_Id (Port) = I2C_Id_1 or else As_Port_Id (Port) = I2C_Id_3; procedure Configure_I2C (Port : in out I2C_Port); MPU_I2C_Port : I2C_Port renames I2C_3; EXT_I2C_Port : I2C_Port renames I2C_1; --------- -- MPU -- --------- MPU_Device : MPU9250.MPU9250_Device (MPU_I2C_Port'Access, High); MAG_Device : AK8963_Device (MPU_I2C_Port'Access, Add_00); end STM32.Board;
------------------------------------------------------------------------------ -- -- -- Copyright (C) 2015-2016, 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 STMicroelectronics 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. -- -- -- -- -- -- This file is based on: -- -- -- -- @file stm32f4_discovery.h -- -- @author MCD Application Team -- -- @version V1.1.0 -- -- @date 19-June-2014 -- -- @brief This file contains definitions for STM32F4-Discovery Kit -- -- LEDs, push-buttons hardware resources. -- -- -- -- COPYRIGHT(c) 2014 STMicroelectronics -- ------------------------------------------------------------------------------ -- This file provides declarations for devices on the STM32F4 Discovery kits -- manufactured by ST Microelectronics. with STM32.Device; use STM32.Device; with STM32.GPIO; use STM32.GPIO; with STM32.I2C; use STM32.I2C; with STM32.SPI; use STM32.SPI; with STM32.Timers; use STM32.Timers; with STM32.USARTs; use STM32.USARTs; with MPU9250; use MPU9250; with AK8963; use AK8963; package STM32.Board is pragma Elaborate_Body; subtype User_LED is GPIO_Point; LED_Blue_L : User_LED renames PD2; LED_Green_L : User_LED renames PC1; LED_Green_R : User_LED renames PC2; LED_Red_L : User_LED renames PC0; LED_Red_R : User_LED renames PC3; RG_LEDs : GPIO_Points := LED_Green_L & LED_Green_R & LED_Red_L & LED_Red_R; All_LEDs : GPIO_Points := RG_LEDs & LED_Blue_L; LCH_LED : GPIO_Point renames LED_Blue_L; procedure Initialize_LEDs; -- MUST be called prior to any use of the LEDs procedure Turn_On (This : in out User_LED); procedure Turn_Off (This : in out User_LED); function Is_On (This : User_LED) return Boolean; procedure All_LEDs_Off with Inline; procedure All_LEDs_On with Inline; procedure Toggle_LED (This : in out User_LED) renames STM32.GPIO.Toggle; procedure Toggle_LEDs (These : in out GPIO_Points) renames STM32.GPIO.Toggle; --------- -- PWM -- --------- MOTOR_123_Timer : Timer renames Timer_2; MOTOR_4_Timer : Timer renames Timer_4; MOTOR_1 : GPIO_Point renames PA1; MOTOR_1_AF : GPIO_Alternate_Function renames GPIO_AF_TIM2; MOTOR_1_Channel : Timer_Channel renames Channel_2; MOTOR_2 : GPIO_Point renames PB11; MOTOR_2_AF : GPIO_Alternate_Function renames GPIO_AF_TIM2; MOTOR_2_Channel : Timer_Channel renames Channel_4; MOTOR_3 : GPIO_Point renames PA15; MOTOR_3_AF : GPIO_Alternate_Function renames GPIO_AF_TIM2; MOTOR_3_Channel : Timer_Channel renames Channel_1; MOTOR_4 : GPIO_Point renames PB9; MOTOR_4_AF : GPIO_Alternate_Function renames GPIO_AF_TIM4; MOTOR_4_Channel : Timer_Channel renames Channel_4; --------- -- I2C -- --------- procedure Initialize_I2C_GPIO (Port : in out I2C_Port) with -- I2C_2 is not accessible on this board Pre => As_Port_Id (Port) = I2C_Id_1 or else As_Port_Id (Port) = I2C_Id_3; procedure Configure_I2C (Port : in out I2C_Port); I2C_MPU_Port : I2C_Port renames I2C_3; I2C_MPU_SCL : GPIO_Point renames PA8; I2C_MPU_SDA : GPIO_Point renames PC9; I2C_EXT_Port : I2C_Port renames I2C_1; I2C_EXT_SCL : GPIO_Point renames PB6; I2C_EXT_SDA : GPIO_Point renames PB7; --------- -- SPI -- --------- EXT_SPI : SPI_Port renames SPI_1; EXT_SCK : GPIO_Point renames PA5; EXT_MISO : GPIO_Point renames PA6; EXT_MOSI : GPIO_Point renames PA7; EXT_CS0 : GPIO_Point renames PC12; EXT_CS1 : GPIO_Point renames PB4; EXT_CS2 : GPIO_Point renames PB5; EXT_CS3 : GPIO_Point renames PB8; --------- -- USB -- --------- USB_ID : GPIO_Point renames PA10; USB_DM : GPIO_Point renames PA11; USB_DP : GPIO_Point renames PA12; -------------------------- -- External connections -- -------------------------- EXT_USART1 : USART renames USART_3; EXT_USART1_AF : GPIO_Alternate_Function renames GPIO_AF_USART3; EXT_USART1_TX : GPIO_Point renames PC10; EXT_USART1_RX : GPIO_Point renames PC11; EXT_USART2 : USART renames USART_2; EXT_USART2_AF : GPIO_Alternate_Function renames GPIO_AF_USART2; EXT_USART2_TX : GPIO_Point renames PA2; EXT_USART2_RX : GPIO_Point renames PA3; ----------- -- Radio -- ----------- NRF_USART : USART renames USART_6; NRF_USART_AF : GPIO_Alternate_Function renames GPIO_AF_USART6; NRF_RX : GPIO_Point renames PC6; NRF_TX : GPIO_Point renames PC7; NRF_SWCLK : GPIO_Point renames PB13; NRF_SWIO : GPIO_Point renames PB15; NRF_FLOW_CTRL : GPIO_Point renames PA4; --------- -- MPU -- --------- MPU_Device : MPU9250.MPU9250_Device (I2C_MPU_Port'Access, High); MPU_INT : GPIO_Point renames PC13; MPU_FSYNC : GPIO_Point renames PC14; MAG_Device : AK8963_Device (I2C_MPU_Port'Access, Add_00); end STM32.Board;
Add the Crazyflie board components to its stm32-board spec.
Add the Crazyflie board components to its stm32-board spec.
Ada
bsd-3-clause
simonjwright/Ada_Drivers_Library,Fabien-Chouteau/Ada_Drivers_Library,lambourg/Ada_Drivers_Library,simonjwright/Ada_Drivers_Library,ellamosi/Ada_BMP_Library,Fabien-Chouteau/Ada_Drivers_Library,AdaCore/Ada_Drivers_Library,AdaCore/Ada_Drivers_Library
225800c8450bee16da51aef4e277611b0fc2f992
src/asf-components-widgets-likes.adb
src/asf-components-widgets-likes.adb
----------------------------------------------------------------------- -- components-widgets-likes -- Social Likes Components -- Copyright (C) 2013 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Locales; with Util.Beans.Objects; with Util.Strings.Tokenizers; with ASF.Requests; with ASF.Contexts.Writer; package body ASF.Components.Widgets.Likes is FB_LAYOUT_ATTR : aliased constant String := "data-layout"; FB_SHOW_FACES_ATTR : aliased constant String := "data-show-faces"; FB_WIDTH_ATTR : aliased constant String := "data-width"; FB_ACTION_ATTR : aliased constant String := "data-action"; FB_FONT_ATTR : aliased constant String := "data-font"; FB_COlORSCHEME_ATTR : aliased constant String := "data-colorscheme"; FB_REF_ATTR : aliased constant String := "data-ref"; FB_KIDS_ATTR : aliased constant String := "data-kid_directed_site"; FB_SEND_ATTR : aliased constant String := "data-send"; TW_VIA_ATTR : aliased constant String := "data-via"; TW_COUNT_ATTR : aliased constant String := "data-count"; TW_SIZE_ATTR : aliased constant String := "data-size"; G_ANNOTATION_ATTR : aliased constant String := "data-annotation"; G_WIDTH_ATTR : aliased constant String := "data-width"; FACEBOOK_ATTRIBUTE_NAMES : Util.Strings.String_Set.Set; FACEBOOK_SCRIPT_ATTRIBUTE : constant String := "asf.widgets.facebook.script"; GOOGLE_ATTRIBUTE_NAMES : Util.Strings.String_Set.Set; GOOGLE_SCRIPT_ATTRIBUTE : constant String := "asf.widgets.google.script"; TWITTER_ATTRIBUTE_NAMES : Util.Strings.String_Set.Set; TWITTER_SCRIPT_ATTRIBUTE : constant String := "asf.widgets.twitter.script"; type Like_Generator_Binding is record Name : Util.Strings.Name_Access; Generator : Like_Generator_Access; end record; type Like_Generator_Array is array (1 .. MAX_LIKE_GENERATOR) of Like_Generator_Binding; FB_NAME : aliased constant String := "facebook"; FB_GENERATOR : aliased Facebook_Like_Generator; G_NAME : aliased constant String := "google+"; G_GENERATOR : aliased Google_Like_Generator; TWITTER_NAME : aliased constant String := "twitter"; TWITTER_GENERATOR : aliased Twitter_Like_Generator; Generators : Like_Generator_Array := (1 => (FB_NAME'Access, FB_GENERATOR'Access), 2 => (G_NAME'Access, G_GENERATOR'Access), 3 => (TWITTER_NAME'Access, TWITTER_GENERATOR'Access), others => (null, null)); -- ------------------------------ -- Render the facebook like button according to the component attributes. -- ------------------------------ overriding procedure Render_Like (Generator : in Facebook_Like_Generator; UI : in UILike'Class; Href : in String; Context : in out ASF.Contexts.Faces.Faces_Context'Class) is Writer : constant Contexts.Writer.Response_Writer_Access := Context.Get_Response_Writer; Request : constant ASF.Requests.Request_Access := Context.Get_Request; begin if not Context.Is_Ajax_Request and then Util.Beans.Objects.Is_Null (Request.Get_Attribute (FACEBOOK_SCRIPT_ATTRIBUTE)) then Request.Set_Attribute (FACEBOOK_SCRIPT_ATTRIBUTE, Util.Beans.Objects.To_Object (True)); Writer.Queue_Script ("(function(d, s, id) { var js, fjs = d.getElementsByTagName(s)[0];" & "if (d.getElementById(id)) return;" & "js = d.createElement(s); js.id = id;" & "js.src = ""//connect.facebook.net/"); Writer.Queue_Script (Util.Locales.To_String (Context.Get_Locale)); Writer.Queue_Script ("/all.js#xfbml=1&;appId=116337738505130"); Writer.Queue_Script (Generator.App_Id); Writer.Queue_Script (""";fjs.parentNode.insertBefore(js, fjs);" & "}(document, 'script', 'facebook-jssdk'));"); Writer.Start_Element ("div"); Writer.Write_Attribute ("id", "fb-root"); Writer.End_Element ("div"); end if; Writer.Start_Element ("div"); Writer.Write_Attribute ("class", "fb-like"); Writer.Write_Attribute ("data-href", Href); UI.Render_Attributes (Context, FACEBOOK_ATTRIBUTE_NAMES, Writer); Writer.End_Element ("div"); end Render_Like; -- ------------------------------ -- Google like generator -- ------------------------------ overriding procedure Render_Like (Generator : in Google_Like_Generator; UI : in UILike'Class; Href : in String; Context : in out ASF.Contexts.Faces.Faces_Context'Class) is pragma Unreferenced (Generator); Writer : constant Contexts.Writer.Response_Writer_Access := Context.Get_Response_Writer; Request : constant ASF.Requests.Request_Access := Context.Get_Request; begin if not Context.Is_Ajax_Request and then Util.Beans.Objects.Is_Null (Request.Get_Attribute (GOOGLE_SCRIPT_ATTRIBUTE)) then Request.Set_Attribute (GOOGLE_SCRIPT_ATTRIBUTE, Util.Beans.Objects.To_Object (True)); Writer.Queue_Include_Script ("https://apis.google.com/js/plusone.js"); end if; Writer.Start_Element ("div"); Writer.Write_Attribute ("class", "g-plusone"); Writer.Write_Attribute ("data-href", Href); UI.Render_Attributes (Context, GOOGLE_ATTRIBUTE_NAMES, Writer); Writer.End_Element ("div"); end Render_Like; -- ------------------------------ -- Tweeter like generator -- ------------------------------ overriding procedure Render_Like (Generator : in Twitter_Like_Generator; UI : in UILike'Class; Href : in String; Context : in out ASF.Contexts.Faces.Faces_Context'Class) is pragma Unreferenced (Generator); Writer : constant Contexts.Writer.Response_Writer_Access := Context.Get_Response_Writer; Request : constant ASF.Requests.Request_Access := Context.Get_Request; Lang : constant String := Util.Locales.Get_ISO3_Language (Context.Get_Locale); begin if not Context.Is_Ajax_Request and then Util.Beans.Objects.Is_Null (Request.Get_Attribute (TWITTER_SCRIPT_ATTRIBUTE)) then Request.Set_Attribute (TWITTER_SCRIPT_ATTRIBUTE, Util.Beans.Objects.To_Object (True)); Writer.Queue_Script ("!function(d,s,id){var js,fjs=d.getElementsByTagName(s)[0]," & "p=/^http:/.test(d.location)?'http':'https';" & "if(!d.getElementById(id)){js=d.createElement(s);js.id=id;" & "js.src=p+'://platform.twitter.com/widgets.js';" & "fjs.parentNode.insertBefore(js,fjs);}}" & "(document, 'script', 'twitter-wjs');"); end if; Writer.Start_Element ("a"); Writer.Write_Attribute ("href", "https://twitter.com/share"); Writer.Write_Attribute ("class", "twitter-share-button"); Writer.Write_Attribute ("data-url", Href); Writer.Write_Attribute ("data-lang", Lang); UI.Render_Attributes (Context, TWITTER_ATTRIBUTE_NAMES, Writer); Writer.Write_Text ("Tweet"); Writer.End_Element ("a"); end Render_Like; -- ------------------------------ -- Get the link to submit in the like action. -- ------------------------------ function Get_Link (UI : in UILike; Context : in ASF.Contexts.Faces.Faces_Context'Class) return String is Href : constant String := UI.Get_Attribute ("href", Context, ""); begin if Href'Length > 0 then return Href; else return Context.Get_Request.Get_Request_URI; end if; end Get_Link; -- ------------------------------ -- Render an image with the source link created from an email address to the Gravatars service. -- ------------------------------ overriding procedure Encode_Begin (UI : in UILike; Context : in out ASF.Contexts.Faces.Faces_Context'Class) is begin if UI.Is_Rendered (Context) then declare Kind : constant String := UI.Get_Attribute ("type", Context, ""); Href : constant String := UILike'Class (UI).Get_Link (Context); procedure Render (Name : in String; Done : out Boolean); procedure Render (Name : in String; Done : out Boolean) is use type Util.Strings.Name_Access; begin Done := False; for I in Generators'Range loop exit when Generators (I).Name = null; if Generators (I).Name.all = Name then Generators (I).Generator.Render_Like (UI, Href, Context); return; end if; end loop; UI.Log_Error ("Like type {0} is not recognized", Name); end Render; begin if Kind'Length = 0 then UI.Log_Error ("The like type is empty."); else Util.Strings.Tokenizers.Iterate_Tokens (Content => Kind, Pattern => ",", Process => Render'Access); end if; end; end if; end Encode_Begin; -- ------------------------------ -- Register the like generator under the given name. -- ------------------------------ procedure Register_Like (Name : in Util.Strings.Name_Access; Generator : in Like_Generator_Access) is use type Util.Strings.Name_Access; begin for I in Generators'Range loop if Generators (I).Name = null then Generators (I).Name := Name; Generators (I).Generator := Generator; return; end if; end loop; end Register_Like; begin FACEBOOK_ATTRIBUTE_NAMES.Insert (FB_LAYOUT_ATTR'Access); FACEBOOK_ATTRIBUTE_NAMES.Insert (FB_SHOW_FACES_ATTR'Access); FACEBOOK_ATTRIBUTE_NAMES.Insert (FB_WIDTH_ATTR'Access); FACEBOOK_ATTRIBUTE_NAMES.Insert (FB_ACTION_ATTR'Access); FACEBOOK_ATTRIBUTE_NAMES.Insert (FB_FONT_ATTR'Access); FACEBOOK_ATTRIBUTE_NAMES.Insert (FB_COlORSCHEME_ATTR'Access); FACEBOOK_ATTRIBUTE_NAMES.Insert (FB_REF_ATTR'Access); FACEBOOK_ATTRIBUTE_NAMES.Insert (FB_KIDS_ATTR'Access); FACEBOOK_ATTRIBUTE_NAMES.Insert (FB_SEND_ATTR'Access); TWITTER_ATTRIBUTE_NAMES.Insert (TW_SIZE_ATTR'Access); TWITTER_ATTRIBUTE_NAMES.Insert (TW_COUNT_ATTR'Access); TWITTER_ATTRIBUTE_NAMES.Insert (TW_VIA_ATTR'Access); GOOGLE_ATTRIBUTE_NAMES.Insert (G_ANNOTATION_ATTR'Access); GOOGLE_ATTRIBUTE_NAMES.Insert (G_WIDTH_ATTR'Access); end ASF.Components.Widgets.Likes;
----------------------------------------------------------------------- -- components-widgets-likes -- Social Likes Components -- Copyright (C) 2013 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Locales; with Util.Beans.Objects; with Util.Strings.Tokenizers; with ASF.Requests; with ASF.Contexts.Writer; package body ASF.Components.Widgets.Likes is FB_LAYOUT_ATTR : aliased constant String := "data-layout"; FB_SHOW_FACES_ATTR : aliased constant String := "data-show-faces"; FB_WIDTH_ATTR : aliased constant String := "data-width"; FB_ACTION_ATTR : aliased constant String := "data-action"; FB_FONT_ATTR : aliased constant String := "data-font"; FB_COlORSCHEME_ATTR : aliased constant String := "data-colorscheme"; FB_REF_ATTR : aliased constant String := "data-ref"; FB_KIDS_ATTR : aliased constant String := "data-kid_directed_site"; FB_SEND_ATTR : aliased constant String := "data-send"; TW_VIA_ATTR : aliased constant String := "data-via"; TW_COUNT_ATTR : aliased constant String := "data-count"; TW_SIZE_ATTR : aliased constant String := "data-size"; G_ANNOTATION_ATTR : aliased constant String := "data-annotation"; G_WIDTH_ATTR : aliased constant String := "data-width"; FACEBOOK_ATTRIBUTE_NAMES : Util.Strings.String_Set.Set; FACEBOOK_SCRIPT_ATTRIBUTE : constant String := "asf.widgets.facebook.script"; GOOGLE_ATTRIBUTE_NAMES : Util.Strings.String_Set.Set; GOOGLE_SCRIPT_ATTRIBUTE : constant String := "asf.widgets.google.script"; TWITTER_ATTRIBUTE_NAMES : Util.Strings.String_Set.Set; TWITTER_SCRIPT_ATTRIBUTE : constant String := "asf.widgets.twitter.script"; type Like_Generator_Binding is record Name : Util.Strings.Name_Access; Generator : Like_Generator_Access; end record; type Like_Generator_Array is array (1 .. MAX_LIKE_GENERATOR) of Like_Generator_Binding; FB_NAME : aliased constant String := "facebook"; FB_GENERATOR : aliased Facebook_Like_Generator; G_NAME : aliased constant String := "google+"; G_GENERATOR : aliased Google_Like_Generator; TWITTER_NAME : aliased constant String := "twitter"; TWITTER_GENERATOR : aliased Twitter_Like_Generator; Generators : Like_Generator_Array := (1 => (FB_NAME'Access, FB_GENERATOR'Access), 2 => (G_NAME'Access, G_GENERATOR'Access), 3 => (TWITTER_NAME'Access, TWITTER_GENERATOR'Access), others => (null, null)); -- ------------------------------ -- Render the facebook like button according to the component attributes. -- ------------------------------ overriding procedure Render_Like (Generator : in Facebook_Like_Generator; UI : in UILike'Class; Href : in String; Context : in out ASF.Contexts.Faces.Faces_Context'Class) is Writer : constant Contexts.Writer.Response_Writer_Access := Context.Get_Response_Writer; Request : constant ASF.Requests.Request_Access := Context.Get_Request; begin if not Context.Is_Ajax_Request and then Util.Beans.Objects.Is_Null (Request.Get_Attribute (FACEBOOK_SCRIPT_ATTRIBUTE)) then Request.Set_Attribute (FACEBOOK_SCRIPT_ATTRIBUTE, Util.Beans.Objects.To_Object (True)); Writer.Queue_Script ("(function(d, s, id) { var js, fjs = d.getElementsByTagName(s)[0];" & "if (d.getElementById(id)) return;" & "js = d.createElement(s); js.id = id;js.async=true;" & "js.src = ""//connect.facebook.net/"); Writer.Queue_Script (Util.Locales.To_String (Context.Get_Locale)); Writer.Queue_Script ("/all.js#xfbml=1&;appId=116337738505130"); Writer.Queue_Script (Generator.App_Id); Writer.Queue_Script (""";fjs.parentNode.insertBefore(js, fjs);" & "}(document, 'script', 'facebook-jssdk'));"); Writer.Start_Element ("div"); Writer.Write_Attribute ("id", "fb-root"); Writer.End_Element ("div"); end if; Writer.Start_Element ("div"); Writer.Write_Attribute ("class", "fb-like"); Writer.Write_Attribute ("data-href", Href); UI.Render_Attributes (Context, FACEBOOK_ATTRIBUTE_NAMES, Writer); Writer.End_Element ("div"); end Render_Like; -- ------------------------------ -- Google like generator -- ------------------------------ overriding procedure Render_Like (Generator : in Google_Like_Generator; UI : in UILike'Class; Href : in String; Context : in out ASF.Contexts.Faces.Faces_Context'Class) is pragma Unreferenced (Generator); Writer : constant Contexts.Writer.Response_Writer_Access := Context.Get_Response_Writer; Request : constant ASF.Requests.Request_Access := Context.Get_Request; begin if not Context.Is_Ajax_Request and then Util.Beans.Objects.Is_Null (Request.Get_Attribute (GOOGLE_SCRIPT_ATTRIBUTE)) then Request.Set_Attribute (GOOGLE_SCRIPT_ATTRIBUTE, Util.Beans.Objects.To_Object (True)); Writer.Queue_Include_Script ("https://apis.google.com/js/plusone.js"); end if; Writer.Start_Element ("div"); Writer.Write_Attribute ("class", "g-plusone"); Writer.Write_Attribute ("data-href", Href); UI.Render_Attributes (Context, GOOGLE_ATTRIBUTE_NAMES, Writer); Writer.End_Element ("div"); end Render_Like; -- ------------------------------ -- Tweeter like generator -- ------------------------------ overriding procedure Render_Like (Generator : in Twitter_Like_Generator; UI : in UILike'Class; Href : in String; Context : in out ASF.Contexts.Faces.Faces_Context'Class) is pragma Unreferenced (Generator); Writer : constant Contexts.Writer.Response_Writer_Access := Context.Get_Response_Writer; Request : constant ASF.Requests.Request_Access := Context.Get_Request; Lang : constant String := Util.Locales.Get_ISO3_Language (Context.Get_Locale); begin if not Context.Is_Ajax_Request and then Util.Beans.Objects.Is_Null (Request.Get_Attribute (TWITTER_SCRIPT_ATTRIBUTE)) then Request.Set_Attribute (TWITTER_SCRIPT_ATTRIBUTE, Util.Beans.Objects.To_Object (True)); Writer.Queue_Script ("!function(d,s,id){var js,fjs=d.getElementsByTagName(s)[0]," & "p=/^http:/.test(d.location)?'http':'https';" & "if(!d.getElementById(id)){js=d.createElement(s);js.id=id;" & "js.src=p+'://platform.twitter.com/widgets.js';" & "fjs.parentNode.insertBefore(js,fjs);}}" & "(document, 'script', 'twitter-wjs');"); end if; Writer.Start_Element ("a"); Writer.Write_Attribute ("href", "https://twitter.com/share"); Writer.Write_Attribute ("class", "twitter-share-button"); Writer.Write_Attribute ("data-url", Href); Writer.Write_Attribute ("data-lang", Lang); UI.Render_Attributes (Context, TWITTER_ATTRIBUTE_NAMES, Writer); Writer.Write_Text ("Tweet"); Writer.End_Element ("a"); end Render_Like; -- ------------------------------ -- Get the link to submit in the like action. -- ------------------------------ function Get_Link (UI : in UILike; Context : in ASF.Contexts.Faces.Faces_Context'Class) return String is Href : constant String := UI.Get_Attribute ("href", Context, ""); begin if Href'Length > 0 then return Href; else return Context.Get_Request.Get_Request_URI; end if; end Get_Link; -- ------------------------------ -- Render an image with the source link created from an email address to the Gravatars service. -- ------------------------------ overriding procedure Encode_Begin (UI : in UILike; Context : in out ASF.Contexts.Faces.Faces_Context'Class) is begin if UI.Is_Rendered (Context) then declare Writer : constant Contexts.Writer.Response_Writer_Access := Context.Get_Response_Writer; Kind : constant String := UI.Get_Attribute ("type", Context, ""); Href : constant String := UILike'Class (UI).Get_Link (Context); Style : constant String := UI.Get_Attribute ("style", Context, ""); Class : constant String := UI.Get_Attribute ("styleClass", Context, ""); procedure Render (Name : in String; Done : out Boolean); procedure Render (Name : in String; Done : out Boolean) is use type Util.Strings.Name_Access; begin Done := False; for I in Generators'Range loop exit when Generators (I).Name = null; if Generators (I).Name.all = Name then Writer.Start_Element ("div"); if Style'Length > 0 then Writer.Write_Attribute ("style", Style); end if; if Class'Length > 0 then Writer.Write_Attribute ("class", Class); end if; Generators (I).Generator.Render_Like (UI, Href, Context); Writer.End_Element ("div"); return; end if; end loop; UI.Log_Error ("Like type {0} is not recognized", Name); end Render; begin if Kind'Length = 0 then UI.Log_Error ("The like type is empty."); else Util.Strings.Tokenizers.Iterate_Tokens (Content => Kind, Pattern => ",", Process => Render'Access); end if; end; end if; end Encode_Begin; -- ------------------------------ -- Register the like generator under the given name. -- ------------------------------ procedure Register_Like (Name : in Util.Strings.Name_Access; Generator : in Like_Generator_Access) is use type Util.Strings.Name_Access; begin for I in Generators'Range loop if Generators (I).Name = null then Generators (I).Name := Name; Generators (I).Generator := Generator; return; end if; end loop; end Register_Like; begin FACEBOOK_ATTRIBUTE_NAMES.Insert (FB_LAYOUT_ATTR'Access); FACEBOOK_ATTRIBUTE_NAMES.Insert (FB_SHOW_FACES_ATTR'Access); FACEBOOK_ATTRIBUTE_NAMES.Insert (FB_WIDTH_ATTR'Access); FACEBOOK_ATTRIBUTE_NAMES.Insert (FB_ACTION_ATTR'Access); FACEBOOK_ATTRIBUTE_NAMES.Insert (FB_FONT_ATTR'Access); FACEBOOK_ATTRIBUTE_NAMES.Insert (FB_COlORSCHEME_ATTR'Access); FACEBOOK_ATTRIBUTE_NAMES.Insert (FB_REF_ATTR'Access); FACEBOOK_ATTRIBUTE_NAMES.Insert (FB_KIDS_ATTR'Access); FACEBOOK_ATTRIBUTE_NAMES.Insert (FB_SEND_ATTR'Access); TWITTER_ATTRIBUTE_NAMES.Insert (TW_SIZE_ATTR'Access); TWITTER_ATTRIBUTE_NAMES.Insert (TW_COUNT_ATTR'Access); TWITTER_ATTRIBUTE_NAMES.Insert (TW_VIA_ATTR'Access); GOOGLE_ATTRIBUTE_NAMES.Insert (G_ANNOTATION_ATTR'Access); GOOGLE_ATTRIBUTE_NAMES.Insert (G_WIDTH_ATTR'Access); end ASF.Components.Widgets.Likes;
Add a div arround the social like button so that we can apply a style and class on it to control some positioning Use the style and styleClass attributes to put on the placement div
Add a div arround the social like button so that we can apply a style and class on it to control some positioning Use the style and styleClass attributes to put on the placement div
Ada
apache-2.0
stcarrez/ada-asf,stcarrez/ada-asf,stcarrez/ada-asf
6eae112cfa9b6c36887b75b13e65cfcbb7329d34
awa/plugins/awa-workspaces/regtests/awa-workspaces-tests.adb
awa/plugins/awa-workspaces/regtests/awa-workspaces-tests.adb
----------------------------------------------------------------------- -- awa-workspaces-tests -- Unit tests for workspaces and invitations -- 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.Strings.Unbounded; with Util.Test_Caller; with Util.Strings; with ADO; with ASF.Requests.Mockup; with ASF.Responses.Mockup; with ASF.Principals; with ASF.Helpers.Beans; with ASF.Tests; with AWA.Users.Models; with AWA.Services.Contexts; with AWA.Tests.Helpers.Users; with Security.Contexts; with AWA.Workspaces.Beans; package body AWA.Workspaces.Tests is use Ada.Strings.Unbounded; use AWA.Tests; function Get_Invitation_Bean is new ASF.Helpers.Beans.Get_Request_Bean (Element_Type => Beans.Invitation_Bean, Element_Access => Beans.Invitation_Bean_Access); package Caller is new Util.Test_Caller (Test, "Workspaces.Beans"); procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is begin Caller.Add_Test (Suite, "Test AWA.Workspaces.Beans.Send", Test_Invite_User'Access); end Add_Tests; -- ------------------------------ -- Verify the anonymous access for the invitation page. -- ------------------------------ procedure Verify_Anonymous (T : in out Test; Key : in String) is Request : ASF.Requests.Mockup.Request; Reply : ASF.Responses.Mockup.Response; begin ASF.Tests.Do_Get (Request, Reply, "/auth/invitation.html", "invitation-view.html"); ASF.Tests.Assert_Contains (T, "Bad or invalid invitation", Reply, "This invitation is invalid"); ASF.Tests.Do_Get (Request, Reply, "/auth/invitation.html?key=test", "invitation-bad.html"); ASF.Tests.Assert_Contains (T, "This invitation is invalid or has expired", Reply, "This invitation is invalid (key)"); ASF.Tests.Do_Get (Request, Reply, "/auth/invitation.html?key=x" & key, "invitation-bad2.html"); ASF.Tests.Assert_Contains (T, "This invitation is invalid or has expired", Reply, "This invitation is invalid (key)"); if Key = "" then return; end if; ASF.Tests.Do_Get (Request, Reply, "/auth/invitation.html?key=" & Key, "invitation-ok.html"); ASF.Tests.Assert_Contains (T, "Accept invitation", Reply, "Accept invitation page is invalid"); end Verify_Anonymous; -- ------------------------------ -- Test sending an invitation. -- ------------------------------ procedure Test_Invite_User (T : in out Test) is use type ADO.Identifier; use type AWA.Workspaces.Beans.Invitation_Bean_Access; Request : ASF.Requests.Mockup.Request; Reply : ASF.Responses.Mockup.Response; Invite : AWA.Workspaces.Beans.Invitation_Bean_Access; Check : AWA.Workspaces.Beans.Invitation_Bean; begin AWA.Tests.Helpers.Users.Login ("[email protected]", Request); Request.Set_Parameter ("email", "[email protected]"); Request.Set_Parameter ("message", "I invite you to this application"); Request.Set_Parameter ("send", "1"); Request.Set_Parameter ("invite", "1"); ASF.Tests.Do_Post (Request, Reply, "/workspaces/invite.html", "invite.html"); T.Assert (Reply.Get_Status = ASF.Responses.SC_OK, "Invalid response after invitation creation"); -- Verify the invitation by looking at the inviteUser bean. Invite := Get_Invitation_Bean (Request, "inviteUser"); T.Assert (Invite /= null, "Null inviteUser bean"); T.Assert (Invite.Get_Id /= ADO.NO_IDENTIFIER, "The invite ID is invalid"); T.Assert (not Invite.Get_Access_Key.Is_Null, "The invite access key is null"); Check.Key := Invite.Get_Access_Key.Get_Access_Key; T.Verify_Anonymous (Invite.Get_Access_Key.Get_Access_Key); end Test_Invite_User; end AWA.Workspaces.Tests;
----------------------------------------------------------------------- -- awa-workspaces-tests -- Unit tests for workspaces and invitations -- 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.Strings.Unbounded; with Util.Test_Caller; with Util.Strings; with ADO; with ASF.Requests.Mockup; with ASF.Responses.Mockup; with ASF.Principals; with ASF.Helpers.Beans; with ASF.Tests; with AWA.Users.Models; with AWA.Services.Contexts; with AWA.Tests.Helpers.Users; with Security.Contexts; with AWA.Workspaces.Beans; package body AWA.Workspaces.Tests is use Ada.Strings.Unbounded; use AWA.Tests; function Get_Invitation_Bean is new ASF.Helpers.Beans.Get_Request_Bean (Element_Type => Beans.Invitation_Bean, Element_Access => Beans.Invitation_Bean_Access); package Caller is new Util.Test_Caller (Test, "Workspaces.Beans"); procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is begin Caller.Add_Test (Suite, "Test AWA.Workspaces.Beans.Send", Test_Invite_User'Access); end Add_Tests; -- ------------------------------ -- Verify the anonymous access for the invitation page. -- ------------------------------ procedure Verify_Anonymous (T : in out Test; Key : in String) is Request : ASF.Requests.Mockup.Request; Reply : ASF.Responses.Mockup.Response; begin ASF.Tests.Do_Get (Request, Reply, "/auth/invitation.html", "invitation-view.html"); ASF.Tests.Assert_Contains (T, "Bad or invalid invitation", Reply, "This invitation is invalid"); ASF.Tests.Do_Get (Request, Reply, "/auth/invitation.html?key=test", "invitation-bad.html"); ASF.Tests.Assert_Contains (T, "This invitation is invalid or has expired", Reply, "This invitation is invalid (key)"); ASF.Tests.Do_Get (Request, Reply, "/auth/invitation.html?key=x" & key, "invitation-bad2.html"); ASF.Tests.Assert_Contains (T, "This invitation is invalid or has expired", Reply, "This invitation is invalid (key)"); if Key = "" then return; end if; ASF.Tests.Do_Get (Request, Reply, "/auth/invitation.html?key=" & Key, "invitation-ok.html"); ASF.Tests.Assert_Contains (T, "Accept invitation", Reply, "Accept invitation page is invalid"); end Verify_Anonymous; -- ------------------------------ -- Test sending an invitation. -- ------------------------------ procedure Test_Invite_User (T : in out Test) is use type ADO.Identifier; use type AWA.Workspaces.Beans.Invitation_Bean_Access; Request : ASF.Requests.Mockup.Request; Reply : ASF.Responses.Mockup.Response; Invite : AWA.Workspaces.Beans.Invitation_Bean_Access; Check : AWA.Workspaces.Beans.Invitation_Bean; begin AWA.Tests.Helpers.Users.Login ("[email protected]", Request); Request.Set_Parameter ("email", "[email protected]"); Request.Set_Parameter ("message", "I invite you to this application"); Request.Set_Parameter ("send", "1"); Request.Set_Parameter ("invite", "1"); ASF.Tests.Do_Post (Request, Reply, "/workspaces/invite.html", "invite.html"); T.Assert (Reply.Get_Status = ASF.Responses.SC_TEMPORARY_REDIRECT, "Invalid response after invitation creation"); -- Verify the invitation by looking at the inviteUser bean. Invite := Get_Invitation_Bean (Request, "inviteUser"); T.Assert (Invite /= null, "Null inviteUser bean"); T.Assert (Invite.Get_Id /= ADO.NO_IDENTIFIER, "The invite ID is invalid"); T.Assert (not Invite.Get_Access_Key.Is_Null, "The invite access key is null"); Check.Key := Invite.Get_Access_Key.Get_Access_Key; T.Verify_Anonymous (Invite.Get_Access_Key.Get_Access_Key); end Test_Invite_User; end AWA.Workspaces.Tests;
Fix unit test for invitation
Fix unit test for invitation
Ada
apache-2.0
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
46216b07db131ee95bd21b7de44d0f5d338d463b
matp/src/mat-formats.adb
matp/src/mat-formats.adb
----------------------------------------------------------------------- -- mat-formats - Format various types for the console or GUI interface -- Copyright (C) 2015 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Strings; package body MAT.Formats is use type MAT.Types.Target_Tick_Ref; Hex_Prefix : Boolean := True; Hex_Length : Positive := 16; Conversion : constant String (1 .. 10) := "0123456789"; function Location (File : in Ada.Strings.Unbounded.Unbounded_String) return String; function Event_Malloc (Item : in MAT.Events.Target_Event_Type; Related : in MAT.Events.Tools.Target_Event_Vector; Start_Time : in MAT.Types.Target_Tick_Ref) return String; function Event_Free (Item : in MAT.Events.Target_Event_Type; Related : in MAT.Events.Tools.Target_Event_Vector; Start_Time : in MAT.Types.Target_Tick_Ref) return String; -- ------------------------------ -- Set the size of a target address to format them. -- ------------------------------ procedure Set_Address_Size (Size : in Positive) is begin Hex_Length := Size; end Set_Address_Size; -- ------------------------------ -- Format the PID into a string. -- ------------------------------ function Pid (Value : in MAT.Types.Target_Process_Ref) return String is begin return Util.Strings.Image (Natural (Value)); end Pid; -- ------------------------------ -- Format the address into a string. -- ------------------------------ function Addr (Value : in MAT.Types.Target_Addr) return String is Hex : constant String := MAT.Types.Hex_Image (Value, Hex_Length); begin if Hex_Prefix then return "0x" & Hex; else return Hex; end if; end Addr; -- ------------------------------ -- Format the size into a string. -- ------------------------------ function Size (Value : in MAT.Types.Target_Size) return String is Result : constant String := MAT.Types.Target_Size'Image (Value); begin if Result (Result'First) = ' ' then return Result (Result'First + 1 .. Result'Last); else return Result; end if; end Size; -- ------------------------------ -- Format the memory growth size into a string. -- ------------------------------ function Size (Alloced : in MAT.Types.Target_Size; Freed : in MAT.Types.Target_Size) return String is use type MAT.Types.Target_Size; begin if Alloced > Freed then return Size (Alloced - Freed); elsif Alloced < Freed then return "-" & Size (Freed - Alloced); else return "=" & Size (Alloced); end if; end Size; -- ------------------------------ -- Format the time relative to the start time. -- ------------------------------ function Time (Value : in MAT.Types.Target_Tick_Ref; Start : in MAT.Types.Target_Tick_Ref) return String is T : constant MAT.Types.Target_Tick_Ref := Value - Start; Sec : constant MAT.Types.Target_Tick_Ref := T / 1_000_000; Usec : constant MAT.Types.Target_Tick_Ref := T mod 1_000_000; Msec : Natural := Natural (Usec / 1_000); Frac : String (1 .. 5); begin Frac (5) := 's'; Frac (4) := Conversion (Msec mod 10 + 1); Msec := Msec / 10; Frac (3) := Conversion (Msec mod 10 + 1); Msec := Msec / 10; Frac (2) := Conversion (Msec mod 10 + 1); Frac (1) := '.'; return MAT.Types.Target_Tick_Ref'Image (Sec) & Frac; end Time; -- ------------------------------ -- Format the duration in seconds, milliseconds or microseconds. -- ------------------------------ function Duration (Value : in MAT.Types.Target_Tick_Ref) return String is Sec : constant MAT.Types.Target_Tick_Ref := Value / 1_000_000; Usec : constant MAT.Types.Target_Tick_Ref := Value mod 1_000_000; Msec : constant Natural := Natural (Usec / 1_000); Val : Natural; Frac : String (1 .. 5); begin if Sec = 0 and Msec = 0 then return Util.Strings.Image (Integer (Usec)) & "us"; elsif Sec = 0 then Val := Natural (Usec mod 1_000); Frac (5) := 's'; Frac (4) := 'm'; Frac (3) := Conversion (Val mod 10 + 1); Val := Val / 10; Frac (3) := Conversion (Val mod 10 + 1); Val := Val / 10; Frac (2) := Conversion (Val mod 10 + 1); Frac (1) := '.'; return Util.Strings.Image (Integer (Msec)) & Frac; else Val := Msec; Frac (4) := 's'; Frac (3) := Conversion (Val mod 10 + 1); Val := Val / 10; Frac (3) := Conversion (Val mod 10 + 1); Val := Val / 10; Frac (2) := Conversion (Val mod 10 + 1); Frac (1) := '.'; return Util.Strings.Image (Integer (Sec)) & Frac (1 .. 4); end if; end Duration; function Location (File : in Ada.Strings.Unbounded.Unbounded_String) return String is Pos : constant Natural := Ada.Strings.Unbounded.Index (File, "/", Ada.Strings.Backward); Len : constant Natural := Ada.Strings.Unbounded.Length (File); begin if Pos /= 0 then return Ada.Strings.Unbounded.Slice (File, Pos + 1, Len); else return Ada.Strings.Unbounded.To_String (File); end if; end Location; -- ------------------------------ -- Format a file, line, function information into a string. -- ------------------------------ function Location (File : in Ada.Strings.Unbounded.Unbounded_String; Line : in Natural; Func : in Ada.Strings.Unbounded.Unbounded_String) return String is begin if Ada.Strings.Unbounded.Length (File) = 0 then return Ada.Strings.Unbounded.To_String (Func); elsif Line > 0 then declare Num : constant String := Natural'Image (Line); begin return Ada.Strings.Unbounded.To_String (Func) & " (" & Location (File) & ":" & Num (Num'First + 1 .. Num'Last) & ")"; end; else return Ada.Strings.Unbounded.To_String (Func) & " (" & Location (File) & ")"; end if; end Location; -- ------------------------------ -- Format an event range description. -- ------------------------------ function Event (First : in MAT.Events.Target_Event_Type; Last : in MAT.Events.Target_Event_Type) return String is use type MAT.Events.Event_Id_Type; Id1 : constant String := MAT.Events.Event_Id_Type'Image (First.Id); Id2 : constant String := MAT.Events.Event_Id_Type'Image (Last.Id); begin if First.Id = Last.Id then return Id1 (Id1'First + 1 .. Id1'Last); else return Id1 (Id1'First + 1 .. Id1'Last) & ".." & Id2 (Id2'First + 1 .. Id2'Last); end if; end Event; -- ------------------------------ -- Format a short description of the event. -- ------------------------------ function Event (Item : in MAT.Events.Target_Event_Type; Mode : in Format_Type := NORMAL) return String is use type MAT.Types.Target_Addr; begin case Item.Index is when MAT.Events.MSG_MALLOC => if Mode = BRIEF then return "malloc"; else return "malloc(" & Size (Item.Size) & ") = " & Addr (Item.Addr); end if; when MAT.Events.MSG_REALLOC => if Mode = BRIEF then if Item.Old_Addr = 0 then return "realloc"; else return "realloc"; end if; else if Item.Old_Addr = 0 then return "realloc(0," & Size (Item.Size) & ") = " & Addr (Item.Addr); else return "realloc(" & Addr (Item.Old_Addr) & "," & Size (Item.Size) & ") = " & Addr (Item.Addr); end if; end if; when MAT.Events.MSG_FREE => if Mode = BRIEF then return "free"; else return "free(" & Addr (Item.Addr) & "), " & Size (Item.Size); end if; when MAT.Events.MSG_BEGIN => return "begin"; when MAT.Events.MSG_END => return "end"; when MAT.Events.MSG_LIBRARY => return "library"; end case; end Event; function Event_Malloc (Item : in MAT.Events.Target_Event_Type; Related : in MAT.Events.Tools.Target_Event_Vector; Start_Time : in MAT.Types.Target_Tick_Ref) return String is Free_Event : MAT.Events.Target_Event_Type; begin Free_Event := MAT.Events.Tools.Find (Related, MAT.Events.MSG_FREE); return Size (Item.Size) & " bytes allocated after " & Duration (Item.Time - Start_Time) & ", freed " & Duration (Free_Event.Time - Item.Time) & " after by event" & MAT.Events.Event_Id_Type'Image (Free_Event.Id) ; exception when MAT.Events.Tools.Not_Found => return Size (Item.Size) & " bytes allocated (never freed)"; end Event_Malloc; function Event_Free (Item : in MAT.Events.Target_Event_Type; Related : in MAT.Events.Tools.Target_Event_Vector; Start_Time : in MAT.Types.Target_Tick_Ref) return String is Alloc_Event : MAT.Events.Target_Event_Type; begin Alloc_Event := MAT.Events.Tools.Find (Related, MAT.Events.MSG_MALLOC); return Size (Alloc_Event.Size) & " bytes freed after " & Duration (Item.Time - Start_Time) & ", alloc'ed for " & Duration (Item.Time - Alloc_Event.Time) & " by event" & MAT.Events.Event_Id_Type'Image (Alloc_Event.Id); exception when MAT.Events.Tools.Not_Found => return Size (Item.Size) & " bytes freed"; end Event_Free; -- ------------------------------ -- Format a short description of the event. -- ------------------------------ function Event (Item : in MAT.Events.Target_Event_Type; Related : in MAT.Events.Tools.Target_Event_Vector; Start_Time : in MAT.Types.Target_Tick_Ref) return String is begin case Item.Index is when MAT.Events.MSG_MALLOC => return Event_Malloc (Item, Related, Start_Time); when MAT.Events.MSG_REALLOC => return Size (Item.Size) & " bytes reallocated"; when MAT.Events.MSG_FREE => return Event_Free (Item, Related, Start_Time); when MAT.Events.MSG_BEGIN => return "Begin event"; when MAT.Events.MSG_END => return "End event"; when MAT.Events.MSG_LIBRARY => return "Library information event"; end case; end Event; -- ------------------------------ -- Format the difference between two event IDs (offset). -- ------------------------------ function Offset (First : in MAT.Events.Event_Id_Type; Second : in MAT.Events.Event_Id_Type) return String is use type MAT.Events.Event_Id_Type; begin if First = Second or First = 0 or Second = 0 then return ""; elsif First > Second then return "+" & Util.Strings.Image (Natural (First - Second)); else return "-" & Util.Strings.Image (Natural (Second - First)); end if; end Offset; -- ------------------------------ -- Format a short description of the memory allocation slot. -- ------------------------------ function Slot (Value : in MAT.Types.Target_Addr; Item : in MAT.Memory.Allocation; Start_Time : in MAT.Types.Target_Tick_Ref) return String is begin return Addr (Value) & " is " & Size (Item.Size) & " bytes allocated after " & Duration (Item.Time - Start_Time) & " by event" & MAT.Events.Event_Id_Type'Image (Item.Event); end Slot; end MAT.Formats;
----------------------------------------------------------------------- -- mat-formats - Format various types for the console or GUI interface -- Copyright (C) 2015 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Strings; package body MAT.Formats is use type MAT.Types.Target_Tick_Ref; Hex_Prefix : constant Boolean := True; Hex_Length : Positive := 16; Conversion : constant String (1 .. 10) := "0123456789"; function Location (File : in Ada.Strings.Unbounded.Unbounded_String) return String; -- Format a short description of a malloc event. function Event_Malloc (Item : in MAT.Events.Target_Event_Type; Related : in MAT.Events.Tools.Target_Event_Vector; Start_Time : in MAT.Types.Target_Tick_Ref) return String; -- Format a short description of a realloc event. function Event_Realloc (Item : in MAT.Events.Target_Event_Type; Related : in MAT.Events.Tools.Target_Event_Vector; Start_Time : in MAT.Types.Target_Tick_Ref) return String; -- Format a short description of a free event. function Event_Free (Item : in MAT.Events.Target_Event_Type; Related : in MAT.Events.Tools.Target_Event_Vector; Start_Time : in MAT.Types.Target_Tick_Ref) return String; -- ------------------------------ -- Set the size of a target address to format them. -- ------------------------------ procedure Set_Address_Size (Size : in Positive) is begin Hex_Length := Size; end Set_Address_Size; -- ------------------------------ -- Format the PID into a string. -- ------------------------------ function Pid (Value : in MAT.Types.Target_Process_Ref) return String is begin return Util.Strings.Image (Natural (Value)); end Pid; -- ------------------------------ -- Format the address into a string. -- ------------------------------ function Addr (Value : in MAT.Types.Target_Addr) return String is Hex : constant String := MAT.Types.Hex_Image (Value, Hex_Length); begin if Hex_Prefix then return "0x" & Hex; else return Hex; end if; end Addr; -- ------------------------------ -- Format the size into a string. -- ------------------------------ function Size (Value : in MAT.Types.Target_Size) return String is Result : constant String := MAT.Types.Target_Size'Image (Value); begin if Result (Result'First) = ' ' then return Result (Result'First + 1 .. Result'Last); else return Result; end if; end Size; -- ------------------------------ -- Format the memory growth size into a string. -- ------------------------------ function Size (Alloced : in MAT.Types.Target_Size; Freed : in MAT.Types.Target_Size) return String is use type MAT.Types.Target_Size; begin if Alloced > Freed then return "+" & Size (Alloced - Freed); elsif Alloced < Freed then return "-" & Size (Freed - Alloced); else return "=" & Size (Alloced); end if; end Size; -- ------------------------------ -- Format the time relative to the start time. -- ------------------------------ function Time (Value : in MAT.Types.Target_Tick_Ref; Start : in MAT.Types.Target_Tick_Ref) return String is T : constant MAT.Types.Target_Tick_Ref := Value - Start; Sec : constant MAT.Types.Target_Tick_Ref := T / 1_000_000; Usec : constant MAT.Types.Target_Tick_Ref := T mod 1_000_000; Msec : Natural := Natural (Usec / 1_000); Frac : String (1 .. 5); begin Frac (5) := 's'; Frac (4) := Conversion (Msec mod 10 + 1); Msec := Msec / 10; Frac (3) := Conversion (Msec mod 10 + 1); Msec := Msec / 10; Frac (2) := Conversion (Msec mod 10 + 1); Frac (1) := '.'; return MAT.Types.Target_Tick_Ref'Image (Sec) & Frac; end Time; -- ------------------------------ -- Format the duration in seconds, milliseconds or microseconds. -- ------------------------------ function Duration (Value : in MAT.Types.Target_Tick_Ref) return String is Sec : constant MAT.Types.Target_Tick_Ref := Value / 1_000_000; Usec : constant MAT.Types.Target_Tick_Ref := Value mod 1_000_000; Msec : constant Natural := Natural (Usec / 1_000); Val : Natural; Frac : String (1 .. 5); begin if Sec = 0 and Msec = 0 then return Util.Strings.Image (Integer (Usec)) & "us"; elsif Sec = 0 then Val := Natural (Usec mod 1_000); Frac (5) := 's'; Frac (4) := 'm'; Frac (3) := Conversion (Val mod 10 + 1); Val := Val / 10; Frac (3) := Conversion (Val mod 10 + 1); Val := Val / 10; Frac (2) := Conversion (Val mod 10 + 1); Frac (1) := '.'; return Util.Strings.Image (Integer (Msec)) & Frac; else Val := Msec; Frac (4) := 's'; Frac (3) := Conversion (Val mod 10 + 1); Val := Val / 10; Frac (3) := Conversion (Val mod 10 + 1); Val := Val / 10; Frac (2) := Conversion (Val mod 10 + 1); Frac (1) := '.'; return Util.Strings.Image (Integer (Sec)) & Frac (1 .. 4); end if; end Duration; function Location (File : in Ada.Strings.Unbounded.Unbounded_String) return String is Pos : constant Natural := Ada.Strings.Unbounded.Index (File, "/", Ada.Strings.Backward); Len : constant Natural := Ada.Strings.Unbounded.Length (File); begin if Pos /= 0 then return Ada.Strings.Unbounded.Slice (File, Pos + 1, Len); else return Ada.Strings.Unbounded.To_String (File); end if; end Location; -- ------------------------------ -- Format a file, line, function information into a string. -- ------------------------------ function Location (File : in Ada.Strings.Unbounded.Unbounded_String; Line : in Natural; Func : in Ada.Strings.Unbounded.Unbounded_String) return String is begin if Ada.Strings.Unbounded.Length (File) = 0 then return Ada.Strings.Unbounded.To_String (Func); elsif Line > 0 then declare Num : constant String := Natural'Image (Line); begin return Ada.Strings.Unbounded.To_String (Func) & " (" & Location (File) & ":" & Num (Num'First + 1 .. Num'Last) & ")"; end; else return Ada.Strings.Unbounded.To_String (Func) & " (" & Location (File) & ")"; end if; end Location; -- ------------------------------ -- Format an event range description. -- ------------------------------ function Event (First : in MAT.Events.Target_Event_Type; Last : in MAT.Events.Target_Event_Type) return String is use type MAT.Events.Event_Id_Type; Id1 : constant String := MAT.Events.Event_Id_Type'Image (First.Id); Id2 : constant String := MAT.Events.Event_Id_Type'Image (Last.Id); begin if First.Id = Last.Id then return Id1 (Id1'First + 1 .. Id1'Last); else return Id1 (Id1'First + 1 .. Id1'Last) & ".." & Id2 (Id2'First + 1 .. Id2'Last); end if; end Event; -- ------------------------------ -- Format a short description of the event. -- ------------------------------ function Event (Item : in MAT.Events.Target_Event_Type; Mode : in Format_Type := NORMAL) return String is use type MAT.Types.Target_Addr; begin case Item.Index is when MAT.Events.MSG_MALLOC => if Mode = BRIEF then return "malloc"; else return "malloc(" & Size (Item.Size) & ") = " & Addr (Item.Addr); end if; when MAT.Events.MSG_REALLOC => if Mode = BRIEF then if Item.Old_Addr = 0 then return "realloc"; else return "realloc"; end if; else if Item.Old_Addr = 0 then return "realloc(0," & Size (Item.Size) & ") = " & Addr (Item.Addr); else return "realloc(" & Addr (Item.Old_Addr) & "," & Size (Item.Size) & ") = " & Addr (Item.Addr); end if; end if; when MAT.Events.MSG_FREE => if Mode = BRIEF then return "free"; else return "free(" & Addr (Item.Addr) & "), " & Size (Item.Size); end if; when MAT.Events.MSG_BEGIN => return "begin"; when MAT.Events.MSG_END => return "end"; when MAT.Events.MSG_LIBRARY => return "library"; end case; end Event; -- ------------------------------ -- Format a short description of a malloc event. -- ------------------------------ function Event_Malloc (Item : in MAT.Events.Target_Event_Type; Related : in MAT.Events.Tools.Target_Event_Vector; Start_Time : in MAT.Types.Target_Tick_Ref) return String is Free_Event : MAT.Events.Target_Event_Type; begin Free_Event := MAT.Events.Tools.Find (Related, MAT.Events.MSG_FREE); return Size (Item.Size) & " bytes allocated after " & Duration (Item.Time - Start_Time) & ", freed " & Duration (Free_Event.Time - Item.Time) & " after by event" & MAT.Events.Event_Id_Type'Image (Free_Event.Id) ; exception when MAT.Events.Tools.Not_Found => return Size (Item.Size) & " bytes allocated (never freed)"; end Event_Malloc; -- ------------------------------ -- Format a short description of a realloc event. -- ------------------------------ function Event_Realloc (Item : in MAT.Events.Target_Event_Type; Related : in MAT.Events.Tools.Target_Event_Vector; Start_Time : in MAT.Types.Target_Tick_Ref) return String is use type MAT.Events.Event_Id_Type; Free_Event : MAT.Events.Target_Event_Type; begin if Item.Next_Id = 0 and Item.Prev_Id = 0 then return Size (Item.Size) & " bytes reallocated after " & Duration (Item.Time - Start_Time) & " (never freed)"; end if; Free_Event := MAT.Events.Tools.Find (Related, MAT.Events.MSG_FREE); return Size (Item.Size) & " bytes reallocated after " & Duration (Item.Time - Start_Time) & ", freed " & Duration (Free_Event.Time - Item.Time) & " after by event" & MAT.Events.Event_Id_Type'Image (Free_Event.Id) & " " & Size (Item.Size, Item.Old_Size) & " bytes"; exception when MAT.Events.Tools.Not_Found => return Size (Item.Size) & " bytes reallocated after " & Duration (Item.Time - Start_Time) & " (never freed) " & Size (Item.Size, Item.Old_Size) & " bytes"; end Event_Realloc; -- ------------------------------ -- Format a short description of a free event. -- ------------------------------ function Event_Free (Item : in MAT.Events.Target_Event_Type; Related : in MAT.Events.Tools.Target_Event_Vector; Start_Time : in MAT.Types.Target_Tick_Ref) return String is Alloc_Event : MAT.Events.Target_Event_Type; begin Alloc_Event := MAT.Events.Tools.Find (Related, MAT.Events.MSG_MALLOC); return Size (Alloc_Event.Size) & " bytes freed after " & Duration (Item.Time - Start_Time) & ", alloc'ed for " & Duration (Item.Time - Alloc_Event.Time) & " by event" & MAT.Events.Event_Id_Type'Image (Alloc_Event.Id); exception when MAT.Events.Tools.Not_Found => return Size (Item.Size) & " bytes freed"; end Event_Free; -- ------------------------------ -- Format a short description of the event. -- ------------------------------ function Event (Item : in MAT.Events.Target_Event_Type; Related : in MAT.Events.Tools.Target_Event_Vector; Start_Time : in MAT.Types.Target_Tick_Ref) return String is begin case Item.Index is when MAT.Events.MSG_MALLOC => return Event_Malloc (Item, Related, Start_Time); when MAT.Events.MSG_REALLOC => return Event_Realloc (Item, Related, Start_Time); when MAT.Events.MSG_FREE => return Event_Free (Item, Related, Start_Time); when MAT.Events.MSG_BEGIN => return "Begin event"; when MAT.Events.MSG_END => return "End event"; when MAT.Events.MSG_LIBRARY => return "Library information event"; end case; end Event; -- ------------------------------ -- Format the difference between two event IDs (offset). -- ------------------------------ function Offset (First : in MAT.Events.Event_Id_Type; Second : in MAT.Events.Event_Id_Type) return String is use type MAT.Events.Event_Id_Type; begin if First = Second or First = 0 or Second = 0 then return ""; elsif First > Second then return "+" & Util.Strings.Image (Natural (First - Second)); else return "-" & Util.Strings.Image (Natural (Second - First)); end if; end Offset; -- ------------------------------ -- Format a short description of the memory allocation slot. -- ------------------------------ function Slot (Value : in MAT.Types.Target_Addr; Item : in MAT.Memory.Allocation; Start_Time : in MAT.Types.Target_Tick_Ref) return String is begin return Addr (Value) & " is " & Size (Item.Size) & " bytes allocated after " & Duration (Item.Time - Start_Time) & " by event" & MAT.Events.Event_Id_Type'Image (Item.Event); end Slot; end MAT.Formats;
Declare the Event_Realloc function to format a realloc event Implement Event_Realloc and use it in Event to give a realloc event description
Declare the Event_Realloc function to format a realloc event Implement Event_Realloc and use it in Event to give a realloc event description
Ada
apache-2.0
stcarrez/mat,stcarrez/mat,stcarrez/mat
8f3e11945e911e9a9d2dea9d3678beb36d6d8d4e
src/http/util-http-clients.adb
src/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"); -- ------------------------------ -- 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; -- ------------------------------ -- 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; -- ------------------------------ -- 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 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES 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"); -- ------------------------------ -- 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; -- ------------------------------ -- 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; -- ------------------------------ -- 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 the Set_Timeout procedure
Implement the Set_Timeout procedure
Ada
apache-2.0
stcarrez/ada-util,stcarrez/ada-util
f6dc59c81b78420b6bf140486fd845cdb1341768
src/gen-model-xmi.ads
src/gen-model-xmi.ads
----------------------------------------------------------------------- -- gen-model-xmi -- UML-XMI model -- Copyright (C) 2012 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Containers.Hashed_Maps; with Ada.Strings.Unbounded; with Ada.Strings.Unbounded.Hash; with Ada.Containers.Vectors; with Util.Beans.Objects; with Gen.Model.Tables; package Gen.Model.XMI is use Ada.Strings.Unbounded; type Element_Type is (XMI_UNKNOWN, XMI_PACKAGE, XMI_CLASS, XMI_ASSOCIATION, XMI_ASSOCIATION_END, XMI_ATTRIBUTE, XMI_OPERATION, XMI_ENUMERATION, XMI_ENUMERATION_LITERAL, XMI_TAGGED_VALUE, XMI_TAG_DEFINITION, XMI_DATA_TYPE, XMI_STEREOTYPE, XMI_COMMENT); type Visibility_Type is (VISIBILITY_PUBLIC, VISIBILITY_PACKAGE, VISIBILITY_PROTECTED, VISIBILITY_PRIVATE); type Changeability_Type is (CHANGEABILITY_INSERT, CHANGEABILITY_CHANGEABLE, CHANGEABILITY_FROZEN); type Model_Element; type Tagged_Value_Element; type Model_Element_Access is access all Model_Element'Class; type Tagged_Value_Element_Access is access all Tagged_Value_Element'Class; -- Define a list of model elements. package Model_Vectors is new Ada.Containers.Vectors (Index_Type => Positive, Element_Type => Model_Element_Access); subtype Model_Vector is Model_Vectors.Vector; subtype Model_Cursor is Model_Vectors.Cursor; -- Define a map to search an element from its XMI ID. package Model_Map is new Ada.Containers.Hashed_Maps (Key_Type => Unbounded_String, Element_Type => Model_Element_Access, Hash => Ada.Strings.Unbounded.Hash, Equivalent_Keys => "="); subtype Model_Map_Cursor is Model_Map.Cursor; type Model_Map_Access is access all Model_Map.Map; -- Returns true if the table cursor contains a valid table function Has_Element (Position : in Model_Map_Cursor) return Boolean renames Model_Map.Has_Element; -- Returns the table definition. function Element (Position : in Model_Map_Cursor) return Model_Element_Access renames Model_Map.Element; -- Move the iterator to the next table definition. procedure Next (Position : in out Model_Map_Cursor) renames Model_Map.Next; -- Iterate on the model element of the type <tt>On</tt> and execute the <tt>Process</tt> -- procedure. procedure Iterate (Model : in Model_Map.Map; On : in Element_Type; Process : not null access procedure (Id : in Unbounded_String; Node : in Model_Element_Access)); -- Generic procedure to iterate over the XMI elements of a vector -- and having the entity name <b>name</b>. generic type T (<>) is limited private; procedure Iterate_Elements (Closure : in out T; List : in Model_Vector; Process : not null access procedure (Closure : in out T; Node : in Model_Element_Access)); -- Map of UML models indexed on the model name. package UML_Model_Map is new Ada.Containers.Hashed_Maps (Key_Type => Unbounded_String, Element_Type => Model_Map.Map, Hash => Ada.Strings.Unbounded.Hash, Equivalent_Keys => "=", "=" => Model_Map."="); subtype UML_Model is UML_Model_Map.Map; type Search_Type is (BY_NAME, BY_ID); -- Find the model element with the given XMI id. -- Returns null if the model element is not found. function Find (Model : in Model_Map.Map; Key : in String; Mode : in Search_Type := BY_ID) return Model_Element_Access; -- Find the model element within all loaded UML models. -- Returns null if the model element is not found. function Find (Model : in UML_Model; Current : in Model_Map.Map; Id : in Ada.Strings.Unbounded.Unbounded_String) return Model_Element_Access; -- Dump the XMI model elements. procedure Dump (Map : in Model_Map.Map); -- Reconcile all the UML model elements by resolving all the references to UML elements. procedure Reconcile (Model : in out UML_Model); -- ------------------------------ -- Model Element -- ------------------------------ type Model_Element (Model : Model_Map_Access) is abstract new Definition with record -- Element XMI id. XMI_Id : Ada.Strings.Unbounded.Unbounded_String; -- List of tagged values for the element. Tagged_Values : Model_Vector; -- Elements contained. Elements : Model_Vector; -- Stereotypes associated with the element. Stereotypes : Model_Vector; -- The parent model element; Parent : Model_Element_Access; end record; -- Get the element type. function Get_Type (Node : in Model_Element) return Element_Type is abstract; -- Reconcile the element by resolving the references to other elements in the model. procedure Reconcile (Node : in out Model_Element; Model : in UML_Model); -- Find the element with the given name. If the name is a qualified name, navigate -- down the package/class to find the appropriate element. -- Returns null if the element was not found. function Find (Node : in Model_Element; Name : in String) return Model_Element_Access; -- Set the model name. procedure Set_Name (Node : in out Model_Element; Value : in Util.Beans.Objects.Object); -- Set the model XMI unique id. procedure Set_XMI_Id (Node : in out Model_Element; Value : in Util.Beans.Objects.Object); -- Find the tag value element with the given name. -- Returns null if there is no such tag. function Find_Tag_Value (Node : in Model_Element; Name : in String) return Tagged_Value_Element_Access; -- Get the documentation and comment associated with the model element. -- Returns the empty string if there is no comment. function Get_Comment (Node : in Model_Element) return String; -- Get the full qualified name for the element. function Get_Qualified_Name (Node : in Model_Element) return String; -- Find from the model file identified by <tt>Name</tt>, the model element with the -- identifier or name represented by <tt>Key</tt>. -- Returns null if the model element is not found. generic type Element_Type is new Model_Element with private; type Element_Type_Access is access all Element_Type'Class; function Find_Element (Model : in UML_Model; Name : in String; Key : in String; Mode : in Search_Type := BY_ID) return Element_Type_Access; -- ------------------------------ -- Data type -- ------------------------------ type Ref_Type_Element is new Model_Element with record Href : Unbounded_String; Ref : Model_Element_Access; end record; type Ref_Type_Element_Access is access all Ref_Type_Element'Class; -- Get the element type. overriding function Get_Type (Node : in Ref_Type_Element) return Element_Type; -- Reconcile the element by resolving the references to other elements in the model. overriding procedure Reconcile (Node : in out Ref_Type_Element; Model : in UML_Model); -- ------------------------------ -- Data type -- ------------------------------ type Data_Type_Element is new Model_Element with null record; type Data_Type_Element_Access is access all Data_Type_Element'Class; -- Get the element type. overriding function Get_Type (Node : in Data_Type_Element) return Element_Type; -- ------------------------------ -- Enum -- ------------------------------ type Enum_Element is new Model_Element with null record; type Enum_Element_Access is access all Enum_Element'Class; -- Get the element type. overriding function Get_Type (Node : in Enum_Element) return Element_Type; procedure Add_Literal (Node : in out Enum_Element; Id : in Util.Beans.Objects.Object; Name : in Util.Beans.Objects.Object); -- ------------------------------ -- Literal -- ------------------------------ -- The literal describes a possible value for an enum. type Literal_Element is new Model_Element with null record; type Literal_Element_Access is access all Literal_Element'Class; -- Get the element type. overriding function Get_Type (Node : in Literal_Element) return Element_Type; -- ------------------------------ -- Stereotype -- ------------------------------ type Stereotype_Element is new Model_Element with null record; type Stereotype_Element_Access is access all Stereotype_Element'Class; -- Get the element type. overriding function Get_Type (Node : in Stereotype_Element) return Element_Type; -- Returns True if the model element has the stereotype with the given name. function Has_Stereotype (Node : in Model_Element'Class; Stereotype : in Stereotype_Element_Access) return Boolean; -- ------------------------------ -- Comment -- ------------------------------ type Comment_Element is new Model_Element with record Text : Ada.Strings.Unbounded.Unbounded_String; Ref_Id : Ada.Strings.Unbounded.Unbounded_String; end record; type Comment_Element_Access is access all Comment_Element'Class; -- Get the element type. overriding function Get_Type (Node : in Comment_Element) return Element_Type; -- ------------------------------ -- An operation -- ------------------------------ type Operation_Element is new Model_Element with record Visibility : Visibility_Type := VISIBILITY_PUBLIC; end record; type Operation_Element_Access is access all Operation_Element'Class; -- Get the element type. overriding function Get_Type (Node : in Operation_Element) return Element_Type; -- ------------------------------ -- An attribute -- ------------------------------ type Attribute_Element is new Model_Element with record Ref_Id : Ada.Strings.Unbounded.Unbounded_String; Visibility : Visibility_Type := VISIBILITY_PUBLIC; Changeability : Changeability_Type := CHANGEABILITY_CHANGEABLE; Initial_Value : Util.Beans.Objects.Object; Multiplicity_Lower : Integer := 0; Multiplicity_Upper : Integer := 1; end record; type Attribute_Element_Access is access all Attribute_Element'Class; -- Get the element type. overriding function Get_Type (Node : in Attribute_Element) return Element_Type; -- ------------------------------ -- An association end -- ------------------------------ type Association_End_Element is new Model_Element with record Visibility : Visibility_Type := VISIBILITY_PUBLIC; end record; type Association_End_Element_Access is access all Association_End_Element'Class; -- Get the element type. overriding function Get_Type (Node : in Association_End_Element) return Element_Type; -- ------------------------------ -- An association -- ------------------------------ type Association_Element is new Model_Element with record Visibility : Visibility_Type := VISIBILITY_PUBLIC; end record; type Association_Element_Access is access all Association_Element'Class; -- Get the element type. overriding function Get_Type (Node : in Association_Element) return Element_Type; -- ------------------------------ -- Tag Definition -- ------------------------------ TAG_DOCUMENTATION : constant String := "documentation"; TAG_AUTHOR : constant String := "author"; type Tag_Definition_Element is new Model_Element with record Multiplicity_Lower : Natural := 0; Multiplicity_Upper : Natural := 0; end record; type Tag_Definition_Element_Access is access all Tag_Definition_Element'Class; -- Get the element type. overriding function Get_Type (Node : in Tag_Definition_Element) return Element_Type; -- ------------------------------ -- Tagged value -- ------------------------------ type Tagged_Value_Element is new Model_Element with record Value : Ada.Strings.Unbounded.Unbounded_String; Value_Type : Ada.Strings.Unbounded.Unbounded_String; Ref_Id : Ada.Strings.Unbounded.Unbounded_String; Tag_Def : Tag_Definition_Element_Access; end record; -- Get the element type. overriding function Get_Type (Node : in Tagged_Value_Element) return Element_Type; -- Reconcile the element by resolving the references to other elements in the model. overriding procedure Reconcile (Node : in out Tagged_Value_Element; Model : in UML_Model); -- ------------------------------ -- A class -- ------------------------------ type Class_Element is new Model_Element with record Operations : Model_Vector; Attributes : Model_Vector; Associations : Model_Vector; Visibility : Visibility_Type := VISIBILITY_PUBLIC; end record; type Class_Element_Access is access all Class_Element'Class; -- Get the element type. overriding function Get_Type (Node : in Class_Element) return Element_Type; -- ------------------------------ -- A package -- ------------------------------ type Package_Element; type Package_Element_Access is access all Package_Element'Class; type Package_Element is new Model_Element with record Classes : Model_Vector; end record; -- Get the element type. overriding function Get_Type (Node : in Package_Element) return Element_Type; end Gen.Model.XMI;
----------------------------------------------------------------------- -- gen-model-xmi -- UML-XMI model -- Copyright (C) 2012 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Containers.Hashed_Maps; with Ada.Strings.Unbounded; with Ada.Strings.Unbounded.Hash; with Ada.Containers.Vectors; with Util.Beans.Objects; with Gen.Model.Tables; package Gen.Model.XMI is use Ada.Strings.Unbounded; type Element_Type is (XMI_UNKNOWN, XMI_PACKAGE, XMI_CLASS, XMI_ASSOCIATION, XMI_ASSOCIATION_END, XMI_ATTRIBUTE, XMI_OPERATION, XMI_ENUMERATION, XMI_ENUMERATION_LITERAL, XMI_TAGGED_VALUE, XMI_TAG_DEFINITION, XMI_DATA_TYPE, XMI_STEREOTYPE, XMI_COMMENT); -- Defines the visibility of an element (a package, class, attribute, operation). type Visibility_Type is (VISIBILITY_PUBLIC, VISIBILITY_PACKAGE, VISIBILITY_PROTECTED, VISIBILITY_PRIVATE); -- Defines whether an attribute or association changes. type Changeability_Type is (CHANGEABILITY_INSERT, CHANGEABILITY_CHANGEABLE, CHANGEABILITY_FROZEN); type Model_Element; type Tagged_Value_Element; type Model_Element_Access is access all Model_Element'Class; type Tagged_Value_Element_Access is access all Tagged_Value_Element'Class; -- Define a list of model elements. package Model_Vectors is new Ada.Containers.Vectors (Index_Type => Positive, Element_Type => Model_Element_Access); subtype Model_Vector is Model_Vectors.Vector; subtype Model_Cursor is Model_Vectors.Cursor; -- Define a map to search an element from its XMI ID. package Model_Map is new Ada.Containers.Hashed_Maps (Key_Type => Unbounded_String, Element_Type => Model_Element_Access, Hash => Ada.Strings.Unbounded.Hash, Equivalent_Keys => "="); subtype Model_Map_Cursor is Model_Map.Cursor; type Model_Map_Access is access all Model_Map.Map; -- Returns true if the table cursor contains a valid table function Has_Element (Position : in Model_Map_Cursor) return Boolean renames Model_Map.Has_Element; -- Returns the table definition. function Element (Position : in Model_Map_Cursor) return Model_Element_Access renames Model_Map.Element; -- Move the iterator to the next table definition. procedure Next (Position : in out Model_Map_Cursor) renames Model_Map.Next; -- Iterate on the model element of the type <tt>On</tt> and execute the <tt>Process</tt> -- procedure. procedure Iterate (Model : in Model_Map.Map; On : in Element_Type; Process : not null access procedure (Id : in Unbounded_String; Node : in Model_Element_Access)); -- Generic procedure to iterate over the XMI elements of a vector -- and having the entity name <b>name</b>. generic type T (<>) is limited private; procedure Iterate_Elements (Closure : in out T; List : in Model_Vector; Process : not null access procedure (Closure : in out T; Node : in Model_Element_Access)); -- Map of UML models indexed on the model name. package UML_Model_Map is new Ada.Containers.Hashed_Maps (Key_Type => Unbounded_String, Element_Type => Model_Map.Map, Hash => Ada.Strings.Unbounded.Hash, Equivalent_Keys => "=", "=" => Model_Map."="); subtype UML_Model is UML_Model_Map.Map; type Search_Type is (BY_NAME, BY_ID); -- Find the model element with the given XMI id. -- Returns null if the model element is not found. function Find (Model : in Model_Map.Map; Key : in String; Mode : in Search_Type := BY_ID) return Model_Element_Access; -- Find the model element within all loaded UML models. -- Returns null if the model element is not found. function Find (Model : in UML_Model; Current : in Model_Map.Map; Id : in Ada.Strings.Unbounded.Unbounded_String) return Model_Element_Access; -- Dump the XMI model elements. procedure Dump (Map : in Model_Map.Map); -- Reconcile all the UML model elements by resolving all the references to UML elements. procedure Reconcile (Model : in out UML_Model); -- ------------------------------ -- Model Element -- ------------------------------ type Model_Element (Model : Model_Map_Access) is abstract new Definition with record -- Element XMI id. XMI_Id : Ada.Strings.Unbounded.Unbounded_String; -- List of tagged values for the element. Tagged_Values : Model_Vector; -- Elements contained. Elements : Model_Vector; -- Stereotypes associated with the element. Stereotypes : Model_Vector; -- The parent model element; Parent : Model_Element_Access; end record; -- Get the element type. function Get_Type (Node : in Model_Element) return Element_Type is abstract; -- Reconcile the element by resolving the references to other elements in the model. procedure Reconcile (Node : in out Model_Element; Model : in UML_Model); -- Find the element with the given name. If the name is a qualified name, navigate -- down the package/class to find the appropriate element. -- Returns null if the element was not found. function Find (Node : in Model_Element; Name : in String) return Model_Element_Access; -- Set the model name. procedure Set_Name (Node : in out Model_Element; Value : in Util.Beans.Objects.Object); -- Set the model XMI unique id. procedure Set_XMI_Id (Node : in out Model_Element; Value : in Util.Beans.Objects.Object); -- Find the tag value element with the given name. -- Returns null if there is no such tag. function Find_Tag_Value (Node : in Model_Element; Name : in String) return Tagged_Value_Element_Access; -- Get the documentation and comment associated with the model element. -- Returns the empty string if there is no comment. function Get_Comment (Node : in Model_Element) return String; -- Get the full qualified name for the element. function Get_Qualified_Name (Node : in Model_Element) return String; -- Find from the model file identified by <tt>Name</tt>, the model element with the -- identifier or name represented by <tt>Key</tt>. -- Returns null if the model element is not found. generic type Element_Type is new Model_Element with private; type Element_Type_Access is access all Element_Type'Class; function Find_Element (Model : in UML_Model; Name : in String; Key : in String; Mode : in Search_Type := BY_ID) return Element_Type_Access; -- ------------------------------ -- Data type -- ------------------------------ type Ref_Type_Element is new Model_Element with record Href : Unbounded_String; Ref : Model_Element_Access; end record; type Ref_Type_Element_Access is access all Ref_Type_Element'Class; -- Get the element type. overriding function Get_Type (Node : in Ref_Type_Element) return Element_Type; -- Reconcile the element by resolving the references to other elements in the model. overriding procedure Reconcile (Node : in out Ref_Type_Element; Model : in UML_Model); -- ------------------------------ -- Data type -- ------------------------------ type Data_Type_Element is new Model_Element with null record; type Data_Type_Element_Access is access all Data_Type_Element'Class; -- Get the element type. overriding function Get_Type (Node : in Data_Type_Element) return Element_Type; -- ------------------------------ -- Enum -- ------------------------------ type Enum_Element is new Model_Element with null record; type Enum_Element_Access is access all Enum_Element'Class; -- Get the element type. overriding function Get_Type (Node : in Enum_Element) return Element_Type; procedure Add_Literal (Node : in out Enum_Element; Id : in Util.Beans.Objects.Object; Name : in Util.Beans.Objects.Object); -- ------------------------------ -- Literal -- ------------------------------ -- The literal describes a possible value for an enum. type Literal_Element is new Model_Element with null record; type Literal_Element_Access is access all Literal_Element'Class; -- Get the element type. overriding function Get_Type (Node : in Literal_Element) return Element_Type; -- ------------------------------ -- Stereotype -- ------------------------------ type Stereotype_Element is new Model_Element with null record; type Stereotype_Element_Access is access all Stereotype_Element'Class; -- Get the element type. overriding function Get_Type (Node : in Stereotype_Element) return Element_Type; -- Returns True if the model element has the stereotype with the given name. function Has_Stereotype (Node : in Model_Element'Class; Stereotype : in Stereotype_Element_Access) return Boolean; -- ------------------------------ -- Comment -- ------------------------------ type Comment_Element is new Model_Element with record Text : Ada.Strings.Unbounded.Unbounded_String; Ref_Id : Ada.Strings.Unbounded.Unbounded_String; end record; type Comment_Element_Access is access all Comment_Element'Class; -- Get the element type. overriding function Get_Type (Node : in Comment_Element) return Element_Type; -- ------------------------------ -- An operation -- ------------------------------ type Operation_Element is new Model_Element with record Visibility : Visibility_Type := VISIBILITY_PUBLIC; end record; type Operation_Element_Access is access all Operation_Element'Class; -- Get the element type. overriding function Get_Type (Node : in Operation_Element) return Element_Type; -- ------------------------------ -- An attribute -- ------------------------------ type Attribute_Element is new Model_Element with record Ref_Id : Ada.Strings.Unbounded.Unbounded_String; Visibility : Visibility_Type := VISIBILITY_PUBLIC; Changeability : Changeability_Type := CHANGEABILITY_CHANGEABLE; Initial_Value : Util.Beans.Objects.Object; Multiplicity_Lower : Integer := 0; Multiplicity_Upper : Integer := 1; end record; type Attribute_Element_Access is access all Attribute_Element'Class; -- Get the element type. overriding function Get_Type (Node : in Attribute_Element) return Element_Type; -- ------------------------------ -- An association end -- ------------------------------ type Association_End_Element is new Model_Element with record Visibility : Visibility_Type := VISIBILITY_PUBLIC; end record; type Association_End_Element_Access is access all Association_End_Element'Class; -- Get the element type. overriding function Get_Type (Node : in Association_End_Element) return Element_Type; -- ------------------------------ -- An association -- ------------------------------ type Association_Element is new Model_Element with record Visibility : Visibility_Type := VISIBILITY_PUBLIC; end record; type Association_Element_Access is access all Association_Element'Class; -- Get the element type. overriding function Get_Type (Node : in Association_Element) return Element_Type; -- ------------------------------ -- Tag Definition -- ------------------------------ TAG_DOCUMENTATION : constant String := "documentation"; TAG_AUTHOR : constant String := "author"; type Tag_Definition_Element is new Model_Element with record Multiplicity_Lower : Natural := 0; Multiplicity_Upper : Natural := 0; end record; type Tag_Definition_Element_Access is access all Tag_Definition_Element'Class; -- Get the element type. overriding function Get_Type (Node : in Tag_Definition_Element) return Element_Type; -- ------------------------------ -- Tagged value -- ------------------------------ type Tagged_Value_Element is new Model_Element with record Value : Ada.Strings.Unbounded.Unbounded_String; Value_Type : Ada.Strings.Unbounded.Unbounded_String; Ref_Id : Ada.Strings.Unbounded.Unbounded_String; Tag_Def : Tag_Definition_Element_Access; end record; -- Get the element type. overriding function Get_Type (Node : in Tagged_Value_Element) return Element_Type; -- Reconcile the element by resolving the references to other elements in the model. overriding procedure Reconcile (Node : in out Tagged_Value_Element; Model : in UML_Model); -- ------------------------------ -- A class -- ------------------------------ type Class_Element is new Model_Element with record Operations : Model_Vector; Attributes : Model_Vector; Associations : Model_Vector; Visibility : Visibility_Type := VISIBILITY_PUBLIC; end record; type Class_Element_Access is access all Class_Element'Class; -- Get the element type. overriding function Get_Type (Node : in Class_Element) return Element_Type; -- ------------------------------ -- A package -- ------------------------------ type Package_Element; type Package_Element_Access is access all Package_Element'Class; type Package_Element is new Model_Element with record Classes : Model_Vector; end record; -- Get the element type. overriding function Get_Type (Node : in Package_Element) return Element_Type; end Gen.Model.XMI;
Add some comments.
Add some comments.
Ada
apache-2.0
Letractively/ada-gen,Letractively/ada-gen,Letractively/ada-gen,Letractively/ada-gen
582be05d53009d2fd8a394362817f7a859a41ba9
src/gen-generator.ads
src/gen-generator.ads
----------------------------------------------------------------------- -- gen-generator -- Code Generator -- Copyright (C) 2009, 2010, 2011, 2012, 2013 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Text_IO; with Ada.Command_Line; with Ada.Strings.Unbounded; with Ada.Strings.Unbounded.Hash; with Ada.Containers.Hashed_Maps; with Util.Beans.Objects; with Util.Properties; with ASF.Applications.Main; with ASF.Contexts.Faces; with Gen.Model.Packages; with Gen.Model.Projects; with Gen.Artifacts.Hibernate; with Gen.Artifacts.Query; with Gen.Artifacts.Mappings; with Gen.Artifacts.Distribs; with Gen.Artifacts.XMI; package Gen.Generator is -- A fatal error that prevents the generator to proceed has occurred. Fatal_Error : exception; G_URI : constant String := "http://code.google.com/p/ada-ado/generator"; type Package_Type is (PACKAGE_MODEL, PACKAGE_FORMS); type Mapping_File is record Path : Ada.Strings.Unbounded.Unbounded_String; Output : Ada.Text_IO.File_Type; end record; type Handler is new ASF.Applications.Main.Application and Gen.Artifacts.Generator with private; -- Initialize the generator procedure Initialize (H : in out Handler; Config_Dir : in Ada.Strings.Unbounded.Unbounded_String; Debug : in Boolean); -- Get the configuration properties. function Get_Properties (H : in Handler) return Util.Properties.Manager; -- Report an error and set the exit status accordingly procedure Error (H : in out Handler; Message : in String; Arg1 : in String := ""; Arg2 : in String := ""); -- Report an info message. procedure Info (H : in out Handler; Message : in String; Arg1 : in String := ""; Arg2 : in String := ""); -- Read the XML package file procedure Read_Package (H : in out Handler; File : in String); -- Read the model mapping types and initialize the hibernate artifact. procedure Read_Mappings (H : in out Handler); -- Read the XML model file procedure Read_Model (H : in out Handler; File : in String; Silent : in Boolean); -- Read the model and query files stored in the application directory <b>db</b>. procedure Read_Models (H : in out Handler; Dirname : in String); -- Read the XML project file. When <b>Recursive</b> is set, read the GNAT project -- files used by the main project and load all the <b>dynamo.xml</b> files defined -- by these project. procedure Read_Project (H : in out Handler; File : in String; Recursive : in Boolean := False); -- Prepare the model by checking, verifying and initializing it after it is completely known. procedure Prepare (H : in out Handler); -- Finish the generation. Some artifacts could generate other files that take into -- account files generated previously. procedure Finish (H : in out Handler); -- Tell the generator to activate the generation of the given template name. -- The name is a property name that must be defined in generator.properties to -- indicate the template file. Several artifacts can trigger the generation -- of a given template. The template is generated only once. procedure Add_Generation (H : in out Handler; Name : in String; Mode : in Gen.Artifacts.Iteration_Mode; Mapping : in 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 (H : in out Handler; Name : in String); -- Save the content generated by the template generator. procedure Save_Content (H : in out Handler; File : in String; Content : in Ada.Strings.Unbounded.Unbounded_String); -- Generate the code using the template file procedure Generate (H : in out Handler; Mode : in Gen.Artifacts.Iteration_Mode; File : in String; Save : not null access procedure (H : in out Handler; File : in String; Content : in Ada.Strings.Unbounded.Unbounded_String)); -- Generate the code using the template file procedure Generate (H : in out Handler; File : in String; Model : in Gen.Model.Definition_Access; Save : not null access procedure (H : in out Handler; File : in String; Content : in Ada.Strings.Unbounded.Unbounded_String)); -- Generate all the code for the templates activated through <b>Add_Generation</b>. procedure Generate_All (H : in out Handler); -- Generate all the code generation files stored in the directory procedure Generate_All (H : in out Handler; Mode : in Gen.Artifacts.Iteration_Mode; Name : in String); -- Set the directory where template files are stored. procedure Set_Template_Directory (H : in out Handler; Path : in Ada.Strings.Unbounded.Unbounded_String); -- Set the directory where results files are generated. procedure Set_Result_Directory (H : in out Handler; Path : in String); -- Get the result directory path. function Get_Result_Directory (H : in Handler) return String; -- Get the project plugin directory path. function Get_Plugin_Directory (H : in Handler) return String; -- Get the config directory path. function Get_Config_Directory (H : in Handler) return String; -- Get the dynamo installation directory path. function Get_Install_Directory (H : in Handler) return String; -- Return the search directories that the AWA application can use to find files. -- The search directories is built by using the project dependencies. function Get_Search_Directories (H : in Handler) return String; -- Get the exit status -- Returns 0 if the generation was successful -- Returns 1 if there was a generation error function Get_Status (H : in Handler) return Ada.Command_Line.Exit_Status; -- Get the configuration parameter. function Get_Parameter (H : in Handler; Name : in String; Default : in String := "") return String; -- Get the configuration parameter. function Get_Parameter (H : in Handler; Name : in String; Default : in Boolean := False) return Boolean; -- Set the force-save file mode. When False, if the generated file exists already, -- an error message is reported. procedure Set_Force_Save (H : in out Handler; To : in Boolean); -- Set the project name. procedure Set_Project_Name (H : in out Handler; Name : in String); -- Get the project name. function Get_Project_Name (H : in Handler) return String; -- Set the project property. procedure Set_Project_Property (H : in out Handler; Name : in String; Value : in String); -- Get the project property identified by the given name. If the project property -- does not exist, returns the default value. Project properties are loaded -- by <b>Read_Project</b>. function Get_Project_Property (H : in Handler; Name : in String; Default : in String := "") return String; -- Save the project description and parameters. procedure Save_Project (H : in out Handler); -- Get the path of the last generated file. function Get_Generated_File (H : in Handler) return String; -- Update the project model through the <b>Process</b> procedure. procedure Update_Project (H : in out Handler; Process : not null access procedure (P : in out Model.Projects.Root_Project_Definition)); -- Scan the dynamo directories and execute the <b>Process</b> procedure with the -- directory path. procedure Scan_Directories (H : in Handler; Process : not null access procedure (Dir : in String)); private use Ada.Strings.Unbounded; use Gen.Artifacts; type Template_Context is record Mode : Gen.Artifacts.Iteration_Mode; Mapping : Unbounded_String; end record; package Template_Map is new Ada.Containers.Hashed_Maps (Key_Type => Unbounded_String, Element_Type => Template_Context, Hash => Ada.Strings.Unbounded.Hash, Equivalent_Keys => "="); type Handler is new ASF.Applications.Main.Application and Gen.Artifacts.Generator with record Conf : ASF.Applications.Config; -- Config directory. Config_Dir : Ada.Strings.Unbounded.Unbounded_String; -- Output base directory. Output_Dir : Ada.Strings.Unbounded.Unbounded_String; Model : aliased Gen.Model.Packages.Model_Definition; Status : Ada.Command_Line.Exit_Status := 0; -- The file that must be saved (the file attribute in <f:view>. File : access Util.Beans.Objects.Object; -- Indicates whether the file must be saved at each generation or only once. -- This is the mode attribute in <f:view>. Mode : access Util.Beans.Objects.Object; -- Indicates whether the file must be ignored after the generation. -- This is the ignore attribute in <f:view>. It is intended to be used for the package -- body generation to skip that in some cases when it turns out there is no operation. Ignore : access Util.Beans.Objects.Object; -- Whether the AdaMappings.xml file was loaded or not. Type_Mapping_Loaded : Boolean := False; -- The root project document. Project : aliased Gen.Model.Projects.Root_Project_Definition; -- Hibernate XML artifact Hibernate : Gen.Artifacts.Hibernate.Artifact; -- Query generation artifact. Query : Gen.Artifacts.Query.Artifact; -- Type mapping artifact. Mappings : Gen.Artifacts.Mappings.Artifact; -- The distribution artifact. Distrib : Gen.Artifacts.Distribs.Artifact; -- Ada generation from UML-XMI models. XMI : Gen.Artifacts.XMI.Artifact; -- The list of templates that must be generated. Templates : Template_Map.Map; -- Force the saving of a generated file, even if a file already exist. Force_Save : Boolean := True; end record; -- Execute the lifecycle phases on the faces context. overriding procedure Execute_Lifecycle (App : in Handler; Context : in out ASF.Contexts.Faces.Faces_Context'Class); end Gen.Generator;
----------------------------------------------------------------------- -- gen-generator -- Code Generator -- Copyright (C) 2009, 2010, 2011, 2012, 2013 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Text_IO; with Ada.Command_Line; with Ada.Strings.Unbounded; with Ada.Strings.Unbounded.Hash; with Ada.Containers.Hashed_Maps; with Util.Beans.Objects; with Util.Properties; with ASF.Applications.Main; with ASF.Contexts.Faces; with Gen.Model.Packages; with Gen.Model.Projects; with Gen.Artifacts.Hibernate; with Gen.Artifacts.Query; with Gen.Artifacts.Mappings; with Gen.Artifacts.Distribs; with Gen.Artifacts.XMI; package Gen.Generator is -- A fatal error that prevents the generator to proceed has occurred. Fatal_Error : exception; G_URI : constant String := "http://code.google.com/p/ada-ado/generator"; type Package_Type is (PACKAGE_MODEL, PACKAGE_FORMS); type Mapping_File is record Path : Ada.Strings.Unbounded.Unbounded_String; Output : Ada.Text_IO.File_Type; end record; type Handler is new ASF.Applications.Main.Application and Gen.Artifacts.Generator with private; -- Initialize the generator procedure Initialize (H : in out Handler; Config_Dir : in Ada.Strings.Unbounded.Unbounded_String; Debug : in Boolean); -- Get the configuration properties. function Get_Properties (H : in Handler) return Util.Properties.Manager; -- Report an error and set the exit status accordingly procedure Error (H : in out Handler; Message : in String; Arg1 : in String := ""; Arg2 : in String := ""); -- Report an info message. procedure Info (H : in out Handler; Message : in String; Arg1 : in String := ""; Arg2 : in String := ""; Arg3 : in String := ""); -- Read the XML package file procedure Read_Package (H : in out Handler; File : in String); -- Read the model mapping types and initialize the hibernate artifact. procedure Read_Mappings (H : in out Handler); -- Read the XML model file procedure Read_Model (H : in out Handler; File : in String; Silent : in Boolean); -- Read the model and query files stored in the application directory <b>db</b>. procedure Read_Models (H : in out Handler; Dirname : in String); -- Read the XML project file. When <b>Recursive</b> is set, read the GNAT project -- files used by the main project and load all the <b>dynamo.xml</b> files defined -- by these project. procedure Read_Project (H : in out Handler; File : in String; Recursive : in Boolean := False); -- Prepare the model by checking, verifying and initializing it after it is completely known. procedure Prepare (H : in out Handler); -- Finish the generation. Some artifacts could generate other files that take into -- account files generated previously. procedure Finish (H : in out Handler); -- Tell the generator to activate the generation of the given template name. -- The name is a property name that must be defined in generator.properties to -- indicate the template file. Several artifacts can trigger the generation -- of a given template. The template is generated only once. procedure Add_Generation (H : in out Handler; Name : in String; Mode : in Gen.Artifacts.Iteration_Mode; Mapping : in 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 (H : in out Handler; Name : in String); -- Save the content generated by the template generator. procedure Save_Content (H : in out Handler; File : in String; Content : in Ada.Strings.Unbounded.Unbounded_String); -- Generate the code using the template file procedure Generate (H : in out Handler; Mode : in Gen.Artifacts.Iteration_Mode; File : in String; Save : not null access procedure (H : in out Handler; File : in String; Content : in Ada.Strings.Unbounded.Unbounded_String)); -- Generate the code using the template file procedure Generate (H : in out Handler; File : in String; Model : in Gen.Model.Definition_Access; Save : not null access procedure (H : in out Handler; File : in String; Content : in Ada.Strings.Unbounded.Unbounded_String)); -- Generate all the code for the templates activated through <b>Add_Generation</b>. procedure Generate_All (H : in out Handler); -- Generate all the code generation files stored in the directory procedure Generate_All (H : in out Handler; Mode : in Gen.Artifacts.Iteration_Mode; Name : in String); -- Set the directory where template files are stored. procedure Set_Template_Directory (H : in out Handler; Path : in Ada.Strings.Unbounded.Unbounded_String); -- Set the directory where results files are generated. procedure Set_Result_Directory (H : in out Handler; Path : in String); -- Get the result directory path. function Get_Result_Directory (H : in Handler) return String; -- Get the project plugin directory path. function Get_Plugin_Directory (H : in Handler) return String; -- Get the config directory path. function Get_Config_Directory (H : in Handler) return String; -- Get the dynamo installation directory path. function Get_Install_Directory (H : in Handler) return String; -- Return the search directories that the AWA application can use to find files. -- The search directories is built by using the project dependencies. function Get_Search_Directories (H : in Handler) return String; -- Get the exit status -- Returns 0 if the generation was successful -- Returns 1 if there was a generation error function Get_Status (H : in Handler) return Ada.Command_Line.Exit_Status; -- Get the configuration parameter. function Get_Parameter (H : in Handler; Name : in String; Default : in String := "") return String; -- Get the configuration parameter. function Get_Parameter (H : in Handler; Name : in String; Default : in Boolean := False) return Boolean; -- Set the force-save file mode. When False, if the generated file exists already, -- an error message is reported. procedure Set_Force_Save (H : in out Handler; To : in Boolean); -- Set the project name. procedure Set_Project_Name (H : in out Handler; Name : in String); -- Get the project name. function Get_Project_Name (H : in Handler) return String; -- Set the project property. procedure Set_Project_Property (H : in out Handler; Name : in String; Value : in String); -- Get the project property identified by the given name. If the project property -- does not exist, returns the default value. Project properties are loaded -- by <b>Read_Project</b>. function Get_Project_Property (H : in Handler; Name : in String; Default : in String := "") return String; -- Save the project description and parameters. procedure Save_Project (H : in out Handler); -- Get the path of the last generated file. function Get_Generated_File (H : in Handler) return String; -- Update the project model through the <b>Process</b> procedure. procedure Update_Project (H : in out Handler; Process : not null access procedure (P : in out Model.Projects.Root_Project_Definition)); -- Scan the dynamo directories and execute the <b>Process</b> procedure with the -- directory path. procedure Scan_Directories (H : in Handler; Process : not null access procedure (Dir : in String)); private use Ada.Strings.Unbounded; use Gen.Artifacts; type Template_Context is record Mode : Gen.Artifacts.Iteration_Mode; Mapping : Unbounded_String; end record; package Template_Map is new Ada.Containers.Hashed_Maps (Key_Type => Unbounded_String, Element_Type => Template_Context, Hash => Ada.Strings.Unbounded.Hash, Equivalent_Keys => "="); type Handler is new ASF.Applications.Main.Application and Gen.Artifacts.Generator with record Conf : ASF.Applications.Config; -- Config directory. Config_Dir : Ada.Strings.Unbounded.Unbounded_String; -- Output base directory. Output_Dir : Ada.Strings.Unbounded.Unbounded_String; Model : aliased Gen.Model.Packages.Model_Definition; Status : Ada.Command_Line.Exit_Status := 0; -- The file that must be saved (the file attribute in <f:view>. File : access Util.Beans.Objects.Object; -- Indicates whether the file must be saved at each generation or only once. -- This is the mode attribute in <f:view>. Mode : access Util.Beans.Objects.Object; -- Indicates whether the file must be ignored after the generation. -- This is the ignore attribute in <f:view>. It is intended to be used for the package -- body generation to skip that in some cases when it turns out there is no operation. Ignore : access Util.Beans.Objects.Object; -- Whether the AdaMappings.xml file was loaded or not. Type_Mapping_Loaded : Boolean := False; -- The root project document. Project : aliased Gen.Model.Projects.Root_Project_Definition; -- Hibernate XML artifact Hibernate : Gen.Artifacts.Hibernate.Artifact; -- Query generation artifact. Query : Gen.Artifacts.Query.Artifact; -- Type mapping artifact. Mappings : Gen.Artifacts.Mappings.Artifact; -- The distribution artifact. Distrib : Gen.Artifacts.Distribs.Artifact; -- Ada generation from UML-XMI models. XMI : Gen.Artifacts.XMI.Artifact; -- The list of templates that must be generated. Templates : Template_Map.Map; -- Force the saving of a generated file, even if a file already exist. Force_Save : Boolean := True; end record; -- Execute the lifecycle phases on the faces context. overriding procedure Execute_Lifecycle (App : in Handler; Context : in out ASF.Contexts.Faces.Faces_Context'Class); end Gen.Generator;
Add an optional third string parameter to the Info procedure
Add an optional third string parameter to the Info procedure
Ada
apache-2.0
stcarrez/dynamo,stcarrez/dynamo,stcarrez/dynamo
2661dc178617835b00a05c4671aa9f9820e24cbd
awa/plugins/awa-blogs/regtests/awa-blogs-tests.adb
awa/plugins/awa-blogs/regtests/awa-blogs-tests.adb
----------------------------------------------------------------------- -- awa-blogs-tests -- Unit tests for blogs module -- 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.Strings; with ASF.Requests.Mockup; with ASF.Responses.Mockup; with ASF.Principals; with ASF.Tests; with AWA.Users.Models; with AWA.Services.Contexts; with AWA.Tests.Helpers.Users; with Security.Contexts; package body AWA.Blogs.Tests is use Ada.Strings.Unbounded; use AWA.Tests; package Caller is new Util.Test_Caller (Test, "Blogs.Beans"); procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is begin Caller.Add_Test (Suite, "Test AWA.Blogs.Beans.List_Post (Anonymous)", Test_Anonymous_Access'Access); Caller.Add_Test (Suite, "Test AWA.Blogs.Beans.Create_Blog", Test_Create_Blog'Access); Caller.Add_Test (Suite, "Test AWA.Blogs.Beans.Update_Post", Test_Update_Post'Access); Caller.Add_Test (Suite, "Test AWA.Blogs.Beans.List_Post (Admin)", Test_Admin_List_Posts'Access); Caller.Add_Test (Suite, "Test AWA.Blogs.Beans.List_Comments (Admin)", Test_Admin_List_Comments'Access); Caller.Add_Test (Suite, "Test AWA.Blogs.Beans.Stats (Admin)", Test_Admin_Blog_Stats'Access); end Add_Tests; -- ------------------------------ -- Get some access on the blog as anonymous users. -- ------------------------------ procedure Verify_Anonymous (T : in out Test; Post : in String) is Request : ASF.Requests.Mockup.Request; Reply : ASF.Responses.Mockup.Response; begin ASF.Tests.Do_Get (Request, Reply, "/blogs/view.html", "blog-view.html"); ASF.Tests.Assert_Contains (T, "Blog posts", Reply, "Blog view page is invalid"); ASF.Tests.Do_Get (Request, Reply, "/blogs/tagged.html?tag=test", "blog-tagged.html"); ASF.Tests.Assert_Contains (T, "Tag - test", Reply, "Blog tag page is invalid"); ASF.Tests.Do_Get (Request, Reply, "/blogs/post.html?post=missing", "blog-missing.html"); ASF.Tests.Assert_Contains (T, "The post you are looking for does not exist", Reply, "Blog post missing page is invalid"); if Post = "" then return; end if; ASF.Tests.Do_Get (Request, Reply, "/blogs/post.html?post=" & Post, "blog-post.html"); ASF.Tests.Assert_Contains (T, "post-title", Reply, "Blog post page is invalid"); end Verify_Anonymous; -- ------------------------------ -- Test access to the blog as anonymous user. -- ------------------------------ procedure Test_Anonymous_Access (T : in out Test) is begin T.Verify_Anonymous (""); end Test_Anonymous_Access; -- ------------------------------ -- Test creation of blog by simulating web requests. -- ------------------------------ procedure Test_Create_Blog (T : in out Test) is Request : ASF.Requests.Mockup.Request; Reply : ASF.Responses.Mockup.Response; Uuid : constant String := Util.Tests.Get_Uuid; begin AWA.Tests.Helpers.Users.Login ("[email protected]", Request); Request.Set_Parameter ("title", "The Blog Title"); Request.Set_Parameter ("create-blog", "1"); Request.Set_Parameter ("create", "1"); ASF.Tests.Do_Post (Request, Reply, "/blogs/admin/create-blog.html", "create-blog.html"); T.Assert (Reply.Get_Status = ASF.Responses.SC_MOVED_TEMPORARILY, "Invalid response after blog creation"); declare Ident : constant String := Helpers.Extract_Redirect (Reply, "/asfunit/blogs/admin/create.html?id="); begin Util.Tests.Assert_Matches (T, "^[0-9]+$", Ident, "Invalid blog identifier in the response"); T.Blog_Ident := To_Unbounded_String (Ident); Request.Set_Parameter ("post-blog-id", Ident); Request.Set_Parameter ("post", "1"); Request.Set_Parameter ("post-title", "Post title"); Request.Set_Parameter ("text", "The blog post content."); Request.Set_Parameter ("uri", Uuid); Request.Set_Parameter ("save", "1"); Request.Set_Parameter ("post-status", "1"); Request.Set_Parameter ("allow-comment", "0"); ASF.Tests.Do_Post (Request, Reply, "/blogs/admin/create.html", "create-post.html"); T.Post_Ident := Helpers.Extract_Redirect (Reply, "/asfunit/blogs/admin/" & Ident & "/preview/"); Util.Tests.Assert_Matches (T, "^[0-9]+$", To_String (T.Post_Ident), "Invalid post identifier in the response"); end; -- Check public access to the post. T.Post_Uri := To_Unbounded_String (Uuid); T.Verify_Anonymous (Uuid); end Test_Create_Blog; -- ------------------------------ -- Test updating a post by simulating web requests. -- ------------------------------ procedure Test_Update_Post (T : in out Test) is Request : ASF.Requests.Mockup.Request; Reply : ASF.Responses.Mockup.Response; Uuid : constant String := Util.Tests.Get_Uuid; Ident : constant String := To_String (T.Blog_Ident); Post_Ident : Unbounded_String; begin AWA.Tests.Helpers.Users.Login ("[email protected]", Request); Request.Set_Parameter ("post-blog-id", Ident); Request.Set_Parameter ("post-id", To_String (T.Post_Ident)); Request.Set_Parameter ("post", "1"); Request.Set_Parameter ("post-title", "New post title"); Request.Set_Parameter ("text", "The blog post new content."); Request.Set_Parameter ("uri", Uuid); Request.Set_Parameter ("save", "1"); Request.Set_Parameter ("post-status", "1"); Request.Set_Parameter ("allow-comment", "0"); ASF.Tests.Do_Post (Request, Reply, "/blogs/admin/edit.html", "edit-post.html"); Post_Ident := Helpers.Extract_Redirect (Reply, "/asfunit/blogs/admin/" & Ident & "/preview/"); Util.Tests.Assert_Equals (T, To_String (T.Post_Ident), To_String (Post_Ident), "Invalid post identifier returned after post update"); T.Verify_Anonymous (Uuid); end Test_Update_Post; -- ------------------------------ -- Test listing the blog posts. -- ------------------------------ procedure Test_Admin_List_Posts (T : in out Test) is Request : ASF.Requests.Mockup.Request; Reply : ASF.Responses.Mockup.Response; Ident : constant String := To_String (T.Blog_Ident); begin AWA.Tests.Helpers.Users.Login ("[email protected]", Request); ASF.Tests.Do_Get (Request, Reply, "/blogs/admin/list.html?id=" & Ident, "blog-list.html"); ASF.Tests.Assert_Contains (T, "blog-post-list-header", Reply, "Blog admin page is invalid"); end Test_Admin_List_Posts; -- ------------------------------ -- Test listing the blog comments. -- ------------------------------ procedure Test_Admin_List_Comments (T : in out Test) is Request : ASF.Requests.Mockup.Request; Reply : ASF.Responses.Mockup.Response; Ident : constant String := To_String (T.Blog_Ident); begin AWA.Tests.Helpers.Users.Login ("[email protected]", Request); ASF.Tests.Do_Get (Request, Reply, "/blogs/admin/list-comments.html?id=" & Ident, "blog-list-comments.html"); ASF.Tests.Assert_Contains (T, "blog-comment-list-header", Reply, "Blog admin comments page is invalid"); end Test_Admin_List_Comments; -- ------------------------------ -- Test getting the JSON blog stats (for graphs). -- ------------------------------ procedure Test_Admin_Blog_Stats (T : in out Test) is Request : ASF.Requests.Mockup.Request; Reply : ASF.Responses.Mockup.Response; Ident : constant String := To_String (T.Blog_Ident); begin AWA.Tests.Helpers.Users.Login ("[email protected]", Request); ASF.Tests.Do_Get (Request, Reply, "/blogs/admin/" & Ident & "/stats", "blog-stats.html"); ASF.Tests.Assert_Contains (T, "data", Reply, "Blog admin stats page is invalid"); end Test_Admin_Blog_Stats; end AWA.Blogs.Tests;
----------------------------------------------------------------------- -- awa-blogs-tests -- Unit tests for blogs module -- 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 ASF.Requests.Mockup; with ASF.Responses.Mockup; with ASF.Tests; with AWA.Tests.Helpers.Users; package body AWA.Blogs.Tests is use Ada.Strings.Unbounded; use AWA.Tests; package Caller is new Util.Test_Caller (Test, "Blogs.Beans"); procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is begin Caller.Add_Test (Suite, "Test AWA.Blogs.Beans.List_Post (Anonymous)", Test_Anonymous_Access'Access); Caller.Add_Test (Suite, "Test AWA.Blogs.Beans.Create_Blog", Test_Create_Blog'Access); Caller.Add_Test (Suite, "Test AWA.Blogs.Beans.Update_Post", Test_Update_Post'Access); Caller.Add_Test (Suite, "Test AWA.Blogs.Beans.List_Post (Admin)", Test_Admin_List_Posts'Access); Caller.Add_Test (Suite, "Test AWA.Blogs.Beans.List_Comments (Admin)", Test_Admin_List_Comments'Access); Caller.Add_Test (Suite, "Test AWA.Blogs.Beans.Stats (Admin)", Test_Admin_Blog_Stats'Access); end Add_Tests; -- ------------------------------ -- Get some access on the blog as anonymous users. -- ------------------------------ procedure Verify_Anonymous (T : in out Test; Post : in String) is Request : ASF.Requests.Mockup.Request; Reply : ASF.Responses.Mockup.Response; begin ASF.Tests.Do_Get (Request, Reply, "/blogs/view.html", "blog-view.html"); ASF.Tests.Assert_Contains (T, "Blog posts", Reply, "Blog view page is invalid"); ASF.Tests.Do_Get (Request, Reply, "/blogs/tagged.html?tag=test", "blog-tagged.html"); ASF.Tests.Assert_Contains (T, "Tag - test", Reply, "Blog tag page is invalid"); ASF.Tests.Do_Get (Request, Reply, "/blogs/post.html?post=missing", "blog-missing.html"); ASF.Tests.Assert_Contains (T, "The post you are looking for does not exist", Reply, "Blog post missing page is invalid"); if Post = "" then return; end if; ASF.Tests.Do_Get (Request, Reply, "/blogs/post.html?post=" & Post, "blog-post.html"); ASF.Tests.Assert_Contains (T, "post-title", Reply, "Blog post page is invalid"); end Verify_Anonymous; -- ------------------------------ -- Test access to the blog as anonymous user. -- ------------------------------ procedure Test_Anonymous_Access (T : in out Test) is begin T.Verify_Anonymous (""); end Test_Anonymous_Access; -- ------------------------------ -- Test creation of blog by simulating web requests. -- ------------------------------ procedure Test_Create_Blog (T : in out Test) is Request : ASF.Requests.Mockup.Request; Reply : ASF.Responses.Mockup.Response; Uuid : constant String := Util.Tests.Get_Uuid; begin AWA.Tests.Helpers.Users.Login ("[email protected]", Request); Request.Set_Parameter ("title", "The Blog Title"); Request.Set_Parameter ("create-blog", "1"); Request.Set_Parameter ("create", "1"); ASF.Tests.Do_Post (Request, Reply, "/blogs/admin/create-blog.html", "create-blog.html"); T.Assert (Reply.Get_Status = ASF.Responses.SC_MOVED_TEMPORARILY, "Invalid response after blog creation"); declare Ident : constant String := Helpers.Extract_Redirect (Reply, "/asfunit/blogs/admin/create.html?id="); begin Util.Tests.Assert_Matches (T, "^[0-9]+$", Ident, "Invalid blog identifier in the response"); T.Blog_Ident := To_Unbounded_String (Ident); Request.Set_Parameter ("post-blog-id", Ident); Request.Set_Parameter ("post", "1"); Request.Set_Parameter ("post-title", "Post title"); Request.Set_Parameter ("text", "The blog post content."); Request.Set_Parameter ("uri", Uuid); Request.Set_Parameter ("save", "1"); Request.Set_Parameter ("post-status", "1"); Request.Set_Parameter ("allow-comment", "0"); ASF.Tests.Do_Post (Request, Reply, "/blogs/admin/create.html", "create-post.html"); T.Post_Ident := Helpers.Extract_Redirect (Reply, "/asfunit/blogs/admin/" & Ident & "/preview/"); Util.Tests.Assert_Matches (T, "^[0-9]+$", To_String (T.Post_Ident), "Invalid post identifier in the response"); end; -- Check public access to the post. T.Post_Uri := To_Unbounded_String (Uuid); T.Verify_Anonymous (Uuid); end Test_Create_Blog; -- ------------------------------ -- Test updating a post by simulating web requests. -- ------------------------------ procedure Test_Update_Post (T : in out Test) is Request : ASF.Requests.Mockup.Request; Reply : ASF.Responses.Mockup.Response; Uuid : constant String := Util.Tests.Get_Uuid; Ident : constant String := To_String (T.Blog_Ident); Post_Ident : Unbounded_String; begin AWA.Tests.Helpers.Users.Login ("[email protected]", Request); Request.Set_Parameter ("post-blog-id", Ident); Request.Set_Parameter ("post-id", To_String (T.Post_Ident)); Request.Set_Parameter ("post", "1"); Request.Set_Parameter ("post-title", "New post title"); Request.Set_Parameter ("text", "The blog post new content."); Request.Set_Parameter ("uri", Uuid); Request.Set_Parameter ("save", "1"); Request.Set_Parameter ("post-status", "1"); Request.Set_Parameter ("allow-comment", "0"); ASF.Tests.Do_Post (Request, Reply, "/blogs/admin/edit.html", "edit-post.html"); Post_Ident := Helpers.Extract_Redirect (Reply, "/asfunit/blogs/admin/" & Ident & "/preview/"); Util.Tests.Assert_Equals (T, To_String (T.Post_Ident), To_String (Post_Ident), "Invalid post identifier returned after post update"); T.Verify_Anonymous (Uuid); end Test_Update_Post; -- ------------------------------ -- Test listing the blog posts. -- ------------------------------ procedure Test_Admin_List_Posts (T : in out Test) is Request : ASF.Requests.Mockup.Request; Reply : ASF.Responses.Mockup.Response; Ident : constant String := To_String (T.Blog_Ident); begin AWA.Tests.Helpers.Users.Login ("[email protected]", Request); ASF.Tests.Do_Get (Request, Reply, "/blogs/admin/list.html?id=" & Ident, "blog-list.html"); ASF.Tests.Assert_Contains (T, "blog-post-list-header", Reply, "Blog admin page is invalid"); end Test_Admin_List_Posts; -- ------------------------------ -- Test listing the blog comments. -- ------------------------------ procedure Test_Admin_List_Comments (T : in out Test) is Request : ASF.Requests.Mockup.Request; Reply : ASF.Responses.Mockup.Response; Ident : constant String := To_String (T.Blog_Ident); begin AWA.Tests.Helpers.Users.Login ("[email protected]", Request); ASF.Tests.Do_Get (Request, Reply, "/blogs/admin/list-comments.html?id=" & Ident, "blog-list-comments.html"); ASF.Tests.Assert_Contains (T, "blog-comment-list-header", Reply, "Blog admin comments page is invalid"); end Test_Admin_List_Comments; -- ------------------------------ -- Test getting the JSON blog stats (for graphs). -- ------------------------------ procedure Test_Admin_Blog_Stats (T : in out Test) is Request : ASF.Requests.Mockup.Request; Reply : ASF.Responses.Mockup.Response; Ident : constant String := To_String (T.Blog_Ident); begin AWA.Tests.Helpers.Users.Login ("[email protected]", Request); ASF.Tests.Do_Get (Request, Reply, "/blogs/admin/" & Ident & "/stats", "blog-stats.html"); ASF.Tests.Assert_Contains (T, "data", Reply, "Blog admin stats page is invalid"); end Test_Admin_Blog_Stats; end AWA.Blogs.Tests;
Fix compilation warnings
Fix compilation warnings
Ada
apache-2.0
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
3b68848046fe0ec98d38712f98080c8a13c5fa0b
awa/plugins/awa-images/src/awa-images-services.adb
awa/plugins/awa-images/src/awa-images-services.adb
----------------------------------------------------------------------- -- awa-images-services -- Image service -- Copyright (C) 2012, 2013, 2015, 2016 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Processes; with Util.Beans.Objects; with Util.Log.Loggers; with Util.Streams.Pipes; with Util.Streams.Texts; with Util.Strings; with ADO.Sessions; with AWA.Images.Models; with AWA.Services.Contexts; with AWA.Storages.Services; with AWA.Storages.Modules; with Ada.Strings.Unbounded; with EL.Variables.Default; with EL.Contexts.Default; -- == Storage Service == -- The <tt>Storage_Service</tt> provides the operations to access and use the persisent storage. -- It controls the permissions that grant access to the service for users. -- -- Other modules can be notified of storage changes by registering a listener -- on the storage module. package body AWA.Images.Services is package ASC renames AWA.Services.Contexts; -- ------------------------------ -- Image Service -- ------------------------------ Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("AWA.Images.Services"); -- ------------------------------ -- Initializes the storage service. -- ------------------------------ overriding procedure Initialize (Service : in out Image_Service; Module : in AWA.Modules.Module'Class) is begin AWA.Modules.Module_Manager (Service).Initialize (Module); Service.Thumbnail_Command := Module.Get_Config (PARAM_THUMBNAIL_COMMAND); end Initialize; procedure Create_Thumbnail (Service : in Image_Service; Source : in String; Into : in String; Width : in out Natural; Height : in out Natural) is Ctx : EL.Contexts.Default.Default_Context; Variables : aliased EL.Variables.Default.Default_Variable_Mapper; Proc : Util.Processes.Process; Pipe : aliased Util.Streams.Pipes.Pipe_Stream; begin Variables.Bind ("src", Util.Beans.Objects.To_Object (Source)); Variables.Bind ("dst", Util.Beans.Objects.To_Object (Into)); Variables.Bind ("width", Util.Beans.Objects.To_Object (Width)); Variables.Bind ("height", Util.Beans.Objects.To_Object (Height)); Ctx.Set_Variable_Mapper (Variables'Unchecked_Access); declare Cmd : constant Util.Beans.Objects.Object := Service.Thumbnail_Command.Get_Value (Ctx); Command : constant String := Util.Beans.Objects.To_String (Cmd); Input : Util.Streams.Texts.Reader_Stream; begin Width := 0; Height := 0; Pipe.Open (Command, Util.Processes.READ_ALL); Input.Initialize (null, Pipe'Unchecked_Access, 1024); while not Input.Is_Eof loop declare use Ada.Strings; Line : Ada.Strings.Unbounded.Unbounded_String; Pos : Natural; Sep : Natural; Last : Natural; begin Input.Read_Line (Into => Line, Strip => False); exit when Ada.Strings.Unbounded.Length (Line) = 0; Log.Info ("Received: {0}", Line); -- The '-verbose' option of ImageMagick reports information about the original -- image. Extract the picture width and height. -- image.png PNG 120x282 120x282+0+0 8-bit DirectClass 34.4KB 0.000u 0:00.018 Pos := Ada.Strings.Unbounded.Index (Line, " "); if Pos > 0 and Width = 0 then Pos := Ada.Strings.Unbounded.Index (Line, " ", Pos + 1); if Pos > 0 then Sep := Ada.Strings.Unbounded.Index (Line, "x", Pos + 1); Last := Ada.Strings.Unbounded.Index (Line, "=", Pos + 1); if Sep > 0 and Sep < Last then Log.Info ("Dimension {0} - {1}..{2}", Ada.Strings.Unbounded.Slice (Line, Pos, Last), Natural'Image (Pos), Natural'Image (Last)); Width := Natural'Value (Unbounded.Slice (Line, Pos + 1, Sep - 1)); Height := Natural'Value (Unbounded.Slice (Line, Sep + 1, Last - 1)); end if; end if; end if; end; end loop; Pipe.Close; Util.Processes.Wait (Proc); if Pipe.Get_Exit_Status /= 0 then Log.Error ("Command {0} exited with status {1}", Command, Integer'Image (Pipe.Get_Exit_Status)); end if; end; end Create_Thumbnail; -- Build a thumbnail for the image identified by the Id. procedure Build_Thumbnail (Service : in Image_Service; Id : in ADO.Identifier) is Storage_Service : constant AWA.Storages.Services.Storage_Service_Access := AWA.Storages.Modules.Get_Storage_Manager; Ctx : constant ASC.Service_Context_Access := ASC.Current; DB : ADO.Sessions.Master_Session := ASC.Get_Master_Session (Ctx); Img : AWA.Images.Models.Image_Ref; Thumb : AWA.Images.Models.Image_Ref; Target_File : AWA.Storages.Storage_File (AWA.Storages.TMP); Local_File : AWA.Storages.Storage_File (AWA.Storages.CACHE); Thumbnail : AWA.Storages.Models.Storage_Ref; Width : Natural := 64; Height : Natural := 64; begin Img.Load (DB, Id); declare Image_File : constant AWA.Storages.Models.Storage_Ref'Class := Img.Get_Storage; begin Storage_Service.Get_Local_File (From => Image_File.Get_Id, Into => Local_File); Storage_Service.Create_Local_File (Target_File); Service.Create_Thumbnail (AWA.Storages.Get_Path (Local_File), AWA.Storages.Get_Path (Target_File), Width, Height); Thumbnail.Set_Mime_Type ("image/jpeg"); Thumbnail.Set_Original (Image_File); Thumbnail.Set_Workspace (Image_File.Get_Workspace); Thumbnail.Set_Folder (Image_File.Get_Folder); Thumbnail.Set_Owner (Image_File.Get_Owner); Thumbnail.Set_Name (String '(Image_File.Get_Name)); Storage_Service.Save (Thumbnail, AWA.Storages.Get_Path (Target_File), AWA.Storages.Models.DATABASE); Thumb.Set_Width (64); Thumb.Set_Height (64); Thumb.Set_Owner (Image_File.Get_Owner); Thumb.Set_Folder (Image_File.Get_Folder); Thumb.Set_Storage (Thumbnail); Img.Set_Width (Width); Img.Set_Height (Height); Img.Set_Thumb_Width (64); Img.Set_Thumb_Height (64); Img.Set_Thumbnail (Thumbnail); Ctx.Start; Img.Save (DB); Thumb.Save (DB); Ctx.Commit; end; end Build_Thumbnail; -- Save the data object contained in the <b>Data</b> part element into the -- target storage represented by <b>Into</b>. procedure Create_Image (Service : in Image_Service; File : in AWA.Storages.Models.Storage_Ref'Class) is pragma Unreferenced (Service); Ctx : constant AWA.Services.Contexts.Service_Context_Access := AWA.Services.Contexts.Current; DB : ADO.Sessions.Master_Session := AWA.Services.Contexts.Get_Master_Session (Ctx); Img : AWA.Images.Models.Image_Ref; begin Ctx.Start; Img.Set_Width (0); Img.Set_Height (0); Img.Set_Thumb_Height (0); Img.Set_Thumb_Width (0); Img.Set_Storage (File); Img.Set_Folder (File.Get_Folder); Img.Set_Owner (File.Get_Owner); Img.Save (DB); Ctx.Commit; end Create_Image; -- Deletes the storage instance. procedure Delete_Image (Service : in Image_Service; File : in AWA.Storages.Models.Storage_Ref'Class) is begin null; end Delete_Image; -- ------------------------------ -- Scale the image dimension. -- ------------------------------ procedure Scale (Width : in Natural; Height : in Natural; To_Width : in out Natural; To_Height : in out Natural) is begin if To_Width = Natural'Last or To_Height = Natural'Last or (To_Width = 0 and To_Height = 0) then To_Width := Width; To_Height := Height; elsif To_Width = 0 then To_Width := (Width * To_Height) / Height; elsif To_Height = 0 then To_Height := (Height * To_Width) / Width; end if; end Scale; -- ------------------------------ -- Get the dimension represented by the string. The string has one of the following -- formats: -- original -> Width, Height := Natural'Last -- default -> Width, Height := 0 -- <width>x -> Width := <width>, Height := 0 -- x<height> -> Width := 0, Height := <height> -- <width>x<height> -> Width := <width>, Height := <height> -- ------------------------------ procedure Get_Sizes (Dimension : in String; Width : out Natural; Height : out Natural) is Pos : Natural; begin if Dimension = "original" then Width := Natural'Last; Height := Natural'Last; elsif Dimension = "default" then Width := 800; Height := 0; else Pos := Util.Strings.Index (Dimension, 'x'); if Pos > Dimension'First then Width := Natural'Value (Dimension (Dimension'First .. Pos - 1)); else Width := 0; end if; if Pos < Dimension'Last then Height := Natural'Value (Dimension (Pos + 1 .. Dimension'Last)); else Height := 0; end if; end if; end Get_Sizes; end AWA.Images.Services;
----------------------------------------------------------------------- -- awa-images-services -- Image service -- Copyright (C) 2012, 2013, 2015, 2016 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Processes; with Util.Beans.Objects; with Util.Log.Loggers; with Util.Streams.Pipes; with Util.Streams.Texts; with Util.Strings; with ADO.Sessions; with AWA.Images.Models; with AWA.Services.Contexts; with AWA.Storages.Services; with AWA.Storages.Modules; with Ada.Strings.Unbounded; with EL.Variables.Default; with EL.Contexts.Default; -- == Storage Service == -- The <tt>Storage_Service</tt> provides the operations to access and use the persisent storage. -- It controls the permissions that grant access to the service for users. -- -- Other modules can be notified of storage changes by registering a listener -- on the storage module. package body AWA.Images.Services is package ASC renames AWA.Services.Contexts; -- ------------------------------ -- Image Service -- ------------------------------ Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("AWA.Images.Services"); -- ------------------------------ -- Initializes the storage service. -- ------------------------------ overriding procedure Initialize (Service : in out Image_Service; Module : in AWA.Modules.Module'Class) is begin AWA.Modules.Module_Manager (Service).Initialize (Module); Service.Thumbnail_Command := Module.Get_Config (PARAM_THUMBNAIL_COMMAND); end Initialize; procedure Create_Thumbnail (Service : in Image_Service; Source : in String; Into : in String; Width : in out Natural; Height : in out Natural) is Ctx : EL.Contexts.Default.Default_Context; Variables : aliased EL.Variables.Default.Default_Variable_Mapper; Proc : Util.Processes.Process; Pipe : aliased Util.Streams.Pipes.Pipe_Stream; begin Variables.Bind ("src", Util.Beans.Objects.To_Object (Source)); Variables.Bind ("dst", Util.Beans.Objects.To_Object (Into)); Variables.Bind ("width", Util.Beans.Objects.To_Object (Width)); Variables.Bind ("height", Util.Beans.Objects.To_Object (Height)); Ctx.Set_Variable_Mapper (Variables'Unchecked_Access); declare Cmd : constant Util.Beans.Objects.Object := Service.Thumbnail_Command.Get_Value (Ctx); Command : constant String := Util.Beans.Objects.To_String (Cmd); Input : Util.Streams.Texts.Reader_Stream; begin Width := 0; Height := 0; Pipe.Open (Command, Util.Processes.READ_ALL); Input.Initialize (Pipe'Unchecked_Access, 1024); while not Input.Is_Eof loop declare use Ada.Strings; Line : Ada.Strings.Unbounded.Unbounded_String; Pos : Natural; Sep : Natural; Last : Natural; begin Input.Read_Line (Into => Line, Strip => False); exit when Ada.Strings.Unbounded.Length (Line) = 0; Log.Info ("Received: {0}", Line); -- The '-verbose' option of ImageMagick reports information about the original -- image. Extract the picture width and height. -- image.png PNG 120x282 120x282+0+0 8-bit DirectClass 34.4KB 0.000u 0:00.018 Pos := Ada.Strings.Unbounded.Index (Line, " "); if Pos > 0 and Width = 0 then Pos := Ada.Strings.Unbounded.Index (Line, " ", Pos + 1); if Pos > 0 then Sep := Ada.Strings.Unbounded.Index (Line, "x", Pos + 1); Last := Ada.Strings.Unbounded.Index (Line, "=", Pos + 1); if Sep > 0 and Sep < Last then Log.Info ("Dimension {0} - {1}..{2}", Ada.Strings.Unbounded.Slice (Line, Pos, Last), Natural'Image (Pos), Natural'Image (Last)); Width := Natural'Value (Unbounded.Slice (Line, Pos + 1, Sep - 1)); Height := Natural'Value (Unbounded.Slice (Line, Sep + 1, Last - 1)); end if; end if; end if; end; end loop; Pipe.Close; Util.Processes.Wait (Proc); if Pipe.Get_Exit_Status /= 0 then Log.Error ("Command {0} exited with status {1}", Command, Integer'Image (Pipe.Get_Exit_Status)); end if; end; end Create_Thumbnail; -- Build a thumbnail for the image identified by the Id. procedure Build_Thumbnail (Service : in Image_Service; Id : in ADO.Identifier) is Storage_Service : constant AWA.Storages.Services.Storage_Service_Access := AWA.Storages.Modules.Get_Storage_Manager; Ctx : constant ASC.Service_Context_Access := ASC.Current; DB : ADO.Sessions.Master_Session := ASC.Get_Master_Session (Ctx); Img : AWA.Images.Models.Image_Ref; Thumb : AWA.Images.Models.Image_Ref; Target_File : AWA.Storages.Storage_File (AWA.Storages.TMP); Local_File : AWA.Storages.Storage_File (AWA.Storages.CACHE); Thumbnail : AWA.Storages.Models.Storage_Ref; Width : Natural := 64; Height : Natural := 64; begin Img.Load (DB, Id); declare Image_File : constant AWA.Storages.Models.Storage_Ref'Class := Img.Get_Storage; begin Storage_Service.Get_Local_File (From => Image_File.Get_Id, Into => Local_File); Storage_Service.Create_Local_File (Target_File); Service.Create_Thumbnail (AWA.Storages.Get_Path (Local_File), AWA.Storages.Get_Path (Target_File), Width, Height); Thumbnail.Set_Mime_Type ("image/jpeg"); Thumbnail.Set_Original (Image_File); Thumbnail.Set_Workspace (Image_File.Get_Workspace); Thumbnail.Set_Folder (Image_File.Get_Folder); Thumbnail.Set_Owner (Image_File.Get_Owner); Thumbnail.Set_Name (String '(Image_File.Get_Name)); Storage_Service.Save (Thumbnail, AWA.Storages.Get_Path (Target_File), AWA.Storages.Models.DATABASE); Thumb.Set_Width (64); Thumb.Set_Height (64); Thumb.Set_Owner (Image_File.Get_Owner); Thumb.Set_Folder (Image_File.Get_Folder); Thumb.Set_Storage (Thumbnail); Img.Set_Width (Width); Img.Set_Height (Height); Img.Set_Thumb_Width (64); Img.Set_Thumb_Height (64); Img.Set_Thumbnail (Thumbnail); Ctx.Start; Img.Save (DB); Thumb.Save (DB); Ctx.Commit; end; end Build_Thumbnail; -- Save the data object contained in the <b>Data</b> part element into the -- target storage represented by <b>Into</b>. procedure Create_Image (Service : in Image_Service; File : in AWA.Storages.Models.Storage_Ref'Class) is pragma Unreferenced (Service); Ctx : constant AWA.Services.Contexts.Service_Context_Access := AWA.Services.Contexts.Current; DB : ADO.Sessions.Master_Session := AWA.Services.Contexts.Get_Master_Session (Ctx); Img : AWA.Images.Models.Image_Ref; begin Ctx.Start; Img.Set_Width (0); Img.Set_Height (0); Img.Set_Thumb_Height (0); Img.Set_Thumb_Width (0); Img.Set_Storage (File); Img.Set_Folder (File.Get_Folder); Img.Set_Owner (File.Get_Owner); Img.Save (DB); Ctx.Commit; end Create_Image; -- Deletes the storage instance. procedure Delete_Image (Service : in Image_Service; File : in AWA.Storages.Models.Storage_Ref'Class) is begin null; end Delete_Image; -- ------------------------------ -- Scale the image dimension. -- ------------------------------ procedure Scale (Width : in Natural; Height : in Natural; To_Width : in out Natural; To_Height : in out Natural) is begin if To_Width = Natural'Last or To_Height = Natural'Last or (To_Width = 0 and To_Height = 0) then To_Width := Width; To_Height := Height; elsif To_Width = 0 then To_Width := (Width * To_Height) / Height; elsif To_Height = 0 then To_Height := (Height * To_Width) / Width; end if; end Scale; -- ------------------------------ -- Get the dimension represented by the string. The string has one of the following -- formats: -- original -> Width, Height := Natural'Last -- default -> Width, Height := 0 -- <width>x -> Width := <width>, Height := 0 -- x<height> -> Width := 0, Height := <height> -- <width>x<height> -> Width := <width>, Height := <height> -- ------------------------------ procedure Get_Sizes (Dimension : in String; Width : out Natural; Height : out Natural) is Pos : Natural; begin if Dimension = "original" then Width := Natural'Last; Height := Natural'Last; elsif Dimension = "default" then Width := 800; Height := 0; else Pos := Util.Strings.Index (Dimension, 'x'); if Pos > Dimension'First then Width := Natural'Value (Dimension (Dimension'First .. Pos - 1)); else Width := 0; end if; if Pos < Dimension'Last then Height := Natural'Value (Dimension (Pos + 1 .. Dimension'Last)); else Height := 0; end if; end if; end Get_Sizes; end AWA.Images.Services;
Update initialization of input reader stream
Update initialization of input reader stream
Ada
apache-2.0
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
739c60a00fbc5345c2260ed574e27a3e5d9a3781
src/natools-string_slices.adb
src/natools-string_slices.adb
------------------------------------------------------------------------------ -- Copyright (c) 2013, 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. -- ------------------------------------------------------------------------------ package body Natools.String_Slices is use type String_Refs.Reference; ----------------------------- -- String_Range primitives -- ----------------------------- function Is_In (Point : Natural; Reference : String_Range) return Boolean is begin return Point >= Reference.First and Point < Reference.First + Reference.Length; end Is_In; function Is_Subrange (Sample, Reference : String_Range) return Boolean is begin return Sample.First >= Reference.First and then Sample.First + Sample.Length <= Reference.First + Reference.Length; end Is_Subrange; function Last (Self : String_Range) return Natural is begin return Self.First + Self.Length - 1; end Last; function To_Range (First : Positive; Last : Natural) return String_Range is begin if Last >= First then return (First => First, Length => Last - First + 1); else return (First => First, Length => 0); end if; end To_Range; function Get_Range (S : String) return String_Range is begin return (S'First, S'Length); end Get_Range; procedure Set_First (Self : in out String_Range; New_First : in Positive) is begin if New_First >= Self.First + Self.Length then Self.Length := 0; else Self.Length := Self.Length - (New_First - Self.First); end if; Self.First := New_First; end Set_First; procedure Set_Last (Self : in out String_Range; New_Last : in Natural) is begin if New_Last < Self.First then Self.Length := 0; else Self.Length := New_Last - Self.First + 1; end if; end Set_Last; procedure Set_Length (Self : in out String_Range; New_Length : in Natural) is begin Self.Length := New_Length; end Set_Length; function Image (Interval : String_Range) return String is First_Img : String := Integer'Image (Interval.First); begin pragma Assert (First_Img (First_Img'First) = ' '); if Interval.Length = 0 then return "empty at" & First_Img; end if; First_Img (First_Img'First) := '['; if Interval.Length = 1 then return First_Img & ']'; else return First_Img & ',' & Integer'Image (Last (Interval)) & ']'; end if; end Image; -------------------------- -- Conversion functions -- -------------------------- function To_Slice (S : String) return Slice is function Create return String; function Create return String is begin return S; end Create; begin return Slice'(Bounds => (S'First, S'Length), Ref => String_Refs.Create (Create'Access)); end To_Slice; function To_String (S : Slice) return String is begin if S.Ref.Is_Empty then return ""; else return S.Ref.Query.Data.all (S.Bounds.First .. Last (S.Bounds)); end if; end To_String; --------------- -- Accessors -- --------------- procedure Export (S : in Slice; Output : out String) is begin if not S.Ref.Is_Empty then Output := S.Ref.Query.Data.all (S.Bounds.First .. Last (S.Bounds)); end if; end Export; procedure Query (S : in Slice; Process : not null access procedure (Text : in String)) is begin if S.Bounds.Length = 0 or else S.Ref.Is_Empty then Process.all (""); else Process.all (S.Ref.Query.Data.all (S.Bounds.First .. Last (S.Bounds))); end if; end Query; function Get_Range (S : Slice) return String_Range is begin return S.Bounds; end Get_Range; function First (S : Slice) return Positive is begin return S.Bounds.First; end First; function Last (S : Slice) return Natural is begin return Last (S.Bounds); end Last; function Length (S : Slice) return Natural is begin return S.Bounds.Length; end Length; --------------- -- Extenders -- --------------- function Parent (S : Slice) return Slice is begin if S.Ref.Is_Empty then return Slice'(others => <>); else return Slice'(Bounds => Get_Range (S.Ref.Query.Data.all), Ref => S.Ref); end if; end Parent; function Extend (S : Slice; New_Range : in String_Range) return Slice is begin if not Is_Subrange (New_Range, Get_Range (S.Ref.Query.Data.all)) then raise Constraint_Error with "Extend slice beyond complete range"; end if; return Slice'(Bounds => New_Range, Ref => S.Ref); end Extend; function Extend (S : Slice; First : Positive; Last : Natural) return Slice is begin return Extend (S, To_Range (First, Last)); end Extend; procedure Extend (S : in out Slice; New_Range : in String_Range) is begin if not Is_Subrange (New_Range, Get_Range (S.Ref.Query.Data.all)) then raise Constraint_Error with "Extend slice beyond complete range"; end if; S.Bounds := New_Range; end Extend; procedure Extend (S : in out Slice; First : in Positive; Last : in Natural) is begin Extend (S, To_Range (First, Last)); end Extend; ----------------- -- Restrictors -- ----------------- function Subslice (S : Slice; New_Range : String_Range) return Slice is begin if S.Ref.Is_Empty then if New_Range.Length = 0 then return Slice'(Bounds => New_Range, Ref => <>); else raise Constraint_Error with "Subslice of null slice"; end if; end if; if not Is_Subrange (New_Range, S.Bounds) then raise Constraint_Error with "Subslice out of parent range"; end if; return Slice'(Bounds => New_Range, Ref => S.Ref); end Subslice; function Subslice (S : Slice; First : Positive; Last : Natural) return Slice is begin return Subslice (S, To_Range (First, Last)); end Subslice; procedure Restrict (S : in out Slice; New_Range : in String_Range) is begin if S.Ref.Is_Empty and New_Range.Length /= 0 then raise Constraint_Error with "Restrict of null slice"; end if; if not Is_Subrange (New_Range, S.Bounds) then raise Constraint_Error with "Restriction with not a subrange"; end if; S.Bounds := New_Range; end Restrict; procedure Restrict (S : in out Slice; First : in Positive; Last : in Natural) is begin Restrict (S, To_Range (First, Last)); end Restrict; procedure Set_First (S : in out Slice; New_First : in Positive) is begin if New_First < S.Bounds.First then raise Constraint_Error with "New_First out of slice range"; end if; Set_First (S.Bounds, New_First); end Set_First; procedure Set_Last (S : in out Slice; New_Last : in Natural) is begin if New_Last > Last (S.Bounds) then raise Constraint_Error with "New_Last out of slice range"; end if; Set_Last (S.Bounds, New_Last); end Set_Last; procedure Set_Length (S : in out Slice; New_Length : in Natural) is begin if New_Length > S.Bounds.Length then raise Constraint_Error with "New_Length out of slice range"; end if; S.Bounds.Length := New_Length; end Set_Length; ---------------------- -- Slice comparison -- ---------------------- function Is_Empty (S : Slice) return Boolean is begin return S.Bounds.Length = 0 or else S.Ref.Is_Empty; end Is_Empty; function Is_Null (S : Slice) return Boolean is begin return S.Ref.Is_Empty; end Is_Null; function Is_Related (Left, Right : Slice) return Boolean is begin return Left.Ref = Right.Ref; end Is_Related; function Is_Subslice (S, Reference : Slice) return Boolean is begin return S.Ref = Reference.Ref and then Is_Subrange (S.Bounds, Reference.Bounds); end Is_Subslice; ------------------ -- Constructors -- ------------------ function Duplicate (S : Slice) return Slice is function Factory return String; function Factory return String is begin return S.Ref.Query.Data.all; end Factory; begin if S.Bounds.Length = 0 or else S.Ref.Is_Empty then return Null_Slice; else return Slice'(Bounds => S.Bounds, Ref => String_Refs.Create (Factory'Access)); end if; end Duplicate; end Natools.String_Slices;
------------------------------------------------------------------------------ -- Copyright (c) 2013, 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. -- ------------------------------------------------------------------------------ package body Natools.String_Slices is use type String_Refs.Reference; ----------------------------- -- String_Range primitives -- ----------------------------- function Is_In (Point : Natural; Reference : String_Range) return Boolean is begin return Point >= Reference.First and Point < Reference.First + Reference.Length; end Is_In; function Is_Subrange (Sample, Reference : String_Range) return Boolean is begin return Sample.Length = 0 or else (Sample.First >= Reference.First and then Sample.First + Sample.Length <= Reference.First + Reference.Length); end Is_Subrange; function Last (Self : String_Range) return Natural is begin return Self.First + Self.Length - 1; end Last; function To_Range (First : Positive; Last : Natural) return String_Range is begin if Last >= First then return (First => First, Length => Last - First + 1); else return (First => First, Length => 0); end if; end To_Range; function Get_Range (S : String) return String_Range is begin return (S'First, S'Length); end Get_Range; procedure Set_First (Self : in out String_Range; New_First : in Positive) is begin if New_First >= Self.First + Self.Length then Self.Length := 0; else Self.Length := Self.Length - (New_First - Self.First); end if; Self.First := New_First; end Set_First; procedure Set_Last (Self : in out String_Range; New_Last : in Natural) is begin if New_Last < Self.First then Self.Length := 0; else Self.Length := New_Last - Self.First + 1; end if; end Set_Last; procedure Set_Length (Self : in out String_Range; New_Length : in Natural) is begin Self.Length := New_Length; end Set_Length; function Image (Interval : String_Range) return String is First_Img : String := Integer'Image (Interval.First); begin pragma Assert (First_Img (First_Img'First) = ' '); if Interval.Length = 0 then return "empty at" & First_Img; end if; First_Img (First_Img'First) := '['; if Interval.Length = 1 then return First_Img & ']'; else return First_Img & ',' & Integer'Image (Last (Interval)) & ']'; end if; end Image; -------------------------- -- Conversion functions -- -------------------------- function To_Slice (S : String) return Slice is function Create return String; function Create return String is begin return S; end Create; begin return Slice'(Bounds => (S'First, S'Length), Ref => String_Refs.Create (Create'Access)); end To_Slice; function To_String (S : Slice) return String is begin if S.Ref.Is_Empty then return ""; else return S.Ref.Query.Data.all (S.Bounds.First .. Last (S.Bounds)); end if; end To_String; --------------- -- Accessors -- --------------- procedure Export (S : in Slice; Output : out String) is begin if not S.Ref.Is_Empty then Output := S.Ref.Query.Data.all (S.Bounds.First .. Last (S.Bounds)); end if; end Export; procedure Query (S : in Slice; Process : not null access procedure (Text : in String)) is begin if S.Bounds.Length = 0 or else S.Ref.Is_Empty then Process.all (""); else Process.all (S.Ref.Query.Data.all (S.Bounds.First .. Last (S.Bounds))); end if; end Query; function Get_Range (S : Slice) return String_Range is begin return S.Bounds; end Get_Range; function First (S : Slice) return Positive is begin return S.Bounds.First; end First; function Last (S : Slice) return Natural is begin return Last (S.Bounds); end Last; function Length (S : Slice) return Natural is begin return S.Bounds.Length; end Length; --------------- -- Extenders -- --------------- function Parent (S : Slice) return Slice is begin if S.Ref.Is_Empty then return Slice'(others => <>); else return Slice'(Bounds => Get_Range (S.Ref.Query.Data.all), Ref => S.Ref); end if; end Parent; function Extend (S : Slice; New_Range : in String_Range) return Slice is begin if not Is_Subrange (New_Range, Get_Range (S.Ref.Query.Data.all)) then raise Constraint_Error with "Extend slice beyond complete range"; end if; return Slice'(Bounds => New_Range, Ref => S.Ref); end Extend; function Extend (S : Slice; First : Positive; Last : Natural) return Slice is begin return Extend (S, To_Range (First, Last)); end Extend; procedure Extend (S : in out Slice; New_Range : in String_Range) is begin if not Is_Subrange (New_Range, Get_Range (S.Ref.Query.Data.all)) then raise Constraint_Error with "Extend slice beyond complete range"; end if; S.Bounds := New_Range; end Extend; procedure Extend (S : in out Slice; First : in Positive; Last : in Natural) is begin Extend (S, To_Range (First, Last)); end Extend; ----------------- -- Restrictors -- ----------------- function Subslice (S : Slice; New_Range : String_Range) return Slice is begin if S.Ref.Is_Empty then if New_Range.Length = 0 then return Slice'(Bounds => New_Range, Ref => <>); else raise Constraint_Error with "Subslice of null slice"; end if; end if; if not Is_Subrange (New_Range, S.Bounds) then raise Constraint_Error with "Subslice out of parent range"; end if; return Slice'(Bounds => New_Range, Ref => S.Ref); end Subslice; function Subslice (S : Slice; First : Positive; Last : Natural) return Slice is begin return Subslice (S, To_Range (First, Last)); end Subslice; procedure Restrict (S : in out Slice; New_Range : in String_Range) is begin if S.Ref.Is_Empty and New_Range.Length /= 0 then raise Constraint_Error with "Restrict of null slice"; end if; if not Is_Subrange (New_Range, S.Bounds) then raise Constraint_Error with "Restriction with not a subrange"; end if; S.Bounds := New_Range; end Restrict; procedure Restrict (S : in out Slice; First : in Positive; Last : in Natural) is begin Restrict (S, To_Range (First, Last)); end Restrict; procedure Set_First (S : in out Slice; New_First : in Positive) is begin if New_First < S.Bounds.First then raise Constraint_Error with "New_First out of slice range"; end if; Set_First (S.Bounds, New_First); end Set_First; procedure Set_Last (S : in out Slice; New_Last : in Natural) is begin if New_Last > Last (S.Bounds) then raise Constraint_Error with "New_Last out of slice range"; end if; Set_Last (S.Bounds, New_Last); end Set_Last; procedure Set_Length (S : in out Slice; New_Length : in Natural) is begin if New_Length > S.Bounds.Length then raise Constraint_Error with "New_Length out of slice range"; end if; S.Bounds.Length := New_Length; end Set_Length; ---------------------- -- Slice comparison -- ---------------------- function Is_Empty (S : Slice) return Boolean is begin return S.Bounds.Length = 0 or else S.Ref.Is_Empty; end Is_Empty; function Is_Null (S : Slice) return Boolean is begin return S.Ref.Is_Empty; end Is_Null; function Is_Related (Left, Right : Slice) return Boolean is begin return Left.Ref = Right.Ref; end Is_Related; function Is_Subslice (S, Reference : Slice) return Boolean is begin return S.Ref = Reference.Ref and then Is_Subrange (S.Bounds, Reference.Bounds); end Is_Subslice; ------------------ -- Constructors -- ------------------ function Duplicate (S : Slice) return Slice is function Factory return String; function Factory return String is begin return S.Ref.Query.Data.all; end Factory; begin if S.Bounds.Length = 0 or else S.Ref.Is_Empty then return Null_Slice; else return Slice'(Bounds => S.Bounds, Ref => String_Refs.Create (Factory'Access)); end if; end Duplicate; end Natools.String_Slices;
fix Is_Subrange so that any empty range is a subrange of any range
string_slices: fix Is_Subrange so that any empty range is a subrange of any range
Ada
isc
faelys/natools
94a7d6e3c48b87e3f071ad33b4960347c8e35bde
tools/druss-commands-devices.adb
tools/druss-commands-devices.adb
----------------------------------------------------------------------- -- druss-commands-devices -- Print information about the devices -- 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 Util.Properties; with Bbox.API; with Druss.Gateways; package body Druss.Commands.Devices is -- ------------------------------ -- Execute the wifi 'status' command to print the Wifi current status. -- ------------------------------ procedure Do_List (Command : in Command_Type; Args : in Argument_List'Class; Selector : in Device_Selector_Type; Context : in out Context_Type) is pragma Unreferenced (Command, Args); procedure Box_Status (Gateway : in out Druss.Gateways.Gateway_Type); Console : constant Druss.Commands.Consoles.Console_Access := Context.Console; procedure Box_Status (Gateway : in out Druss.Gateways.Gateway_Type) is procedure Print_Device (Manager : in Util.Properties.Manager; Name : in String); procedure Print_Device (Manager : in Util.Properties.Manager; Name : in String) is Link : constant String := Manager.Get (Name & ".link", ""); Kind : constant String := Manager.Get (Name & ".devicetype", ""); begin case Selector is when DEVICE_ALL => null; when DEVICE_ACTIVE => if Manager.Get (Name & ".active", "") = "0" then return; end if; when DEVICE_INACTIVE => if Manager.Get (Name & ".active", "") = "1" then return; end if; end case; Console.Start_Row; Console.Print_Field (F_BBOX_IP_ADDR, Gateway.Ip); Console.Print_Field (F_IP_ADDR, Manager.Get (Name & ".ipaddress", "")); Console.Print_Field (F_ETHERNET, Manager.Get (Name & ".macaddress", "")); Console.Print_Field (F_HOSTNAME, Manager.Get (Name & ".hostname", "")); Console.Print_Field (F_ACTIVE, Manager.Get (Name & ".active", "")); Console.Print_Field (F_DEVTYPE, (if Kind = "STB" then "STB" else "")); if Link = "Ethernet" then Console.Print_Field (F_LINK, Link & " port " & Manager.Get (Name & ".ethernet.logicalport", "")); else Console.Print_Field (F_LINK, Link & " RSSI " & Manager.Get (Name & ".wireless.rssi0", "")); end if; Console.End_Row; end Print_Device; begin Gateway.Refresh; Bbox.API.Iterate (Gateway.Hosts, "hosts.list", Print_Device'Access); end Box_Status; begin Console.Start_Title; Console.Print_Title (F_BBOX_IP_ADDR, "Bbox IP", 16); Console.Print_Title (F_IP_ADDR, "Device IP", 16); Console.Print_Title (F_ETHERNET, "Ethernet", 20); Console.Print_Title (F_HOSTNAME, "Hostname", 28); Console.Print_Title (F_DEVTYPE, "Type", 6); -- Console.Print_Title (F_ACTIVE, "Active", 8); Console.Print_Title (F_LINK, "Link", 18); Console.End_Title; Druss.Gateways.Iterate (Context.Gateways, Gateways.ITER_ENABLE, Box_Status'Access); end Do_List; -- ------------------------------ -- Execute a status command to report information about the Bbox. -- ------------------------------ overriding procedure Execute (Command : in out Command_Type; Name : in String; Args : in Argument_List'Class; Context : in out Context_Type) is pragma Unreferenced (Name); begin if Args.Get_Count > 1 then Context.Console.Notice (N_USAGE, "Too many arguments to the command"); Druss.Commands.Driver.Usage (Args, Context); elsif Args.Get_Count = 0 then Command.Do_List (Args, DEVICE_ACTIVE, Context); elsif Args.Get_Argument (1) = "all" then Command.Do_List (Args, DEVICE_ALL, Context); elsif Args.Get_Argument (1) = "active" then Command.Do_List (Args, DEVICE_ACTIVE, Context); elsif Args.Get_Argument (1) = "inactive" then Command.Do_List (Args, DEVICE_INACTIVE, Context); else Context.Console.Notice (N_USAGE, "Invalid argument: " & Args.Get_Argument (1)); Druss.Commands.Driver.Usage (Args, Context); end if; end Execute; -- ------------------------------ -- Write the help associated with the command. -- ------------------------------ overriding procedure Help (Command : in out Command_Type; Context : in out Context_Type) is pragma Unreferenced (Command); Console : constant Druss.Commands.Consoles.Console_Access := Context.Console; begin Console.Notice (N_HELP, "devices: Print information about the devices"); Console.Notice (N_HELP, "Usage: devices [all | active | inactive]"); Console.Notice (N_HELP, ""); Console.Notice (N_HELP, " List the devices that are known by the Bbox."); Console.Notice (N_HELP, ""); Console.Notice (N_HELP, " all List all the devices"); Console.Notice (N_HELP, " active List the active devices (the default)"); Console.Notice (N_HELP, " inative List the inactive devices"); end Help; end Druss.Commands.Devices;
----------------------------------------------------------------------- -- druss-commands-devices -- Print information about the devices -- 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 Util.Properties; with Bbox.API; with Druss.Gateways; package body Druss.Commands.Devices is -- ------------------------------ -- Execute the wifi 'status' command to print the Wifi current status. -- ------------------------------ procedure Do_List (Command : in Command_Type; Args : in Argument_List'Class; Selector : in Device_Selector_Type; Context : in out Context_Type) is pragma Unreferenced (Command, Args); procedure Box_Status (Gateway : in out Druss.Gateways.Gateway_Type); Console : constant Druss.Commands.Consoles.Console_Access := Context.Console; procedure Box_Status (Gateway : in out Druss.Gateways.Gateway_Type) is procedure Print_Device (Manager : in Util.Properties.Manager; Name : in String); procedure Print_Device (Manager : in Util.Properties.Manager; Name : in String) is Link : constant String := Manager.Get (Name & ".link", ""); Kind : constant String := Manager.Get (Name & ".devicetype", ""); begin case Selector is when DEVICE_ALL => null; when DEVICE_ACTIVE => if Manager.Get (Name & ".active", "") = "0" then return; end if; when DEVICE_INACTIVE => if Manager.Get (Name & ".active", "") = "1" then return; end if; end case; Console.Start_Row; Console.Print_Field (F_BBOX_IP_ADDR, Gateway.Ip); Console.Print_Field (F_IP_ADDR, Manager.Get (Name & ".ipaddress", "")); Console.Print_Field (F_ETHERNET, Manager.Get (Name & ".macaddress", "")); Console.Print_Field (F_HOSTNAME, Manager.Get (Name & ".hostname", "")); -- Console.Print_Field (F_ACTIVE, Manager.Get (Name & ".active", "")); Console.Print_Field (F_DEVTYPE, (if Kind = "STB" then "STB" else "")); if Link = "Ethernet" then Console.Print_Field (F_LINK, Link & " port " & Manager.Get (Name & ".ethernet.logicalport", "")); else Console.Print_Field (F_LINK, Link & " RSSI " & Manager.Get (Name & ".wireless.rssi0", "")); end if; Console.End_Row; end Print_Device; begin Gateway.Refresh; Bbox.API.Iterate (Gateway.Hosts, "hosts.list", Print_Device'Access); end Box_Status; begin Console.Start_Title; Console.Print_Title (F_BBOX_IP_ADDR, "Bbox IP", 16); Console.Print_Title (F_IP_ADDR, "Device IP", 16); Console.Print_Title (F_ETHERNET, "Ethernet", 20); Console.Print_Title (F_HOSTNAME, "Hostname", 28); Console.Print_Title (F_DEVTYPE, "Type", 6); -- Console.Print_Title (F_ACTIVE, "Active", 8); Console.Print_Title (F_LINK, "Link", 18); Console.End_Title; Druss.Gateways.Iterate (Context.Gateways, Gateways.ITER_ENABLE, Box_Status'Access); end Do_List; -- ------------------------------ -- Execute a status command to report information about the Bbox. -- ------------------------------ overriding procedure Execute (Command : in out Command_Type; Name : in String; Args : in Argument_List'Class; Context : in out Context_Type) is pragma Unreferenced (Name); begin if Args.Get_Count > 1 then Context.Console.Notice (N_USAGE, "Too many arguments to the command"); Druss.Commands.Driver.Usage (Args, Context); elsif Args.Get_Count = 0 then Command.Do_List (Args, DEVICE_ACTIVE, Context); elsif Args.Get_Argument (1) = "all" then Command.Do_List (Args, DEVICE_ALL, Context); elsif Args.Get_Argument (1) = "active" then Command.Do_List (Args, DEVICE_ACTIVE, Context); elsif Args.Get_Argument (1) = "inactive" then Command.Do_List (Args, DEVICE_INACTIVE, Context); else Context.Console.Notice (N_USAGE, "Invalid argument: " & Args.Get_Argument (1)); Druss.Commands.Driver.Usage (Args, Context); end if; end Execute; -- ------------------------------ -- Write the help associated with the command. -- ------------------------------ overriding procedure Help (Command : in out Command_Type; Context : in out Context_Type) is pragma Unreferenced (Command); Console : constant Druss.Commands.Consoles.Console_Access := Context.Console; begin Console.Notice (N_HELP, "devices: Print information about the devices"); Console.Notice (N_HELP, "Usage: devices [all | active | inactive]"); Console.Notice (N_HELP, ""); Console.Notice (N_HELP, " List the devices that are known by the Bbox."); Console.Notice (N_HELP, ""); Console.Notice (N_HELP, " all List all the devices"); Console.Notice (N_HELP, " active List the active devices (the default)"); Console.Notice (N_HELP, " inative List the inactive devices"); end Help; end Druss.Commands.Devices;
Fix presentation of list of devices
Fix presentation of list of devices
Ada
apache-2.0
stcarrez/bbox-ada-api
92179e46c74fdd4810711197e91ce01006309b51
src/security.ads
src/security.ads
----------------------------------------------------------------------- -- security -- Security -- Copyright (C) 2010, 2011, 2012, 2015 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- -- == Introduction == -- The <tt>Security</tt> package provides a security framework that allows -- an application to use OpenID or OAuth security frameworks. This security -- framework was first developed within the Ada Server Faces project. -- This package defines abstractions that are close or similar to Java -- security package. -- -- The security framework uses the following abstractions: -- -- === Policy and policy manager === -- The <tt>Policy</tt> defines and implements the set of security rules that specify how to -- protect the system or resources. The <tt>Policy_Manager</tt> maintains the security policies. -- -- === Principal === -- The <tt>Principal</tt> is the entity that can be authenticated. A principal is obtained -- after successful authentication of a user or of a system through an authorization process. -- The OpenID or OAuth authentication processes generate such security principal. -- -- === Permission === -- The <tt>Permission</tt> represents an access to a system or application resource. -- A permission is checked by using the security policy manager. The policy manager uses a -- security controller to enforce the permission. -- -- === Security Context === -- The <tt>Security_Context</tt> holds the contextual information that the security controller -- can use to verify the permission. The security context is associated with a principal and -- a set of policy context. -- -- == Overview == -- An application will create a security policy manager and register one or several security -- policies (yellow). The framework defines a simple role based security policy and an URL -- security policy intended to provide security in web applications. The security policy manager -- reads some security policy configuration file which allows the security policies to configure -- and create the security controllers. These controllers will enforce the security according -- to the application security rules. All these components are built only once when -- an application starts. -- -- A user is authenticated through an authentication system which creates a <tt>Principal</tt> -- instance that identifies the user (green). The security framework provides two authentication -- systems: OpenID and OAuth. -- -- [images/ModelOverview.png] -- -- When a permission must be enforced, a security context is created and linked to the -- <tt>Principal</tt> instance (blue). Additional security policy context can be added depending -- on the application context. To check the permission, the security policy manager is called -- and it will ask a security controller to verify the permission. -- -- The framework allows an application to plug its own security policy, its own policy context, -- its own principal and authentication mechanism. -- -- @include security-permissions.ads -- -- == Principal == -- A principal is created by using either the [Security_Auth OpenID], -- the [Security_OAuth OAuth] or another authentication mechanism. The authentication produces -- an object that must implement the <tt>Principal</tt> interface. For example: -- -- P : Security.Auth.Principal_Access := Security.Auth.Create_Principal (Auth); -- -- or -- -- P : Security.OAuth.Clients.Access_Token_Access := Security.OAuth.Clients.Create_Access_Token -- -- The principal is then stored in a security context. -- -- @include security-contexts.ads -- -- [Security_Policies Security Policies] -- [Security_Auth OpenID] -- [Security_OAuth OAuth] -- package Security is pragma Preelaborate; -- ------------------------------ -- Principal -- ------------------------------ type Principal is limited interface; type Principal_Access is access all Principal'Class; -- Get the principal name. function Get_Name (From : in Principal) return String is abstract; end Security;
----------------------------------------------------------------------- -- security -- Security -- Copyright (C) 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. ----------------------------------------------------------------------- -- == Introduction == -- The <tt>Security</tt> package provides a security framework that allows -- an application to use OpenID or OAuth security frameworks. This security -- framework was first developed within the Ada Server Faces project. -- It was moved to a separate project so that it can easyly be used with AWS. -- This package defines abstractions that are close or similar to Java -- security package. -- -- The security framework uses the following abstractions: -- -- === Policy and policy manager === -- The <tt>Policy</tt> defines and implements the set of security rules that specify how to -- protect the system or resources. The <tt>Policy_Manager</tt> maintains the security policies. -- -- === Principal === -- The <tt>Principal</tt> is the entity that can be authenticated. A principal is obtained -- after successful authentication of a user or of a system through an authorization process. -- The OpenID or OAuth authentication processes generate such security principal. -- -- === Permission === -- The <tt>Permission</tt> represents an access to a system or application resource. -- A permission is checked by using the security policy manager. The policy manager uses a -- security controller to enforce the permission. -- -- === Security Context === -- The <tt>Security_Context</tt> holds the contextual information that the security controller -- can use to verify the permission. The security context is associated with a principal and -- a set of policy context. -- -- == Overview == -- An application will create a security policy manager and register one or several security -- policies (yellow). The framework defines a simple role based security policy and an URL -- security policy intended to provide security in web applications. The security policy manager -- reads some security policy configuration file which allows the security policies to configure -- and create the security controllers. These controllers will enforce the security according -- to the application security rules. All these components are built only once when -- an application starts. -- -- A user is authenticated through an authentication system which creates a <tt>Principal</tt> -- instance that identifies the user (green). The security framework provides two authentication -- systems: OpenID and OAuth 2.0 OpenID Connect. -- -- [images/ModelOverview.png] -- -- When a permission must be enforced, a security context is created and linked to the -- <tt>Principal</tt> instance (blue). Additional security policy context can be added depending -- on the application context. To check the permission, the security policy manager is called -- and it will ask a security controller to verify the permission. -- -- The framework allows an application to plug its own security policy, its own policy context, -- its own principal and authentication mechanism. -- -- @include security-permissions.ads -- -- == Principal == -- A principal is created by using either the [Security_Auth OpenID], -- the [Security_OAuth OAuth] or another authentication mechanism. The authentication produces -- an object that must implement the <tt>Principal</tt> interface. For example: -- -- P : Security.Auth.Principal_Access := Security.Auth.Create_Principal (Auth); -- -- or -- -- P : Security.OAuth.Clients.Access_Token_Access := Security.OAuth.Clients.Create_Access_Token -- -- The principal is then stored in a security context. -- -- @include security-contexts.ads -- -- [Security_Policies Security Policies] -- [Security_Auth OpenID] -- [Security_OAuth OAuth] -- package Security is pragma Preelaborate; -- ------------------------------ -- Principal -- ------------------------------ type Principal is limited interface; type Principal_Access is access all Principal'Class; -- Get the principal name. function Get_Name (From : in Principal) return String is abstract; end Security;
Add some documentation
Add some documentation
Ada
apache-2.0
stcarrez/ada-security
9a26a44c37b3ef261c54eb1c97a9cfb5976cf84d
src/security.ads
src/security.ads
----------------------------------------------------------------------- -- security -- Security -- 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. ----------------------------------------------------------------------- -- == Introduction == -- -- -- @include "security-contexts.ads" -- @include "security-controllers.ads" package Security is end Security;
----------------------------------------------------------------------- -- security -- Security -- 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. ----------------------------------------------------------------------- -- == Introduction == -- -- -- @include security-contexts.ads -- @include security-controllers.ads package Security is end Security;
Fix documentation links
Fix documentation links
Ada
apache-2.0
stcarrez/ada-security
c0d2e60ab0e63779d472ec5b56fa32a7b406d3c3
src/util-properties-bundles.ads
src/util-properties-bundles.ads
----------------------------------------------------------------------- -- properties-bundles -- Generic name/value property management -- Copyright (C) 2001, 2002, 2003, 2006, 2008, 2009, 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.Containers; with Ada.Finalization; with Ada.Containers.Hashed_Maps; with Util.Strings; with Util.Concurrent.Locks; package Util.Properties.Bundles is NO_BUNDLE : exception; NOT_WRITEABLE : exception; type Manager is new Util.Properties.Manager with private; -- ------------------------------ -- Bundle loader -- ------------------------------ -- The <b>Loader</b> provides facilities for loading property bundles -- and maintains a cache of bundles. The cache is thread-safe but the returned -- bundles are not thread-safe. type Loader is limited private; type Loader_Access is access all Loader; -- Initialize the bundle factory and specify where the property files are stored. procedure Initialize (Factory : in out Loader; Path : in String); -- Load the bundle with the given name and for the given locale name. procedure Load_Bundle (Factory : in out Loader; Name : in String; Locale : in String; Bundle : out Manager'Class); private procedure Add_Bundle (Self : in out Manager; Props : in Manager_Access); -- Add a bundle type Bundle_Manager_Access is access all Manager'Class; type Manager is new Util.Properties.Manager with null record; overriding procedure Initialize (Object : in out Manager); overriding procedure Adjust (Object : in out Manager); package Bundle_Map is new Ada.Containers.Hashed_Maps (Element_Type => Bundle_Manager_Access, Key_Type => Util.Strings.Name_Access, Hash => Util.Strings.Hash, Equivalent_Keys => Util.Strings.Equivalent_Keys); type Loader is new Ada.Finalization.Limited_Controlled with record Lock : Util.Concurrent.Locks.RW_Lock; Bundles : Bundle_Map.Map; Path : Unbounded_String; end record; -- Finalize the bundle loader and clear the cache overriding procedure Finalize (Factory : in out Loader); -- Clear the cache bundle procedure Clear_Cache (Factory : in out Loader); -- Find the bundle with the given name and for the given locale name. procedure Find_Bundle (Factory : in out Loader; Name : in String; Locale : in String; Bundle : out Manager'Class; Found : out Boolean); -- Load the bundle with the given name and for the given locale name. procedure Load_Bundle (Factory : in out Loader; Name : in String; Found : out Boolean); end Util.Properties.Bundles;
----------------------------------------------------------------------- -- properties-bundles -- Generic name/value property management -- Copyright (C) 2001, 2002, 2003, 2006, 2008, 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. ----------------------------------------------------------------------- with Ada.Containers; with Ada.Finalization; with Ada.Containers.Hashed_Maps; with Util.Strings; with Util.Concurrent.Locks; -- == Property bundles == -- Property bundles represent several property files that share some overriding rules and -- capabilities. Their introduction comes from Java resource bundles which allow to -- localize easily some configuration files or some message. When loading a property bundle -- a locale is defined to specify the target language and locale. If a specific property -- file for that locale exists, it is used first. Otherwise, the property bundle will use -- the default property file. -- -- A rule exists on the name of the specific property locale file: it must start with the -- bundle name followed by `_` and the name of the locale. The default property file must -- be the bundle name. For example, the bundle `dates` is associated with the following -- property files: -- -- dates.properties Default values (English locale) -- dates_fr.properties French locale -- dates_de.properties German locale -- dates_es.properties Spain locale -- -- Because a bundle can be associated with one or several property files, a specific loader is -- used. The loader instance must be declared and configured to indicate one or several search -- directories that contain property files. -- -- with Util.Properties.Bundles; -- ... -- Loader : Util.Properties.Bundles.Loader; -- Bundle : Util.Properties.Bundles.Manager; -- ... -- Util.Properties.Bundles.Initialize (Loader, "bundles;/usr/share/bundles"); -- Util.Properties.Bundles.Load_Bundle (Loader, "dates", "fr", Bundle); -- Ada.Text_IO.Put_Line (Bundle.Get ("util.month1.long"); -- -- In this example, the `util.month1.long` key is first search in the `dates_fr` French locale -- and if it is not found it is searched in the default locale. package Util.Properties.Bundles is NO_BUNDLE : exception; NOT_WRITEABLE : exception; type Manager is new Util.Properties.Manager with private; -- ------------------------------ -- Bundle loader -- ------------------------------ -- The <b>Loader</b> provides facilities for loading property bundles -- and maintains a cache of bundles. The cache is thread-safe but the returned -- bundles are not thread-safe. type Loader is limited private; type Loader_Access is access all Loader; -- Initialize the bundle factory and specify where the property files are stored. procedure Initialize (Factory : in out Loader; Path : in String); -- Load the bundle with the given name and for the given locale name. procedure Load_Bundle (Factory : in out Loader; Name : in String; Locale : in String; Bundle : out Manager'Class); private procedure Add_Bundle (Self : in out Manager; Props : in Manager_Access); -- Add a bundle type Bundle_Manager_Access is access all Manager'Class; type Manager is new Util.Properties.Manager with null record; overriding procedure Initialize (Object : in out Manager); overriding procedure Adjust (Object : in out Manager); package Bundle_Map is new Ada.Containers.Hashed_Maps (Element_Type => Bundle_Manager_Access, Key_Type => Util.Strings.Name_Access, Hash => Util.Strings.Hash, Equivalent_Keys => Util.Strings.Equivalent_Keys); type Loader is new Ada.Finalization.Limited_Controlled with record Lock : Util.Concurrent.Locks.RW_Lock; Bundles : Bundle_Map.Map; Path : Unbounded_String; end record; -- Finalize the bundle loader and clear the cache overriding procedure Finalize (Factory : in out Loader); -- Clear the cache bundle procedure Clear_Cache (Factory : in out Loader); -- Find the bundle with the given name and for the given locale name. procedure Find_Bundle (Factory : in out Loader; Name : in String; Locale : in String; Bundle : out Manager'Class; Found : out Boolean); -- Load the bundle with the given name and for the given locale name. procedure Load_Bundle (Factory : in out Loader; Name : in String; Found : out Boolean); end Util.Properties.Bundles;
Document the property bundles
Document the property bundles
Ada
apache-2.0
stcarrez/ada-util,stcarrez/ada-util
2670738a72f46fc88c6d34bc14ebb7d60317508f
src/orka/implementation/orka-resources-locations-directories.adb
src/orka/implementation/orka-resources-locations-directories.adb
-- Copyright (c) 2018 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.Directories; package body Orka.Resources.Locations.Directories is use Ada.Streams; function Open_File (File_Name : String) return Byte_Array_File is begin return Result : Byte_Array_File := (Ada.Finalization.Limited_Controlled with File => <>, Finalized => False) do Stream_IO.Open (Result.File, Stream_IO.In_File, File_Name); end return; end Open_File; overriding procedure Finalize (Object : in out Byte_Array_File) is begin if not Object.Finalized then if Stream_IO.Is_Open (Object.File) then Stream_IO.Close (Object.File); end if; Object.Finalized := True; end if; end Finalize; function Read_File (Object : in out Byte_Array_File) return Byte_Array_Access is File_Stream : Stream_IO.Stream_Access; File_Size : constant Integer := Integer (Stream_IO.Size (Object.File)); subtype File_Byte_Array is Byte_Array (1 .. Stream_Element_Offset (File_Size)); Raw_Contents : Byte_Array_Access := new File_Byte_Array; begin File_Stream := Stream_IO.Stream (Object.File); File_Byte_Array'Read (File_Stream, Raw_Contents.all); return Raw_Contents; exception when others => Free_Byte_Array (Raw_Contents); raise; end Read_File; ----------------------------------------------------------------------------- function Create_File (File_Name : String) return Byte_Array_File is begin return Result : Byte_Array_File := (Ada.Finalization.Limited_Controlled with File => <>, Finalized => False) do Stream_IO.Create (Result.File, Stream_IO.In_File, File_Name); end return; end Create_File; procedure Write_Data (Object : in out Byte_Array_File'Class; Data : Byte_Array_Access) is File_Stream : Stream_IO.Stream_Access; File_Size : constant Integer := Data'Length; subtype File_Byte_Array is Byte_Array (1 .. Stream_Element_Offset (File_Size)); begin File_Stream := Stream_IO.Stream (Object.File); File_Byte_Array'Write (File_Stream, Data.all); end Write_Data; ----------------------------------------------------------------------------- overriding function Exists (Object : Directory_Location; Path : String) return Boolean is Directory : String renames SU.To_String (Object.Full_Path); Full_Path : constant String := Directory & Path_Separator & Path; begin return Ada.Directories.Exists (Full_Path); end Exists; overriding function Read_Data (Object : Directory_Location; Path : String) return not null Byte_Array_Access is Directory : String renames SU.To_String (Object.Full_Path); Full_Path : constant String := Directory & Path_Separator & Path; use Ada.Directories; begin if not Exists (Full_Path) then raise Name_Error with "File '" & Full_Path & "' not found"; end if; if Kind (Full_Path) /= Ordinary_File then raise Name_Error with "Path '" & Full_Path & "' is not a regular file"; end if; declare File : constant Byte_Array_File'Class := Open_File (Full_Path); begin return File.Read_File; end; end Read_Data; procedure Write_Data (Object : Directory_Location; Path : String; Data : Byte_Array_Access) is Directory : String renames SU.To_String (Object.Full_Path); Full_Path : constant String := Directory & Path_Separator & Path; use Ada.Directories; begin if Exists (Full_Path) then raise Name_Error with "File '" & Full_Path & "' already exists"; end if; declare File : constant Byte_Array_File'Class := Create_File (Full_Path); begin File.Write_Data (Data); end; end Write_Data; function Create_Location (Path : String) return Location_Ptr is use Ada.Directories; Full_Path : constant String := Full_Name (Path); begin if not Exists (Full_Path) then raise Name_Error with "Directory '" & Full_Path & "' not found"; end if; if Kind (Full_Path) /= Directory then raise Name_Error with "Path '" & Full_Path & "' is not a directory"; end if; return new Directory_Location'(Full_Path => SU.To_Unbounded_String (Full_Path)); end Create_Location; end Orka.Resources.Locations.Directories;
-- Copyright (c) 2018 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.Directories; package body Orka.Resources.Locations.Directories is use Ada.Streams; function Open_File (File_Name : String) return Byte_Array_File is begin return Result : Byte_Array_File := (Ada.Finalization.Limited_Controlled with File => <>, Finalized => False) do Stream_IO.Open (Result.File, Stream_IO.In_File, File_Name); end return; end Open_File; overriding procedure Finalize (Object : in out Byte_Array_File) is begin if not Object.Finalized then if Stream_IO.Is_Open (Object.File) then Stream_IO.Close (Object.File); end if; Object.Finalized := True; end if; end Finalize; function Read_File (Object : in out Byte_Array_File) return Byte_Array_Access is File_Stream : Stream_IO.Stream_Access; File_Size : constant Integer := Integer (Stream_IO.Size (Object.File)); subtype File_Byte_Array is Byte_Array (1 .. Stream_Element_Offset (File_Size)); Raw_Contents : Byte_Array_Access := new File_Byte_Array; begin File_Stream := Stream_IO.Stream (Object.File); File_Byte_Array'Read (File_Stream, Raw_Contents.all); return Raw_Contents; exception when others => Free_Byte_Array (Raw_Contents); raise; end Read_File; ----------------------------------------------------------------------------- function Create_File (File_Name : String) return Byte_Array_File is begin return Result : Byte_Array_File := (Ada.Finalization.Limited_Controlled with File => <>, Finalized => False) do Stream_IO.Create (Result.File, Stream_IO.Out_File, File_Name); end return; end Create_File; procedure Write_Data (Object : in out Byte_Array_File'Class; Data : Byte_Array_Access) is File_Stream : Stream_IO.Stream_Access; File_Size : constant Integer := Data'Length; subtype File_Byte_Array is Byte_Array (1 .. Stream_Element_Offset (File_Size)); begin File_Stream := Stream_IO.Stream (Object.File); File_Byte_Array'Write (File_Stream, Data.all); end Write_Data; ----------------------------------------------------------------------------- overriding function Exists (Object : Directory_Location; Path : String) return Boolean is Directory : String renames SU.To_String (Object.Full_Path); Full_Path : constant String := Directory & Path_Separator & Path; begin return Ada.Directories.Exists (Full_Path); end Exists; overriding function Read_Data (Object : Directory_Location; Path : String) return not null Byte_Array_Access is Directory : String renames SU.To_String (Object.Full_Path); Full_Path : constant String := Directory & Path_Separator & Path; use Ada.Directories; begin if not Exists (Full_Path) then raise Name_Error with "File '" & Full_Path & "' not found"; end if; if Kind (Full_Path) /= Ordinary_File then raise Name_Error with "Path '" & Full_Path & "' is not a regular file"; end if; declare File : constant Byte_Array_File'Class := Open_File (Full_Path); begin return File.Read_File; end; end Read_Data; procedure Write_Data (Object : Directory_Location; Path : String; Data : Byte_Array_Access) is Directory : String renames SU.To_String (Object.Full_Path); Full_Path : constant String := Directory & Path_Separator & Path; use Ada.Directories; begin if Exists (Full_Path) then raise Name_Error with "File '" & Full_Path & "' already exists"; end if; declare File : constant Byte_Array_File'Class := Create_File (Full_Path); begin File.Write_Data (Data); end; end Write_Data; function Create_Location (Path : String) return Location_Ptr is use Ada.Directories; Full_Path : constant String := Full_Name (Path); begin if not Exists (Full_Path) then raise Name_Error with "Directory '" & Full_Path & "' not found"; end if; if Kind (Full_Path) /= Directory then raise Name_Error with "Path '" & Full_Path & "' is not a directory"; end if; return new Directory_Location'(Full_Path => SU.To_Unbounded_String (Full_Path)); end Create_Location; end Orka.Resources.Locations.Directories;
Fix writing to created file in procedure Write_Data
orka: Fix writing to created file in procedure Write_Data Signed-off-by: onox <[email protected]>
Ada
apache-2.0
onox/orka
ee7ff787c53e34992c9f865208cb3643ad3f52ae
src/security-oauth-servers.ads
src/security-oauth-servers.ads
----------------------------------------------------------------------- -- security-oauth-servers -- OAuth Server Authentication Support -- Copyright (C) 2016, 2017 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Strings.Unbounded; with Ada.Calendar; with Ada.Finalization; with Ada.Strings.Hash; with Ada.Containers.Indefinite_Hashed_Maps; with Util.Strings; with Security.Auth; with Security.Permissions; -- == OAuth Server == -- OAuth server side is provided by the <tt>Security.OAuth.Servers</tt> package. -- This package allows to implement the authorization framework described in RFC 6749 -- "The OAuth 2.0 Authorization Framework". -- -- The authorization method produces a <tt>Grant_Type</tt> object that contains the result -- of the grant (successful or denied). It is the responsibility of the caller to format -- the result in JSON/XML and return it to the client. -- -- Three important operations are defined for the OAuth 2.0 framework. They will be used -- in the following order: -- -- <tt>Authorize</tt> is used to obtain an authorization request. This operation is -- optional in the OAuth 2.0 framework since some authorization method directly return -- the access token. This operation is used by the "Authorization Code Grant" and the -- "Implicit Grant". -- -- <tt>Token</tt> is used to get the access token and optional refresh token. Each time it -- is called, a new token is generated. -- -- <tt>Authenticate</tt> is used for the API request to verify the access token -- and authenticate the API call. This operation can be called several times with the same -- token until the token is revoked or it has expired. -- -- Several grant types are supported. -- -- === Application Manager === -- The application manager maintains the repository of applications which are known by -- the server and which can request authorization. Each application is identified by -- a client identifier (represented by the <tt>client_id</tt> request parameter). -- The application defines the authorization methods which are allowed as well as -- the parameters to control and drive the authorization. This includes the redirection -- URI, the application secret, the expiration delay for the access token. -- -- The application manager is implemented by the application server and it must -- implement the <tt>Application_Manager</tt> interface with the <tt>Find_Application</tt> -- method. The <tt>Find_Application</tt> is one of the first call made during the -- authenticate and token generation phases. -- -- === Resource Owner Password Credentials Grant === -- The password grant is one of the easiest grant method to understand but it is also one -- of the less secure. In this grant method, the username and user password are passed in -- the request parameter together with the application client identifier. The realm verifies -- the username and password and when they are correct it generates the access token with -- an optional refresh token. -- -- Realm : Security.OAuth.Servers.Auth_Manager; -- Grant : Security.OAuth.Servers.Grant_Type; -- -- Realm.Token (Params, Grant); -- -- === Accessing Protected Resources === -- When accessing a protected resource, the API implementation will use the -- <tt>Authenticate</tt> operation to verify the access token and get a security principal. -- The security principal will identify the resource owner as well as the application -- that is doing the call. -- -- Realm : Security.OAuth.Servers.Auth_Manager; -- Grant : Security.OAuth.Servers.Grant_Type; -- Token : String := ...; -- -- Realm.Authenticate (Token, Grant); -- -- When a security principal is returned, the access token was validated and the -- request is granted for the application. -- package Security.OAuth.Servers is Invalid_Application : exception; type Application is new Security.OAuth.Application with private; -- Check if the application has the given permission. function Has_Permission (App : in Application; Permission : in Security.Permissions.Permission_Index) return Boolean; -- Define the status of the grant. type Grant_Status is (Invalid_Grant, Expired_Grant, Revoked_Grant, Stealed_Grant, Valid_Grant); -- Define the grant type. type Grant_Kind is (No_Grant, Access_Grant, Code_Grant, Implicit_Grant, Password_Grant, Credential_Grant, Extension_Grant); -- The <tt>Grant_Type</tt> holds the results of the authorization. -- When the grant is refused, the type holds information about the refusal. type Grant_Type is record -- The request grant type. Request : Grant_Kind := No_Grant; -- The response status. Status : Grant_Status := Invalid_Grant; -- When success, the token to return. Token : Ada.Strings.Unbounded.Unbounded_String; -- When success, the token expiration date. Expires : Ada.Calendar.Time; -- When success, the authentication principal. Auth : Security.Principal_Access; -- When error, the type of error to return. Error : Util.Strings.Name_Access; end record; type Application_Manager is limited interface; type Application_Manager_Access is access all Application_Manager'Class; -- 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. function Find_Application (Realm : in Application_Manager; Client_Id : in String) return Application'Class is abstract; type Realm_Manager is limited interface; type Realm_Manager_Access is access all Realm_Manager'Class; -- 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. procedure Authenticate (Realm : in out Realm_Manager; Token : in String; Auth : out Principal_Access; Cacheable : out Boolean) is abstract; -- 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. function Authorize (Realm : in Realm_Manager; App : in Application'Class; Scope : in String; Auth : in Principal_Access) return String is abstract; procedure Verify (Realm : in out Realm_Manager; Username : in String; Password : in String; Auth : out Principal_Access) is abstract; procedure Verify (Realm : in out Realm_Manager; Token : in String; Auth : out Principal_Access) is abstract; procedure Revoke (Realm : in out Realm_Manager; Auth : in Principal_Access) is abstract; type Auth_Manager is tagged limited private; type Auth_Manager_Access is access all Auth_Manager'Class; -- Set the auth private key. procedure Set_Private_Key (Manager : in out Auth_Manager; Key : in String); -- Set the application manager to use and and applications. procedure Set_Application_Manager (Manager : in out Auth_Manager; Repository : in Application_Manager_Access); -- Set the realm manager to authentify users. procedure Set_Realm_Manager (Manager : in out Auth_Manager; Realm : in Realm_Manager_Access); -- Authorize the access to the protected resource by the application and for the -- given principal. The resource owner has been verified and is represented by the -- <tt>Auth</tt> principal. Extract from the request parameters represented by -- <tt>Params</tt> the application client id, the scope and the expected response type. -- Handle the "Authorization Code Grant" and "Implicit Grant" defined in RFC 6749. procedure Authorize (Realm : in out Auth_Manager; Params : in Security.Auth.Parameters'Class; Auth : in Security.Principal_Access; Grant : out Grant_Type); procedure Token (Realm : in out Auth_Manager; Params : in Security.Auth.Parameters'Class; Grant : out Grant_Type); -- Make the access token from the authorization code that was created by the -- <tt>Authorize</tt> operation. Verify the client application, the redirect uri, the -- client secret and the validity of the authorization code. Extract from the -- authorization code the auth principal that was used for the grant and make the -- access token. procedure Token_From_Code (Realm : in out Auth_Manager; App : in Application'Class; Params : in Security.Auth.Parameters'Class; Grant : out Grant_Type); procedure Authorize_Code (Realm : in out Auth_Manager; App : in Application'Class; Params : in Security.Auth.Parameters'Class; Auth : in Security.Principal_Access; Grant : out Grant_Type); procedure Authorize_Token (Realm : in out Auth_Manager; App : in Application'Class; Params : in Security.Auth.Parameters'Class; Auth : in Security.Principal_Access; Grant : out Grant_Type); -- Make the access token from the resource owner password credentials. The username, -- password and scope are extracted from the request and they are verified through the -- <tt>Verify</tt> procedure to obtain an associated principal. When successful, the -- principal describes the authorization and it is used to forge the access token. -- This operation implements the RFC 6749: 4.3. Resource Owner Password Credentials Grant. procedure Token_From_Password (Realm : in out Auth_Manager; App : in Application'Class; Params : in Security.Auth.Parameters'Class; Grant : out Grant_Type); -- RFC 6749: 5. Issuing an Access Token procedure Create_Token (Realm : in Auth_Manager; Ident : in String; Grant : in out Grant_Type); -- Authenticate the access token and get a security principal that identifies the app/user. -- See RFC 6749, 7. Accessing Protected Resources. -- The access token is first searched in the cache. If it was found, it means the access -- token was already verified in the past, it is granted and associated with a principal. -- Otherwise, we have to verify the token signature first, then the expiration date and -- we extract from the token public part the auth identification. The <tt>Authenticate</tt> -- operation is then called to obtain the principal from the auth identification. -- When access token is invalid or authentification cannot be verified, a null principal -- is returned. The <tt>Grant</tt> data will hold the result of the grant with the reason -- of failures (if any). procedure Authenticate (Realm : in out Auth_Manager; Token : in String; Grant : out Grant_Type); procedure Revoke (Realm : in out Auth_Manager; Token : in String); private use Ada.Strings.Unbounded; function Format_Expire (Expire : in Ada.Calendar.Time) return String; type Application is new Security.OAuth.Application with record Expire_Timeout : Duration := 3600.0; Permissions : Security.Permissions.Permission_Index_Set := Security.Permissions.EMPTY_SET; end record; type Cache_Entry is record Expire : Ada.Calendar.Time; Auth : Principal_Access; end record; package Cache_Map is new Ada.Containers.Indefinite_Hashed_Maps (Key_Type => String, Element_Type => Cache_Entry, Hash => Ada.Strings.Hash, Equivalent_Keys => "=", "=" => "="); -- The access token cache is used to speed up the access token verification -- when a request to a protected resource is made. protected type Token_Cache is procedure Authenticate (Token : in String; Grant : in out Grant_Type); procedure Insert (Token : in String; Expire : in Ada.Calendar.Time; Principal : in Principal_Access); procedure Remove (Token : in String); procedure Timeout; private Entries : Cache_Map.Map; end Token_Cache; type Auth_Manager is new Ada.Finalization.Limited_Controlled with record -- The repository of applications. Repository : Application_Manager_Access; -- The realm for user authentication. Realm : Realm_Manager_Access; -- The server private key used by the HMAC signature. Private_Key : Ada.Strings.Unbounded.Unbounded_String; -- The access token cache. Cache : Token_Cache; -- The expiration time for the generated authorization code. Expire_Code : Duration := 300.0; end record; -- The <tt>Token_Validity</tt> record provides information about a token to find out -- the different components it is made of and verify its validity. The <tt>Validate</tt> -- procedure is in charge of checking the components and verifying the HMAC signature. -- The token has the following format: -- <expiration>.<client_id>.<auth-ident>.hmac(<public>.<private-key>) type Token_Validity is record Status : Grant_Status := Invalid_Grant; Ident_Start : Natural := 0; Ident_End : Natural := 0; Expire : Ada.Calendar.Time; end record; function Validate (Realm : in Auth_Manager; Client_Id : in String; Token : in String) return Token_Validity; end Security.OAuth.Servers;
----------------------------------------------------------------------- -- security-oauth-servers -- OAuth Server Authentication Support -- Copyright (C) 2016, 2017 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Strings.Unbounded; with Ada.Calendar; with Ada.Finalization; with Ada.Strings.Hash; with Ada.Containers.Indefinite_Hashed_Maps; with Util.Strings; with Security.Auth; with Security.Permissions; -- == OAuth Server == -- OAuth server side is provided by the <tt>Security.OAuth.Servers</tt> package. -- This package allows to implement the authorization framework described in RFC 6749 -- "The OAuth 2.0 Authorization Framework". -- -- The authorization method produces a <tt>Grant_Type</tt> object that contains the result -- of the grant (successful or denied). It is the responsibility of the caller to format -- the result in JSON/XML and return it to the client. -- -- Three important operations are defined for the OAuth 2.0 framework. They will be used -- in the following order: -- -- <tt>Authorize</tt> is used to obtain an authorization request. This operation is -- optional in the OAuth 2.0 framework since some authorization method directly return -- the access token. This operation is used by the "Authorization Code Grant" and the -- "Implicit Grant". -- -- <tt>Token</tt> is used to get the access token and optional refresh token. Each time it -- is called, a new token is generated. -- -- <tt>Authenticate</tt> is used for the API request to verify the access token -- and authenticate the API call. This operation can be called several times with the same -- token until the token is revoked or it has expired. -- -- Several grant types are supported. -- -- === Application Manager === -- The application manager maintains the repository of applications which are known by -- the server and which can request authorization. Each application is identified by -- a client identifier (represented by the <tt>client_id</tt> request parameter). -- The application defines the authorization methods which are allowed as well as -- the parameters to control and drive the authorization. This includes the redirection -- URI, the application secret, the expiration delay for the access token. -- -- The application manager is implemented by the application server and it must -- implement the <tt>Application_Manager</tt> interface with the <tt>Find_Application</tt> -- method. The <tt>Find_Application</tt> is one of the first call made during the -- authenticate and token generation phases. -- -- === Resource Owner Password Credentials Grant === -- The password grant is one of the easiest grant method to understand but it is also one -- of the less secure. In this grant method, the username and user password are passed in -- the request parameter together with the application client identifier. The realm verifies -- the username and password and when they are correct it generates the access token with -- an optional refresh token. -- -- Realm : Security.OAuth.Servers.Auth_Manager; -- Grant : Security.OAuth.Servers.Grant_Type; -- -- Realm.Token (Params, Grant); -- -- === Accessing Protected Resources === -- When accessing a protected resource, the API implementation will use the -- <tt>Authenticate</tt> operation to verify the access token and get a security principal. -- The security principal will identify the resource owner as well as the application -- that is doing the call. -- -- Realm : Security.OAuth.Servers.Auth_Manager; -- Grant : Security.OAuth.Servers.Grant_Type; -- Token : String := ...; -- -- Realm.Authenticate (Token, Grant); -- -- When a security principal is returned, the access token was validated and the -- request is granted for the application. -- package Security.OAuth.Servers is Invalid_Application : exception; type Application is new Security.OAuth.Application with private; -- Check if the application has the given permission. function Has_Permission (App : in Application; Permission : in Security.Permissions.Permission_Index) return Boolean; -- Define the status of the grant. type Grant_Status is (Invalid_Grant, Expired_Grant, Revoked_Grant, Stealed_Grant, Valid_Grant); -- Define the grant type. type Grant_Kind is (No_Grant, Access_Grant, Code_Grant, Implicit_Grant, Password_Grant, Credential_Grant, Extension_Grant); -- The <tt>Grant_Type</tt> holds the results of the authorization. -- When the grant is refused, the type holds information about the refusal. type Grant_Type is record -- The request grant type. Request : Grant_Kind := No_Grant; -- The response status. Status : Grant_Status := Invalid_Grant; -- When success, the token to return. Token : Ada.Strings.Unbounded.Unbounded_String; -- When success, the token expiration date. Expires : Ada.Calendar.Time; -- When success, the authentication principal. Auth : Security.Principal_Access; -- When error, the type of error to return. Error : Util.Strings.Name_Access; end record; type Application_Manager is limited interface; type Application_Manager_Access is access all Application_Manager'Class; -- 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. function Find_Application (Realm : in Application_Manager; Client_Id : in String) return Application'Class is abstract; type Realm_Manager is limited interface; type Realm_Manager_Access is access all Realm_Manager'Class; -- 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. procedure Authenticate (Realm : in out Realm_Manager; Token : in String; Auth : out Principal_Access; Cacheable : out Boolean) is abstract; -- 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. function Authorize (Realm : in Realm_Manager; App : in Application'Class; Scope : in String; Auth : in Principal_Access) return String is abstract; procedure Verify (Realm : in out Realm_Manager; Username : in String; Password : in String; Auth : out Principal_Access) is abstract; procedure Verify (Realm : in out Realm_Manager; Token : in String; Auth : out Principal_Access) is abstract; procedure Revoke (Realm : in out Realm_Manager; Auth : in Principal_Access) is abstract; type Auth_Manager is tagged limited private; type Auth_Manager_Access is access all Auth_Manager'Class; -- Set the auth private key. procedure Set_Private_Key (Manager : in out Auth_Manager; Key : in String); -- Set the application manager to use and and applications. procedure Set_Application_Manager (Manager : in out Auth_Manager; Repository : in Application_Manager_Access); -- Set the realm manager to authentify users. procedure Set_Realm_Manager (Manager : in out Auth_Manager; Realm : in Realm_Manager_Access); -- Authorize the access to the protected resource by the application and for the -- given principal. The resource owner has been verified and is represented by the -- <tt>Auth</tt> principal. Extract from the request parameters represented by -- <tt>Params</tt> the application client id, the scope and the expected response type. -- Handle the "Authorization Code Grant" and "Implicit Grant" defined in RFC 6749. procedure Authorize (Realm : in out Auth_Manager; Params : in Security.Auth.Parameters'Class; Auth : in Security.Principal_Access; Grant : out Grant_Type); -- The <tt>Token</tt> procedure is the main entry point to get the access token and -- refresh token. The request parameters are accessed through the <tt>Params</tt> interface. -- The operation looks at the "grant_type" parameter to identify the access method. -- It also looks at the "client_id" to find the application for which the access token -- is created. Upon successful authentication, the operation returns a grant. procedure Token (Realm : in out Auth_Manager; Params : in Security.Auth.Parameters'Class; Grant : out Grant_Type); -- Make the access token from the authorization code that was created by the -- <tt>Authorize</tt> operation. Verify the client application, the redirect uri, the -- client secret and the validity of the authorization code. Extract from the -- authorization code the auth principal that was used for the grant and make the -- access token. procedure Token_From_Code (Realm : in out Auth_Manager; App : in Application'Class; Params : in Security.Auth.Parameters'Class; Grant : out Grant_Type); procedure Authorize_Code (Realm : in out Auth_Manager; App : in Application'Class; Params : in Security.Auth.Parameters'Class; Auth : in Security.Principal_Access; Grant : out Grant_Type); procedure Authorize_Token (Realm : in out Auth_Manager; App : in Application'Class; Params : in Security.Auth.Parameters'Class; Auth : in Security.Principal_Access; Grant : out Grant_Type); -- Make the access token from the resource owner password credentials. The username, -- password and scope are extracted from the request and they are verified through the -- <tt>Verify</tt> procedure to obtain an associated principal. When successful, the -- principal describes the authorization and it is used to forge the access token. -- This operation implements the RFC 6749: 4.3. Resource Owner Password Credentials Grant. procedure Token_From_Password (Realm : in out Auth_Manager; App : in Application'Class; Params : in Security.Auth.Parameters'Class; Grant : out Grant_Type); -- Forge an access token. The access token is signed by an HMAC-SHA1 signature. -- The returned token is formed as follows: -- <expiration>.<ident>.HMAC-SHA1(<private-key>, <expiration>.<ident>) -- See also RFC 6749: 5. Issuing an Access Token procedure Create_Token (Realm : in Auth_Manager; Ident : in String; Grant : in out Grant_Type); -- Authenticate the access token and get a security principal that identifies the app/user. -- See RFC 6749, 7. Accessing Protected Resources. -- The access token is first searched in the cache. If it was found, it means the access -- token was already verified in the past, it is granted and associated with a principal. -- Otherwise, we have to verify the token signature first, then the expiration date and -- we extract from the token public part the auth identification. The <tt>Authenticate</tt> -- operation is then called to obtain the principal from the auth identification. -- When access token is invalid or authentification cannot be verified, a null principal -- is returned. The <tt>Grant</tt> data will hold the result of the grant with the reason -- of failures (if any). procedure Authenticate (Realm : in out Auth_Manager; Token : in String; Grant : out Grant_Type); procedure Revoke (Realm : in out Auth_Manager; Token : in String); private use Ada.Strings.Unbounded; function Format_Expire (Expire : in Ada.Calendar.Time) return String; type Application is new Security.OAuth.Application with record Expire_Timeout : Duration := 3600.0; Permissions : Security.Permissions.Permission_Index_Set := Security.Permissions.EMPTY_SET; end record; type Cache_Entry is record Expire : Ada.Calendar.Time; Auth : Principal_Access; end record; package Cache_Map is new Ada.Containers.Indefinite_Hashed_Maps (Key_Type => String, Element_Type => Cache_Entry, Hash => Ada.Strings.Hash, Equivalent_Keys => "=", "=" => "="); -- The access token cache is used to speed up the access token verification -- when a request to a protected resource is made. protected type Token_Cache is procedure Authenticate (Token : in String; Grant : in out Grant_Type); procedure Insert (Token : in String; Expire : in Ada.Calendar.Time; Principal : in Principal_Access); procedure Remove (Token : in String); procedure Timeout; private Entries : Cache_Map.Map; end Token_Cache; type Auth_Manager is new Ada.Finalization.Limited_Controlled with record -- The repository of applications. Repository : Application_Manager_Access; -- The realm for user authentication. Realm : Realm_Manager_Access; -- The server private key used by the HMAC signature. Private_Key : Ada.Strings.Unbounded.Unbounded_String; -- The access token cache. Cache : Token_Cache; -- The expiration time for the generated authorization code. Expire_Code : Duration := 300.0; end record; -- The <tt>Token_Validity</tt> record provides information about a token to find out -- the different components it is made of and verify its validity. The <tt>Validate</tt> -- procedure is in charge of checking the components and verifying the HMAC signature. -- The token has the following format: -- <expiration>.<client_id>.<auth-ident>.hmac(<public>.<private-key>) type Token_Validity is record Status : Grant_Status := Invalid_Grant; Ident_Start : Natural := 0; Ident_End : Natural := 0; Expire : Ada.Calendar.Time; end record; function Validate (Realm : in Auth_Manager; Client_Id : in String; Token : in String) return Token_Validity; end Security.OAuth.Servers;
Add some documentation
Add some documentation
Ada
apache-2.0
stcarrez/ada-security
4edfd86c86835f7bb2c350b8f335357a042ac80a
samples/encrypt.adb
samples/encrypt.adb
----------------------------------------------------------------------- -- encrypt -- Encrypt file using Util.Streams.AES -- Copyright (C) 2019, 2021 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Text_IO; with Ada.Command_Line; with Ada.Streams.Stream_IO; with Util.Streams.Files; with Util.Streams.AES; with Util.Encoders.AES; with Util.Encoders.KDF.PBKDF2_HMAC_SHA256; procedure Encrypt is use Util.Encoders.KDF; procedure Crypt_File (Source : in String; Destination : in String; Password : in String); procedure Crypt_File (Source : in String; Destination : in String; Password : in String) is In_Stream : aliased Util.Streams.Files.File_Stream; Out_Stream : aliased Util.Streams.Files.File_Stream; Cipher : aliased Util.Streams.AES.Encoding_Stream; Password_Key : constant Util.Encoders.Secret_Key := Util.Encoders.Create (Password); Salt : constant Util.Encoders.Secret_Key := Util.Encoders.Create ("fake-salt"); Key : Util.Encoders.Secret_Key (Length => Util.Encoders.AES.AES_256_Length); begin -- Generate a derived key from the password. PBKDF2_HMAC_SHA256 (Password => Password_Key, Salt => Salt, Counter => 20000, Result => Key); -- Setup file -> input and cipher -> output file streams. In_Stream.Open (Ada.Streams.Stream_IO.In_File, Source); Out_Stream.Create (Mode => Ada.Streams.Stream_IO.Out_File, Name => Destination); Cipher.Produces (Output => Out_Stream'Access, Size => 32768); Cipher.Set_Key (Secret => Key, Mode => Util.Encoders.AES.ECB); -- Copy input to output through the cipher. Util.Streams.Copy (From => In_Stream, Into => Cipher); end Crypt_File; begin if Ada.Command_Line.Argument_Count /= 3 then Ada.Text_IO.Put_Line ("Usage: encrypt source password destination"); return; end if; Crypt_File (Source => Ada.Command_Line.Argument (1), Destination => Ada.Command_Line.Argument (3), Password => Ada.Command_Line.Argument (2)); end Encrypt;
----------------------------------------------------------------------- -- encrypt -- Encrypt file using Util.Streams.AES -- Copyright (C) 2019, 2021, 2022 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Text_IO; with Ada.Command_Line; with Ada.Streams.Stream_IO; with Util.Streams.Files; with Util.Streams.AES; with Util.Encoders.AES; with Util.Encoders.KDF.PBKDF2_HMAC_SHA256; procedure Encrypt is use Util.Encoders.KDF; procedure Crypt_File (Source : in String; Destination : in String; Password : in String); procedure Crypt_File (Source : in String; Destination : in String; Password : in String) is In_Stream : aliased Util.Streams.Files.File_Stream; Out_Stream : aliased Util.Streams.Files.File_Stream; Cipher : aliased Util.Streams.AES.Encoding_Stream; Password_Key : constant Util.Encoders.Secret_Key := Util.Encoders.Create (Password); Salt : constant Util.Encoders.Secret_Key := Util.Encoders.Create ("fake-salt"); Key : Util.Encoders.Secret_Key (Length => Util.Encoders.AES.AES_256_Length); begin -- Generate a derived key from the password. PBKDF2_HMAC_SHA256 (Password => Password_Key, Salt => Salt, Counter => 20000, Result => Key); -- Setup file -> input and cipher -> output file streams. In_Stream.Open (Ada.Streams.Stream_IO.In_File, Source); Out_Stream.Create (Mode => Ada.Streams.Stream_IO.Out_File, Name => Destination); Cipher.Produces (Output => Out_Stream'Unchecked_Access, Size => 32768); Cipher.Set_Key (Secret => Key, Mode => Util.Encoders.AES.ECB); -- Copy input to output through the cipher. Util.Streams.Copy (From => In_Stream, Into => Cipher); end Crypt_File; begin if Ada.Command_Line.Argument_Count /= 3 then Ada.Text_IO.Put_Line ("Usage: encrypt source password destination"); return; end if; Crypt_File (Source => Ada.Command_Line.Argument (1), Destination => Ada.Command_Line.Argument (3), Password => Ada.Command_Line.Argument (2)); end Encrypt;
Fix the example
Fix the example
Ada
apache-2.0
stcarrez/ada-util,stcarrez/ada-util
0e4f99ad5f280a71c01fd08622828d6c30a03b6f
src/util-beans-objects-readers.adb
src/util-beans-objects-readers.adb
----------------------------------------------------------------------- -- util-beans-objects-readers -- Datasets -- 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. ----------------------------------------------------------------------- package body Util.Beans.Objects.Readers is use type Maps.Map_Bean_Access; use type Vectors.Vector_Bean_Access; -- Start a document. overriding procedure Start_Document (Handler : in out Reader) is begin Object_Stack.Clear (Handler.Context); Object_Stack.Push (Handler.Context); Object_Stack.Current (Handler.Context).Map := new Maps.Map_Bean; end Start_Document; -- ----------------------- -- Start a new object associated with the given name. This is called when -- the '{' is reached. The reader must be updated so that the next -- <b>Set_Member</b> procedure will associate the name/value pair on the -- new object. -- ----------------------- overriding procedure Start_Object (Handler : in out Reader; Name : in String; Logger : in out Util.Log.Logging'Class) is pragma Unreferenced (Logger); Current : constant Object_Context_Access := Object_Stack.Current (Handler.Context); Next : Object_Context_Access; begin Object_Stack.Push (Handler.Context); Next := Object_Stack.Current (Handler.Context); Next.Map := new Maps.Map_Bean; if Current.Map /= null then Current.Map.Include (Name, To_Object (Next.List, DYNAMIC)); else Current.List.Append (To_Object (Next.List, DYNAMIC)); end if; end Start_Object; -- ----------------------- -- Finish an object associated with the given name. The reader must be -- updated to be associated with the previous object. -- ----------------------- overriding procedure Finish_Object (Handler : in out Reader; Name : in String; Logger : in out Util.Log.Logging'Class) is pragma Unreferenced (Name, Logger); begin Object_Stack.Pop (Handler.Context); end Finish_Object; overriding procedure Start_Array (Handler : in out Reader; Name : in String; Logger : in out Util.Log.Logging'Class) is pragma Unreferenced (Logger); Current : constant Object_Context_Access := Object_Stack.Current (Handler.Context); Next : Object_Context_Access; begin Object_Stack.Push (Handler.Context); Next := Object_Stack.Current (Handler.Context); Next.List := new Vectors.Vector_Bean; if Current.Map /= null then Current.Map.Include (Name, To_Object (Next.List, DYNAMIC)); else Current.List.Append (To_Object (Next.List, DYNAMIC)); end if; end Start_Array; overriding procedure Finish_Array (Handler : in out Reader; Name : in String; Count : in Natural; Logger : in out Util.Log.Logging'Class) is pragma Unreferenced (Name, Count, Logger); begin Object_Stack.Pop (Handler.Context); end Finish_Array; -- ----------------------- -- Set the name/value pair on the current object. For each active mapping, -- find whether a rule matches our name and execute it. -- ----------------------- overriding procedure Set_Member (Handler : in out Reader; Name : in String; Value : in Util.Beans.Objects.Object; Logger : in out Util.Log.Logging'Class; Attribute : in Boolean := False) is pragma Unreferenced (Logger, Attribute); Current : constant Object_Context_Access := Object_Stack.Current (Handler.Context); begin if Current.Map /= null then Current.Map.Set_Value (Name, Value); else Current.List.Append (Value); end if; end Set_Member; end Util.Beans.Objects.Readers;
----------------------------------------------------------------------- -- util-beans-objects-readers -- Datasets -- 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. ----------------------------------------------------------------------- package body Util.Beans.Objects.Readers is use type Maps.Map_Bean_Access; use type Vectors.Vector_Bean_Access; -- Start a document. overriding procedure Start_Document (Handler : in out Reader) is begin Object_Stack.Clear (Handler.Context); Object_Stack.Push (Handler.Context); Object_Stack.Current (Handler.Context).Map := new Maps.Map_Bean; Handler.Root := To_Object (Object_Stack.Current (Handler.Context).Map, DYNAMIC); end Start_Document; -- ----------------------- -- Start a new object associated with the given name. This is called when -- the '{' is reached. The reader must be updated so that the next -- <b>Set_Member</b> procedure will associate the name/value pair on the -- new object. -- ----------------------- overriding procedure Start_Object (Handler : in out Reader; Name : in String; Logger : in out Util.Log.Logging'Class) is pragma Unreferenced (Logger); Current : constant Object_Context_Access := Object_Stack.Current (Handler.Context); Next : Object_Context_Access; begin Object_Stack.Push (Handler.Context); Next := Object_Stack.Current (Handler.Context); Next.Map := new Maps.Map_Bean; if Current.Map /= null then Current.Map.Include (Name, To_Object (Next.Map, DYNAMIC)); else Current.List.Append (To_Object (Next.Map, DYNAMIC)); end if; end Start_Object; -- ----------------------- -- Finish an object associated with the given name. The reader must be -- updated to be associated with the previous object. -- ----------------------- overriding procedure Finish_Object (Handler : in out Reader; Name : in String; Logger : in out Util.Log.Logging'Class) is pragma Unreferenced (Name, Logger); begin Object_Stack.Pop (Handler.Context); end Finish_Object; overriding procedure Start_Array (Handler : in out Reader; Name : in String; Logger : in out Util.Log.Logging'Class) is pragma Unreferenced (Logger); Current : constant Object_Context_Access := Object_Stack.Current (Handler.Context); Next : Object_Context_Access; begin Object_Stack.Push (Handler.Context); Next := Object_Stack.Current (Handler.Context); Next.List := new Vectors.Vector_Bean; if Current.Map /= null then Current.Map.Include (Name, To_Object (Next.List, DYNAMIC)); else Current.List.Append (To_Object (Next.List, DYNAMIC)); end if; end Start_Array; overriding procedure Finish_Array (Handler : in out Reader; Name : in String; Count : in Natural; Logger : in out Util.Log.Logging'Class) is pragma Unreferenced (Name, Count, Logger); begin Object_Stack.Pop (Handler.Context); end Finish_Array; -- ----------------------- -- Set the name/value pair on the current object. For each active mapping, -- find whether a rule matches our name and execute it. -- ----------------------- overriding procedure Set_Member (Handler : in out Reader; Name : in String; Value : in Util.Beans.Objects.Object; Logger : in out Util.Log.Logging'Class; Attribute : in Boolean := False) is pragma Unreferenced (Logger, Attribute); Current : constant Object_Context_Access := Object_Stack.Current (Handler.Context); begin if Current.Map /= null then Current.Map.Set_Value (Name, Value); else Current.List.Append (Value); end if; end Set_Member; -- ----------------------- -- Get the root object. -- ----------------------- function Get_Root (Handler : in Reader) return Object is begin return Handler.Root; end Get_Root; end Util.Beans.Objects.Readers;
Implement the Get_Root function Setup the Root object when the document is created Fix creation of objects
Implement the Get_Root function Setup the Root object when the document is created Fix creation of objects
Ada
apache-2.0
stcarrez/ada-util,stcarrez/ada-util
88d548833c5060e71db82d55af490ea5c2d7bf2b
src/gl/implementation/gl-transforms.adb
src/gl/implementation/gl-transforms.adb
-- Copyright (c) 2015 onox <[email protected]> -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. with Ada.Numerics.Generic_Elementary_Functions; package body GL.Transforms is package Elementary_Functions is new Ada.Numerics.Generic_Elementary_Functions (Single); function To_Radians (Angle : Single) return Single is begin return Angle * Ada.Numerics.Pi / 180.0; end To_Radians; procedure Translate (Matrix : in out Matrix4; Offset : Vector3) is begin Matrix (W, X) := Matrix (X, X) * Offset (X) + Matrix (Y, X) * Offset (Y) + Matrix (Z, X) * Offset (Z) + Matrix (W, X); Matrix (W, Y) := Matrix (X, Y) * Offset (X) + Matrix (Y, Y) * Offset (Y) + Matrix (Z, Y) * Offset (Z) + Matrix (W, Y); Matrix (W, Z) := Matrix (X, Z) * Offset (X) + Matrix (Y, Z) * Offset (Y) + Matrix (Z, Z) * Offset (Z) + Matrix (W, Z); Matrix (W, W) := Matrix (X, W) * Offset (X) + Matrix (Y, W) * Offset (Y) + Matrix (Z, W) * Offset (Z) + Matrix (W, W); end Translate; procedure Rotate_X (Matrix : in out Matrix4; Angle : Single) is CA : constant Single := Elementary_Functions.Cos (To_Radians (Angle), 2.0 * Ada.Numerics.Pi); SA : constant Single := Elementary_Functions.Sin (To_Radians (Angle), 2.0 * Ada.Numerics.Pi); Result_Matrix : Matrix4 := Matrix; begin Result_Matrix (Y, X) := CA * Matrix (Y, X) + SA * Matrix (Z, X); Result_Matrix (Y, Y) := CA * Matrix (Y, Y) + SA * Matrix (Z, Y); Result_Matrix (Y, Z) := CA * Matrix (Y, Z) + SA * Matrix (Z, Z); Result_Matrix (Y, W) := CA * Matrix (Y, W) + SA * Matrix (Z, W); Result_Matrix (Z, X) := -SA * Matrix (Y, X) + CA * Matrix (Z, X); Result_Matrix (Z, Y) := -SA * Matrix (Y, Y) + CA * Matrix (Z, Y); Result_Matrix (Z, Z) := -SA * Matrix (Y, Z) + CA * Matrix (Z, Z); Result_Matrix (Z, W) := -SA * Matrix (Y, W) + CA * Matrix (Z, W); Matrix := Result_Matrix; end Rotate_X; procedure Rotate_Y (Matrix : in out Matrix4; Angle : Single) is CA : constant Single := Elementary_Functions.Cos (To_Radians (Angle), 2.0 * Ada.Numerics.Pi); SA : constant Single := Elementary_Functions.Sin (To_Radians (Angle), 2.0 * Ada.Numerics.Pi); Result_Matrix : Matrix4 := Matrix; begin Result_Matrix (X, X) := CA * Matrix (X, X) - SA * Matrix (Z, X); Result_Matrix (X, Y) := CA * Matrix (X, Y) - SA * Matrix (Z, Y); Result_Matrix (X, Z) := CA * Matrix (X, Z) - SA * Matrix (Z, Z); Result_Matrix (X, W) := CA * Matrix (X, W) - SA * Matrix (Z, W); Result_Matrix (Z, X) := SA * Matrix (X, X) + CA * Matrix (Z, X); Result_Matrix (Z, Y) := SA * Matrix (X, Y) + CA * Matrix (Z, Y); Result_Matrix (Z, Z) := SA * Matrix (X, Z) + CA * Matrix (Z, Z); Result_Matrix (Z, W) := SA * Matrix (X, W) + CA * Matrix (Z, W); Matrix := Result_Matrix; end Rotate_Y; procedure Rotate_Z (Matrix : in out Matrix4; Angle : Single) is CA : constant Single := Elementary_Functions.Cos (To_Radians (Angle), 2.0 * Ada.Numerics.Pi); SA : constant Single := Elementary_Functions.Sin (To_Radians (Angle), 2.0 * Ada.Numerics.Pi); Result_Matrix : Matrix4 := Matrix; begin Result_Matrix (X, X) := CA * Matrix (X, X) + SA * Matrix (Y, X); Result_Matrix (X, Y) := CA * Matrix (X, Y) + SA * Matrix (Y, Y); Result_Matrix (X, Z) := CA * Matrix (X, Z) + SA * Matrix (Y, Z); Result_Matrix (X, W) := CA * Matrix (X, W) + SA * Matrix (Y, W); Result_Matrix (Y, X) := -SA * Matrix (X, X) + CA * Matrix (Y, X); Result_Matrix (Y, Y) := -SA * Matrix (X, Y) + CA * Matrix (Y, Y); Result_Matrix (Y, Z) := -SA * Matrix (X, Z) + CA * Matrix (Y, Z); Result_Matrix (Y, W) := -SA * Matrix (X, W) + CA * Matrix (Y, W); Matrix := Result_Matrix; end Rotate_Z; procedure Rotate (Matrix : in out Matrix4; Direction : in Vector3; Angle : in Single) is CA : constant Single := Elementary_Functions.Cos (To_Radians (Angle), 2.0 * Ada.Numerics.Pi); SA : constant Single := Elementary_Functions.Sin (To_Radians (Angle), 2.0 * Ada.Numerics.Pi); MCA : constant Single := 1.0 - CA; MCARXY : constant Single := MCA * Direction (X) * Direction (Y); MCARXZ : constant Single := MCA * Direction (X) * Direction (Z); MCARYZ : constant Single := MCA * Direction (Y) * Direction (Z); RXSA : constant Single := Direction (X) * SA; RYSA : constant Single := Direction (Y) * SA; RZSA : constant Single := Direction (Z) * SA; R11 : constant Single := CA + MCA * Direction (X)**2; R12 : constant Single := MCARXY + RZSA; R13 : constant Single := MCARXZ - RYSA; R21 : constant Single := MCARXY - RZSA; R22 : constant Single := CA + MCA * Direction (Y)**2; R23 : constant Single := MCARYZ + RXSA; R31 : constant Single := MCARXZ + RYSA; R32 : constant Single := MCARYZ - RXSA; R33 : constant Single := CA + MCA * Direction (Z)**2; Result_Matrix : Matrix4 := Matrix; begin Result_Matrix (X, X) := R11 * Matrix (X, X) + R12 * Matrix (Y, X) + R13 * Matrix (Z, X); Result_Matrix (X, Y) := R11 * Matrix (X, Y) + R12 * Matrix (Y, Y) + R13 * Matrix (Z, X); Result_Matrix (X, Z) := R11 * Matrix (X, Z) + R12 * Matrix (Y, Z) + R13 * Matrix (Z, X); Result_Matrix (X, W) := R11 * Matrix (X, W) + R12 * Matrix (Y, W) + R13 * Matrix (Z, X); Result_Matrix (Y, X) := R21 * Matrix (X, X) + R22 * Matrix (Y, X) + R23 * Matrix (Z, X); Result_Matrix (Y, Y) := R21 * Matrix (X, Y) + R22 * Matrix (Y, Y) + R23 * Matrix (Z, X); Result_Matrix (Y, Z) := R21 * Matrix (X, Z) + R22 * Matrix (Y, Z) + R23 * Matrix (Z, X); Result_Matrix (Y, W) := R21 * Matrix (X, W) + R22 * Matrix (Y, W) + R23 * Matrix (Z, X); Result_Matrix (Z, X) := R31 * Matrix (X, X) + R32 * Matrix (Y, X) + R33 * Matrix (Z, X); Result_Matrix (Z, Y) := R31 * Matrix (X, Y) + R32 * Matrix (Y, Y) + R33 * Matrix (Z, X); Result_Matrix (Z, Z) := R31 * Matrix (X, Z) + R32 * Matrix (Y, Z) + R33 * Matrix (Z, X); Result_Matrix (Z, W) := R31 * Matrix (X, W) + R32 * Matrix (Y, W) + R33 * Matrix (Z, X); Matrix := Result_Matrix; end Rotate; procedure Scale (Matrix : in out Matrix4; Factors : Vector3) is begin Matrix (X, X) := Matrix (X, X) * Factors (X); Matrix (X, Y) := Matrix (X, Y) * Factors (X); Matrix (X, Z) := Matrix (X, Y) * Factors (X); Matrix (X, W) := Matrix (X, W) * Factors (X); Matrix (Y, X) := Matrix (Y, X) * Factors (Y); Matrix (Y, Y) := Matrix (Y, Y) * Factors (Y); Matrix (Y, Z) := Matrix (Y, Z) * Factors (Y); Matrix (Y, W) := Matrix (Y, W) * Factors (Y); Matrix (Z, X) := Matrix (Z, X) * Factors (Z); Matrix (Z, Y) := Matrix (Z, Y) * Factors (Z); Matrix (Z, Z) := Matrix (Z, Z) * Factors (Z); Matrix (Z, W) := Matrix (Z, W) * Factors (Z); end Scale; procedure Scale (Matrix : in out Matrix4; Factor : Single) is Factors : constant Vector3 := (Factor, Factor, Factor); begin Scale (Matrix, Factors); end Scale; function Perspective (FOV, Aspect, Z_Near, Z_Far : Single) return Matrix4 is F : constant Single := 1.0 / Elementary_Functions.Tan (FOV / 2.0, 360.0); Matrix : Matrix4 := Identity4; begin Matrix (X, X) := F / Aspect; Matrix (Y, Y) := F; Matrix (Z, Z) := (Z_Near + Z_Far) / (Z_Near - Z_Far); Matrix (W, Z) := (2.0 * Z_Near * Z_Far) / (Z_Near - Z_Far); Matrix (Z, W) := Single (-1.0); Matrix (W, W) := Single (0.0); return Matrix; end Perspective; end GL.Transforms;
-- Copyright (c) 2015 onox <[email protected]> -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. with Ada.Numerics.Generic_Elementary_Functions; package body GL.Transforms is package Elementary_Functions is new Ada.Numerics.Generic_Elementary_Functions (Single); function To_Radians (Angle : Single) return Single is begin return Angle * Ada.Numerics.Pi / 180.0; end To_Radians; procedure Translate (Matrix : in out Matrix4; Offset : Vector3) is begin Matrix (W, X) := Matrix (X, X) * Offset (X) + Matrix (Y, X) * Offset (Y) + Matrix (Z, X) * Offset (Z) + Matrix (W, X); Matrix (W, Y) := Matrix (X, Y) * Offset (X) + Matrix (Y, Y) * Offset (Y) + Matrix (Z, Y) * Offset (Z) + Matrix (W, Y); Matrix (W, Z) := Matrix (X, Z) * Offset (X) + Matrix (Y, Z) * Offset (Y) + Matrix (Z, Z) * Offset (Z) + Matrix (W, Z); Matrix (W, W) := Matrix (X, W) * Offset (X) + Matrix (Y, W) * Offset (Y) + Matrix (Z, W) * Offset (Z) + Matrix (W, W); end Translate; procedure Rotate_X (Matrix : in out Matrix4; Angle : Single) is CA : constant Single := Elementary_Functions.Cos (To_Radians (Angle), 2.0 * Ada.Numerics.Pi); SA : constant Single := Elementary_Functions.Sin (To_Radians (Angle), 2.0 * Ada.Numerics.Pi); Result_Matrix : Matrix4 := Matrix; begin Result_Matrix (Y, X) := CA * Matrix (Y, X) + SA * Matrix (Z, X); Result_Matrix (Y, Y) := CA * Matrix (Y, Y) + SA * Matrix (Z, Y); Result_Matrix (Y, Z) := CA * Matrix (Y, Z) + SA * Matrix (Z, Z); Result_Matrix (Y, W) := CA * Matrix (Y, W) + SA * Matrix (Z, W); Result_Matrix (Z, X) := -SA * Matrix (Y, X) + CA * Matrix (Z, X); Result_Matrix (Z, Y) := -SA * Matrix (Y, Y) + CA * Matrix (Z, Y); Result_Matrix (Z, Z) := -SA * Matrix (Y, Z) + CA * Matrix (Z, Z); Result_Matrix (Z, W) := -SA * Matrix (Y, W) + CA * Matrix (Z, W); Matrix := Result_Matrix; end Rotate_X; procedure Rotate_Y (Matrix : in out Matrix4; Angle : Single) is CA : constant Single := Elementary_Functions.Cos (To_Radians (Angle), 2.0 * Ada.Numerics.Pi); SA : constant Single := Elementary_Functions.Sin (To_Radians (Angle), 2.0 * Ada.Numerics.Pi); Result_Matrix : Matrix4 := Matrix; begin Result_Matrix (X, X) := CA * Matrix (X, X) - SA * Matrix (Z, X); Result_Matrix (X, Y) := CA * Matrix (X, Y) - SA * Matrix (Z, Y); Result_Matrix (X, Z) := CA * Matrix (X, Z) - SA * Matrix (Z, Z); Result_Matrix (X, W) := CA * Matrix (X, W) - SA * Matrix (Z, W); Result_Matrix (Z, X) := SA * Matrix (X, X) + CA * Matrix (Z, X); Result_Matrix (Z, Y) := SA * Matrix (X, Y) + CA * Matrix (Z, Y); Result_Matrix (Z, Z) := SA * Matrix (X, Z) + CA * Matrix (Z, Z); Result_Matrix (Z, W) := SA * Matrix (X, W) + CA * Matrix (Z, W); Matrix := Result_Matrix; end Rotate_Y; procedure Rotate_Z (Matrix : in out Matrix4; Angle : Single) is CA : constant Single := Elementary_Functions.Cos (To_Radians (Angle), 2.0 * Ada.Numerics.Pi); SA : constant Single := Elementary_Functions.Sin (To_Radians (Angle), 2.0 * Ada.Numerics.Pi); Result_Matrix : Matrix4 := Matrix; begin Result_Matrix (X, X) := CA * Matrix (X, X) + SA * Matrix (Y, X); Result_Matrix (X, Y) := CA * Matrix (X, Y) + SA * Matrix (Y, Y); Result_Matrix (X, Z) := CA * Matrix (X, Z) + SA * Matrix (Y, Z); Result_Matrix (X, W) := CA * Matrix (X, W) + SA * Matrix (Y, W); Result_Matrix (Y, X) := -SA * Matrix (X, X) + CA * Matrix (Y, X); Result_Matrix (Y, Y) := -SA * Matrix (X, Y) + CA * Matrix (Y, Y); Result_Matrix (Y, Z) := -SA * Matrix (X, Z) + CA * Matrix (Y, Z); Result_Matrix (Y, W) := -SA * Matrix (X, W) + CA * Matrix (Y, W); Matrix := Result_Matrix; end Rotate_Z; procedure Rotate (Matrix : in out Matrix4; Direction : in Vector3; Angle : in Single) is CA : constant Single := Elementary_Functions.Cos (To_Radians (Angle), 2.0 * Ada.Numerics.Pi); SA : constant Single := Elementary_Functions.Sin (To_Radians (Angle), 2.0 * Ada.Numerics.Pi); MCA : constant Single := 1.0 - CA; MCARXY : constant Single := MCA * Direction (X) * Direction (Y); MCARXZ : constant Single := MCA * Direction (X) * Direction (Z); MCARYZ : constant Single := MCA * Direction (Y) * Direction (Z); RXSA : constant Single := Direction (X) * SA; RYSA : constant Single := Direction (Y) * SA; RZSA : constant Single := Direction (Z) * SA; R11 : constant Single := CA + MCA * Direction (X)**2; R12 : constant Single := MCARXY + RZSA; R13 : constant Single := MCARXZ - RYSA; R21 : constant Single := MCARXY - RZSA; R22 : constant Single := CA + MCA * Direction (Y)**2; R23 : constant Single := MCARYZ + RXSA; R31 : constant Single := MCARXZ + RYSA; R32 : constant Single := MCARYZ - RXSA; R33 : constant Single := CA + MCA * Direction (Z)**2; Result_Matrix : Matrix4 := Matrix; begin Result_Matrix (X, X) := R11 * Matrix (X, X) + R12 * Matrix (Y, X) + R13 * Matrix (Z, X); Result_Matrix (X, Y) := R11 * Matrix (X, Y) + R12 * Matrix (Y, Y) + R13 * Matrix (Z, X); Result_Matrix (X, Z) := R11 * Matrix (X, Z) + R12 * Matrix (Y, Z) + R13 * Matrix (Z, X); Result_Matrix (X, W) := R11 * Matrix (X, W) + R12 * Matrix (Y, W) + R13 * Matrix (Z, X); Result_Matrix (Y, X) := R21 * Matrix (X, X) + R22 * Matrix (Y, X) + R23 * Matrix (Z, X); Result_Matrix (Y, Y) := R21 * Matrix (X, Y) + R22 * Matrix (Y, Y) + R23 * Matrix (Z, X); Result_Matrix (Y, Z) := R21 * Matrix (X, Z) + R22 * Matrix (Y, Z) + R23 * Matrix (Z, X); Result_Matrix (Y, W) := R21 * Matrix (X, W) + R22 * Matrix (Y, W) + R23 * Matrix (Z, X); Result_Matrix (Z, X) := R31 * Matrix (X, X) + R32 * Matrix (Y, X) + R33 * Matrix (Z, X); Result_Matrix (Z, Y) := R31 * Matrix (X, Y) + R32 * Matrix (Y, Y) + R33 * Matrix (Z, X); Result_Matrix (Z, Z) := R31 * Matrix (X, Z) + R32 * Matrix (Y, Z) + R33 * Matrix (Z, X); Result_Matrix (Z, W) := R31 * Matrix (X, W) + R32 * Matrix (Y, W) + R33 * Matrix (Z, X); Matrix := Result_Matrix; end Rotate; procedure Scale (Matrix : in out Matrix4; Factors : Vector3) is begin Matrix (X, X) := Matrix (X, X) * Factors (X); Matrix (X, Y) := Matrix (X, Y) * Factors (X); Matrix (X, Z) := Matrix (X, Z) * Factors (X); Matrix (X, W) := Matrix (X, W) * Factors (X); Matrix (Y, X) := Matrix (Y, X) * Factors (Y); Matrix (Y, Y) := Matrix (Y, Y) * Factors (Y); Matrix (Y, Z) := Matrix (Y, Z) * Factors (Y); Matrix (Y, W) := Matrix (Y, W) * Factors (Y); Matrix (Z, X) := Matrix (Z, X) * Factors (Z); Matrix (Z, Y) := Matrix (Z, Y) * Factors (Z); Matrix (Z, Z) := Matrix (Z, Z) * Factors (Z); Matrix (Z, W) := Matrix (Z, W) * Factors (Z); end Scale; procedure Scale (Matrix : in out Matrix4; Factor : Single) is Factors : constant Vector3 := (Factor, Factor, Factor); begin Scale (Matrix, Factors); end Scale; function Perspective (FOV, Aspect, Z_Near, Z_Far : Single) return Matrix4 is F : constant Single := 1.0 / Elementary_Functions.Tan (FOV / 2.0, 360.0); Matrix : Matrix4 := Identity4; begin Matrix (X, X) := F / Aspect; Matrix (Y, Y) := F; Matrix (Z, Z) := (Z_Near + Z_Far) / (Z_Near - Z_Far); Matrix (W, Z) := (2.0 * Z_Near * Z_Far) / (Z_Near - Z_Far); Matrix (Z, W) := Single (-1.0); Matrix (W, W) := Single (0.0); return Matrix; end Perspective; end GL.Transforms;
Fix typo in Scale procedure
gl: Fix typo in Scale procedure Signed-off-by: onox <[email protected]>
Ada
apache-2.0
onox/orka
0f86da8adb76e771d2062d9e4f8910547144ccb4
regtests/util-files-tests.adb
regtests/util-files-tests.adb
----------------------------------------------------------------------- -- files.tests -- Unit tests for files -- Copyright (C) 2009, 2010, 2011, 2012, 2013, 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. ----------------------------------------------------------------------- with System; with Ada.Directories; with Util.Systems.Constants; with Util.Test_Caller; package body Util.Files.Tests is use Util.Tests; package Caller is new Util.Test_Caller (Test, "Files"); procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is begin Caller.Add_Test (Suite, "Test Util.Files.Read_File", Test_Read_File'Access); Caller.Add_Test (Suite, "Test Util.Files.Read_File (missing)", Test_Read_File_Missing'Access); Caller.Add_Test (Suite, "Test Util.Files.Read_File (truncate)", Test_Read_File'Access); Caller.Add_Test (Suite, "Test Util.Files.Write_File", Test_Write_File'Access); Caller.Add_Test (Suite, "Test Util.Files.Iterate_Path", Test_Iterate_Path'Access); Caller.Add_Test (Suite, "Test Util.Files.Find_File_Path", Test_Find_File_Path'Access); Caller.Add_Test (Suite, "Test Util.Files.Compose_Path", Test_Compose_Path'Access); Caller.Add_Test (Suite, "Test Util.Files.Get_Relative_Path", Test_Get_Relative_Path'Access); Caller.Add_Test (Suite, "Test Util.Files.Delete_Tree", Test_Delete_Tree'Access); end Add_Tests; -- ------------------------------ -- Test reading a file into a string -- Reads this ada source file and checks we have read it correctly -- ------------------------------ procedure Test_Read_File (T : in out Test) is Result : Unbounded_String; begin Read_File (Path => "regtests/util-files-tests.adb", Into => Result); T.Assert (Index (Result, "Util.Files.Tests") > 0, "Content returned by Read_File is not correct"); T.Assert (Index (Result, "end Util.Files.Tests;") > 0, "Content returned by Read_File is not correct"); end Test_Read_File; procedure Test_Read_File_Missing (T : in out Test) is Result : Unbounded_String; pragma Unreferenced (Result); begin Read_File (Path => "regtests/files-test--util.adb", Into => Result); T.Assert (False, "No exception raised"); exception when others => null; end Test_Read_File_Missing; procedure Test_Read_File_Truncate (T : in out Test) is Result : Unbounded_String; begin Read_File (Path => "regtests/util-files-tests.adb", Into => Result, Max_Size => 50); Assert_Equals (T, Length (Result), 50, "Read_File did not truncate correctly"); T.Assert (Index (Result, "Apache License") > 0, "Content returned by Read_File is not correct"); end Test_Read_File_Truncate; -- ------------------------------ -- Check writing a file -- ------------------------------ procedure Test_Write_File (T : in out Test) is Path : constant String := Util.Tests.Get_Test_Path ("test-write.txt"); Content : constant String := "Testing Util.Files.Write_File" & ASCII.LF; Result : Unbounded_String; begin Write_File (Path => Path, Content => Content); Read_File (Path => Path, Into => Result); Assert_Equals (T, To_String (Result), Content, "Invalid content written or read"); end Test_Write_File; -- ------------------------------ -- Check Find_File_Path -- ------------------------------ procedure Test_Find_File_Path (T : in out Test) is Dir : constant String := Util.Tests.Get_Path ("regtests"); Paths : constant String := ".;" & Dir; begin declare P : constant String := Util.Files.Find_File_Path ("test.properties", Paths); begin Assert_Equals (T, Dir & "/test.properties", P, "Invalid path returned"); end; Assert_Equals (T, "blablabla.properties", Util.Files.Find_File_Path ("blablabla.properties", Paths)); end Test_Find_File_Path; -- ------------------------------ -- Check Iterate_Path -- ------------------------------ procedure Test_Iterate_Path (T : in out Test) is procedure Check_Path (Dir : in String; Done : out Boolean); Last : Unbounded_String; procedure Check_Path (Dir : in String; Done : out Boolean) is begin if Dir = "a" or Dir = "bc" or Dir = "de" then Done := False; else Done := True; end if; Last := To_Unbounded_String (Dir); end Check_Path; begin Iterate_Path ("a;bc;de;f", Check_Path'Access); Assert_Equals (T, "f", Last, "Invalid last path"); Iterate_Path ("de;bc;de;b", Check_Path'Access); Assert_Equals (T, "b", Last, "Invalid last path"); Iterate_Path ("de;bc;de;a", Check_Path'Access, Ada.Strings.Backward); Assert_Equals (T, "de", Last, "Invalid last path"); end Test_Iterate_Path; -- ------------------------------ -- Test the Compose_Path operation -- ------------------------------ procedure Test_Compose_Path (T : in out Test) is begin Assert_Equals (T, "src/sys/processes/os-none", Compose_Path ("src;regtests;src/sys/processes", "os-none"), "Invalid path composition"); Assert_Equals (T, "regtests/bundles", Compose_Path ("src;regtests", "bundles"), "Invalid path composition"); if Ada.Directories.Exists ("/usr/bin") then Assert_Equals (T, "/usr/bin;/usr/local/bin;/usr/bin", Compose_Path ("/usr;/usr/local;/usr", "bin"), "Invalid path composition"); end if; end Test_Compose_Path; -- ------------------------------ -- Test the Get_Relative_Path operation. -- ------------------------------ procedure Test_Get_Relative_Path (T : in out Test) is begin Assert_Equals (T, "../util", Get_Relative_Path ("/home/john/src/asf", "/home/john/src/util"), "Invalid relative path"); Assert_Equals (T, "../util", Get_Relative_Path ("/home/john/src/asf/", "/home/john/src/util"), "Invalid relative path"); Assert_Equals (T, "../util/b", Get_Relative_Path ("/home/john/src/asf", "/home/john/src/util/b"), "Invalid relative path"); Assert_Equals (T, "../as", Get_Relative_Path ("/home/john/src/asf", "/home/john/src/as"), "Invalid relative path"); Assert_Equals (T, "../../", Get_Relative_Path ("/home/john/src/asf", "/home/john"), "Invalid relative path"); Assert_Equals (T, "/usr/share/admin", Get_Relative_Path ("/home/john/src/asf", "/usr/share/admin"), "Invalid absolute path"); Assert_Equals (T, "/home/john", Get_Relative_Path ("home/john/src/asf", "/home/john"), "Invalid relative path"); Assert_Equals (T, "e", Get_Relative_Path ("/home/john/src/asf", "/home/john/src/asf/e"), "Invalid relative path"); Assert_Equals (T, ".", Get_Relative_Path ("/home/john/src/asf", "/home/john/src/asf/"), "Invalid relative path"); end Test_Get_Relative_Path; function Sys_Symlink (Target : in System.Address; Link : in System.Address) return Integer with Import => True, Convention => C, Link_Name => Util.Systems.Constants.SYMBOL_PREFIX & "symlink"; pragma Weak_External (Sys_Symlink); -- ------------------------------ -- Test the Delete_Tree operation. -- ------------------------------ procedure Test_Delete_Tree (T : in out Test) is use type System.Address; Path : constant String := Util.Tests.Get_Test_Path ("test-delete-tree"); begin if Ada.Directories.Exists (Path) then Delete_Tree (Path); end if; -- Create a directory tree with symlink links that point to a non-existing file. Ada.Directories.Create_Directory (Path); for I in 1 .. 10 loop declare P : constant String := Compose (Path, Util.Strings.Image (I)); S : String (1 .. P'Length + 3); R : Integer; begin Ada.Directories.Create_Directory (P); S (1 .. P'Length) := P; S (P'Length + 1) := '/'; S (P'Length + 2) := 'A'; S (S'Last) := ASCII.NUL; for J in 1 .. 5 loop Ada.Directories.Create_Path (Compose (P, Util.Strings.Image (J))); end loop; if Sys_Symlink'Address /= System.Null_Address then R := Sys_Symlink (S'Address, S'Address); Util.Tests.Assert_Equals (T, 0, R, "symlink creation failed"); end if; end; end loop; T.Assert (Ada.Directories.Exists (Path), "Directory must exist"); -- Ada.Directories.Delete_Tree (Path) fails to delete the tree. Delete_Tree (Path); T.Assert (not Ada.Directories.Exists (Path), "Directory must have been deleted"); end Test_Delete_Tree; end Util.Files.Tests;
----------------------------------------------------------------------- -- files.tests -- Unit tests for files -- Copyright (C) 2009, 2010, 2011, 2012, 2013, 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. ----------------------------------------------------------------------- with System; with Ada.Directories; with Util.Systems.Constants; with Util.Test_Caller; package body Util.Files.Tests is use Util.Tests; package Caller is new Util.Test_Caller (Test, "Files"); procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is begin Caller.Add_Test (Suite, "Test Util.Files.Read_File", Test_Read_File'Access); Caller.Add_Test (Suite, "Test Util.Files.Read_File (missing)", Test_Read_File_Missing'Access); Caller.Add_Test (Suite, "Test Util.Files.Read_File (truncate)", Test_Read_File'Access); Caller.Add_Test (Suite, "Test Util.Files.Write_File", Test_Write_File'Access); Caller.Add_Test (Suite, "Test Util.Files.Iterate_Path", Test_Iterate_Path'Access); Caller.Add_Test (Suite, "Test Util.Files.Find_File_Path", Test_Find_File_Path'Access); Caller.Add_Test (Suite, "Test Util.Files.Compose_Path", Test_Compose_Path'Access); Caller.Add_Test (Suite, "Test Util.Files.Get_Relative_Path", Test_Get_Relative_Path'Access); Caller.Add_Test (Suite, "Test Util.Files.Delete_Tree", Test_Delete_Tree'Access); Caller.Add_Test (Suite, "Test Util.Files.Realpath", Test_Realpath'Access); end Add_Tests; -- ------------------------------ -- Test reading a file into a string -- Reads this ada source file and checks we have read it correctly -- ------------------------------ procedure Test_Read_File (T : in out Test) is Result : Unbounded_String; begin Read_File (Path => "regtests/util-files-tests.adb", Into => Result); T.Assert (Index (Result, "Util.Files.Tests") > 0, "Content returned by Read_File is not correct"); T.Assert (Index (Result, "end Util.Files.Tests;") > 0, "Content returned by Read_File is not correct"); end Test_Read_File; procedure Test_Read_File_Missing (T : in out Test) is Result : Unbounded_String; pragma Unreferenced (Result); begin Read_File (Path => "regtests/files-test--util.adb", Into => Result); T.Assert (False, "No exception raised"); exception when others => null; end Test_Read_File_Missing; procedure Test_Read_File_Truncate (T : in out Test) is Result : Unbounded_String; begin Read_File (Path => "regtests/util-files-tests.adb", Into => Result, Max_Size => 50); Assert_Equals (T, Length (Result), 50, "Read_File did not truncate correctly"); T.Assert (Index (Result, "Apache License") > 0, "Content returned by Read_File is not correct"); end Test_Read_File_Truncate; -- ------------------------------ -- Check writing a file -- ------------------------------ procedure Test_Write_File (T : in out Test) is Path : constant String := Util.Tests.Get_Test_Path ("test-write.txt"); Content : constant String := "Testing Util.Files.Write_File" & ASCII.LF; Result : Unbounded_String; begin Write_File (Path => Path, Content => Content); Read_File (Path => Path, Into => Result); Assert_Equals (T, To_String (Result), Content, "Invalid content written or read"); end Test_Write_File; -- ------------------------------ -- Check Find_File_Path -- ------------------------------ procedure Test_Find_File_Path (T : in out Test) is Dir : constant String := Util.Tests.Get_Path ("regtests"); Paths : constant String := ".;" & Dir; begin declare P : constant String := Util.Files.Find_File_Path ("test.properties", Paths); begin Assert_Equals (T, Dir & "/test.properties", P, "Invalid path returned"); end; Assert_Equals (T, "blablabla.properties", Util.Files.Find_File_Path ("blablabla.properties", Paths)); end Test_Find_File_Path; -- ------------------------------ -- Check Iterate_Path -- ------------------------------ procedure Test_Iterate_Path (T : in out Test) is procedure Check_Path (Dir : in String; Done : out Boolean); Last : Unbounded_String; procedure Check_Path (Dir : in String; Done : out Boolean) is begin if Dir = "a" or Dir = "bc" or Dir = "de" then Done := False; else Done := True; end if; Last := To_Unbounded_String (Dir); end Check_Path; begin Iterate_Path ("a;bc;de;f", Check_Path'Access); Assert_Equals (T, "f", Last, "Invalid last path"); Iterate_Path ("de;bc;de;b", Check_Path'Access); Assert_Equals (T, "b", Last, "Invalid last path"); Iterate_Path ("de;bc;de;a", Check_Path'Access, Ada.Strings.Backward); Assert_Equals (T, "de", Last, "Invalid last path"); end Test_Iterate_Path; -- ------------------------------ -- Test the Compose_Path operation -- ------------------------------ procedure Test_Compose_Path (T : in out Test) is begin Assert_Equals (T, "src/sys/processes/os-none", Compose_Path ("src;regtests;src/sys/processes", "os-none"), "Invalid path composition"); Assert_Equals (T, "regtests/bundles", Compose_Path ("src;regtests", "bundles"), "Invalid path composition"); if Ada.Directories.Exists ("/usr/bin") then Assert_Equals (T, "/usr/bin;/usr/local/bin;/usr/bin", Compose_Path ("/usr;/usr/local;/usr", "bin"), "Invalid path composition"); end if; end Test_Compose_Path; -- ------------------------------ -- Test the Get_Relative_Path operation. -- ------------------------------ procedure Test_Get_Relative_Path (T : in out Test) is begin Assert_Equals (T, "../util", Get_Relative_Path ("/home/john/src/asf", "/home/john/src/util"), "Invalid relative path"); Assert_Equals (T, "../util", Get_Relative_Path ("/home/john/src/asf/", "/home/john/src/util"), "Invalid relative path"); Assert_Equals (T, "../util/b", Get_Relative_Path ("/home/john/src/asf", "/home/john/src/util/b"), "Invalid relative path"); Assert_Equals (T, "../as", Get_Relative_Path ("/home/john/src/asf", "/home/john/src/as"), "Invalid relative path"); Assert_Equals (T, "../../", Get_Relative_Path ("/home/john/src/asf", "/home/john"), "Invalid relative path"); Assert_Equals (T, "/usr/share/admin", Get_Relative_Path ("/home/john/src/asf", "/usr/share/admin"), "Invalid absolute path"); Assert_Equals (T, "/home/john", Get_Relative_Path ("home/john/src/asf", "/home/john"), "Invalid relative path"); Assert_Equals (T, "e", Get_Relative_Path ("/home/john/src/asf", "/home/john/src/asf/e"), "Invalid relative path"); Assert_Equals (T, ".", Get_Relative_Path ("/home/john/src/asf", "/home/john/src/asf/"), "Invalid relative path"); end Test_Get_Relative_Path; function Sys_Symlink (Target : in System.Address; Link : in System.Address) return Integer with Import => True, Convention => C, Link_Name => Util.Systems.Constants.SYMBOL_PREFIX & "symlink"; pragma Weak_External (Sys_Symlink); -- ------------------------------ -- Test the Delete_Tree operation. -- ------------------------------ procedure Test_Delete_Tree (T : in out Test) is use type System.Address; Path : constant String := Util.Tests.Get_Test_Path ("test-delete-tree"); begin if Ada.Directories.Exists (Path) then Delete_Tree (Path); end if; -- Create a directory tree with symlink links that point to a non-existing file. Ada.Directories.Create_Directory (Path); for I in 1 .. 10 loop declare P : constant String := Compose (Path, Util.Strings.Image (I)); S : String (1 .. P'Length + 3); R : Integer; begin Ada.Directories.Create_Directory (P); S (1 .. P'Length) := P; S (P'Length + 1) := '/'; S (P'Length + 2) := 'A'; S (S'Last) := ASCII.NUL; for J in 1 .. 5 loop Ada.Directories.Create_Path (Compose (P, Util.Strings.Image (J))); end loop; if Sys_Symlink'Address /= System.Null_Address then R := Sys_Symlink (S'Address, S'Address); Util.Tests.Assert_Equals (T, 0, R, "symlink creation failed"); end if; end; end loop; T.Assert (Ada.Directories.Exists (Path), "Directory must exist"); -- Ada.Directories.Delete_Tree (Path) fails to delete the tree. Delete_Tree (Path); T.Assert (not Ada.Directories.Exists (Path), "Directory must have been deleted"); end Test_Delete_Tree; -- ------------------------------ -- Test the Realpath function. -- ------------------------------ procedure Test_Realpath (T : in out Test) is P : constant String := Util.Files.Realpath ("bin/util_harness"); begin Util.Tests.Assert_Matches (T, ".*/bin/util_harness", P); end Test_Realpath; end Util.Files.Tests;
Add Test_Realpath and register the test for execution
Add Test_Realpath and register the test for execution
Ada
apache-2.0
stcarrez/ada-util,stcarrez/ada-util
2592e8ffc7025fdd38913cc526ca71b4a23de1bc
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 := "64"; 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 := "65"; 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;
Bump version
Bump version
Ada
isc
jrmarino/synth,jrmarino/synth,jrmarino/synth,jrmarino/synth
7f6544686390adeaddb2fdf09235dc684fa6ed83
awa/plugins/awa-votes/src/awa-votes-beans.ads
awa/plugins/awa-votes/src/awa-votes-beans.ads
----------------------------------------------------------------------- -- awa-votes-beans -- Beans for module votes -- 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 Util.Beans.Basic; with AWA.Votes.Modules; with AWA.Votes.Models; -- === Vote Beans === -- The <b>Vote_Bean</b> is a bean intended to be used in presentation files (facelet files) -- to vote for an item. The managed bean can be easily configured in the application XML -- configuration file. The <b>permission</b> and <b>entity_type</b> are the two properties -- that should be defined in the configuration. The <b>permission</b> is the name of the -- permission that must be used to verify that the user is allowed to vote for the item. -- The <b>entity_type</b> is the name of the entity (table name) used by the item. -- The example below defines the bean <tt>questionVote</tt> defined by the question module. -- -- <managed-bean> -- <description>The vote bean that allows to vote for a question.</description> -- <managed-bean-name>questionVote</managed-bean-name> -- <managed-bean-class>AWA.Votes.Beans.Votes_Bean</managed-bean-class> -- <managed-bean-scope>request</managed-bean-scope> -- <managed-property> -- <property-name>permission</property-name> -- <property-class>String</property-class> -- <value>answer-create</value> -- </managed-property> -- <managed-property> -- <property-name>entity_type</property-name> -- <property-class>String</property-class> -- <value>awa_question</value> -- </managed-property> -- </managed-bean> -- -- The vote concerns entities for the <tt>awa_question</tt> entity table. -- The permission <tt>answer-create</tt> is used to verify for the vote. -- -- [http://ada-awa.googlecode.com/svn/wiki/awa_votes_bean.png] -- package AWA.Votes.Beans is type Vote_Bean is new AWA.Votes.Models.Vote_Bean with private; type Vote_Bean_Access is access all Vote_Bean'Class; -- Action to vote up. overriding procedure Vote_Up (Bean : in out Vote_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String); -- Action to vote down. overriding procedure Vote_Down (Bean : in out Vote_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String); -- Action to vote. overriding procedure Vote (Bean : in out Vote_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String); -- Create the Votes_Bean bean instance. function Create_Vote_Bean (Module : in AWA.Votes.Modules.Vote_Module_Access) return Util.Beans.Basic.Readonly_Bean_Access; private type Vote_Bean is new AWA.Votes.Models.Vote_Bean with record Module : AWA.Votes.Modules.Vote_Module_Access := null; end record; end AWA.Votes.Beans;
----------------------------------------------------------------------- -- awa-votes-beans -- Beans for module votes -- 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 Util.Beans.Basic; with AWA.Votes.Modules; with AWA.Votes.Models; -- === Vote Beans === -- The <tt>Vote_Bean</tt> is a bean intended to be used in presentation files (XHTML facelet -- files) to vote for an item. The managed bean can be easily configured in the application XML -- configuration file. The <b>permission</b> and <b>entity_type</b> are the two properties -- that should be defined in the configuration. The <b>permission</b> is the name of the -- permission that must be used to verify that the user is allowed to vote for the item. -- The <b>entity_type</b> is the name of the entity (table name) used by the item. -- The example below defines the bean <tt>questionVote</tt> defined by the question module. -- -- <managed-bean> -- <description>The vote bean that allows to vote for a question.</description> -- <managed-bean-name>questionVote</managed-bean-name> -- <managed-bean-class>AWA.Votes.Beans.Votes_Bean</managed-bean-class> -- <managed-bean-scope>request</managed-bean-scope> -- <managed-property> -- <property-name>permission</property-name> -- <property-class>String</property-class> -- <value>answer-create</value> -- </managed-property> -- <managed-property> -- <property-name>entity_type</property-name> -- <property-class>String</property-class> -- <value>awa_question</value> -- </managed-property> -- </managed-bean> -- -- The vote concerns entities for the <tt>awa_question</tt> entity table. -- The permission <tt>answer-create</tt> is used to verify that the vote is allowed. -- -- [http://ada-awa.googlecode.com/svn/wiki/awa_votes_bean.png] -- -- The managed bean defines three operations that can be called: <tt>vote_up</tt>, -- <tt>vote_down</tt> and <tt>vote</tt> to setup specific ratings. package AWA.Votes.Beans is type Vote_Bean is new AWA.Votes.Models.Vote_Bean with private; type Vote_Bean_Access is access all Vote_Bean'Class; -- Action to vote up. overriding procedure Vote_Up (Bean : in out Vote_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String); -- Action to vote down. overriding procedure Vote_Down (Bean : in out Vote_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String); -- Action to vote. overriding procedure Vote (Bean : in out Vote_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String); -- Create the Votes_Bean bean instance. function Create_Vote_Bean (Module : in AWA.Votes.Modules.Vote_Module_Access) return Util.Beans.Basic.Readonly_Bean_Access; private type Vote_Bean is new AWA.Votes.Models.Vote_Bean with record Module : AWA.Votes.Modules.Vote_Module_Access := null; end record; end AWA.Votes.Beans;
Update the documentation
Update the documentation
Ada
apache-2.0
Letractively/ada-awa,Letractively/ada-awa,tectronics/ada-awa,tectronics/ada-awa,tectronics/ada-awa,Letractively/ada-awa
b49b682469dd733ff8b2a5d3e96a19e1bf6a9a1f
src/wiki-nodes.adb
src/wiki-nodes.adb
----------------------------------------------------------------------- -- wiki-nodes -- Wiki Document Internal representation -- 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. ----------------------------------------------------------------------- package body Wiki.Nodes is -- ------------------------------ -- Create a text node. -- ------------------------------ function Create_Text (Text : in WString) return Node_Type_Access is begin return new Node_Type '(Kind => N_TEXT, Len => Text'Length, Text => Text, others => <>); end Create_Text; -- ------------------------------ -- Append a node to the node list. -- ------------------------------ procedure Append (Into : in out Node_List; Node : in Node_Type_Access) is Block : Node_List_Block_Access := Into.Current; begin if Block.Last = Block.Max then Block.Next := new Node_List_Block (Into.Length); Block := Block.Next; Into.Current := Block; end if; Block.Last := Block.Last + 1; Block.List (Block.Last) := Node; Into.Length := Into.Length + 1; end Append; end Wiki.Nodes;
----------------------------------------------------------------------- -- wiki-nodes -- Wiki Document Internal representation -- 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. ----------------------------------------------------------------------- package body Wiki.Nodes is -- ------------------------------ -- Create a text node. -- ------------------------------ function Create_Text (Text : in WString) return Node_Type_Access is begin return new Node_Type '(Kind => N_TEXT, Len => Text'Length, Text => Text, others => <>); end Create_Text; -- ------------------------------ -- Append a node to the document. -- ------------------------------ procedure Append (Into : in out Document; Node : in Node_Type_Access) is begin Append (Into.Nodes, Node); end Append; -- ------------------------------ -- Append a node to the node list. -- ------------------------------ procedure Append (Into : in out Node_List; Node : in Node_Type_Access) is Block : Node_List_Block_Access := Into.Current; begin if Block.Last = Block.Max then Block.Next := new Node_List_Block (Into.Length); Block := Block.Next; Into.Current := Block; end if; Block.Last := Block.Last + 1; Block.List (Block.Last) := Node; Into.Length := Into.Length + 1; end Append; end Wiki.Nodes;
Implement the Append procedure on a Document
Implement the Append procedure on a Document
Ada
apache-2.0
stcarrez/ada-wiki,stcarrez/ada-wiki
20c9cb092a3292a5023d6a8084f9b90f6f718f8b
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_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;
----------------------------------------------------------------------- -- 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); -- 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); -- 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); -- 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 the Append procedure to add a formatted text node to the document
Declare the Append procedure to add a formatted text node to the document
Ada
apache-2.0
stcarrez/ada-wiki,stcarrez/ada-wiki
f80c6eb44549a7c698d9d062f7b13ebbcfe852d3
src/ado-drivers.adb
src/ado-drivers.adb
----------------------------------------------------------------------- -- ADO Drivers -- Database Drivers -- Copyright (C) 2010, 2011, 2012, 2013, 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.Log.Loggers; with Ada.IO_Exceptions; package body ADO.Drivers is Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("ADO.Drivers"); -- Global configuration properties (loaded by Initialize). Global_Config : Util.Properties.Manager; -- ------------------------------ -- Initialize the drivers and the library by reading the property file -- and configure the runtime with it. -- ------------------------------ procedure Initialize (Config : in String) is begin Log.Info ("Initialize using property file {0}", Config); begin Util.Properties.Load_Properties (Global_Config, Config); exception when Ada.IO_Exceptions.Name_Error => Log.Error ("Configuration file '{0}' does not exist", Config); end; Initialize (Global_Config); end Initialize; -- ------------------------------ -- Initialize the drivers and the library and configure the runtime with the given properties. -- ------------------------------ procedure Initialize (Config : in Util.Properties.Manager'Class) is begin Global_Config := Util.Properties.Manager (Config); -- Initialize the drivers. ADO.Drivers.Initialize; end Initialize; -- ------------------------------ -- 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 is begin return Global_Config.Get (Name, Default); end Get_Config; -- ------------------------------ -- Returns true if the global configuration property is set to true/on. -- ------------------------------ function Is_On (Name : in String) return Boolean is Value : constant String := Global_Config.Get (Name, ""); begin return Value = "on" or Value = "true" or Value = "1"; end Is_On; -- Initialize the drivers which are available. procedure Initialize is separate; end ADO.Drivers;
----------------------------------------------------------------------- -- ADO Drivers -- Database Drivers -- Copyright (C) 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 Ada.IO_Exceptions; package body ADO.Drivers is Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("ADO.Drivers"); -- Global configuration properties (loaded by Initialize). Global_Config : Util.Properties.Manager; -- ------------------------------ -- Initialize the drivers and the library by reading the property file -- and configure the runtime with it. -- ------------------------------ procedure Initialize (Config : in String) is begin Log.Info ("Initialize using property file {0}", Config); begin Util.Properties.Load_Properties (Global_Config, Config); exception when Ada.IO_Exceptions.Name_Error => Log.Error ("Configuration file '{0}' does not exist", Config); end; Initialize (Global_Config); end Initialize; -- ------------------------------ -- Initialize the drivers and the library and configure the runtime with the given properties. -- ------------------------------ procedure Initialize (Config : in Util.Properties.Manager'Class) is begin Global_Config := Util.Properties.Manager (Config); -- Initialize the drivers. ADO.Drivers.Initialize; end Initialize; -- ------------------------------ -- 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 is begin return Global_Config.Get (Name, Default); end Get_Config; -- ------------------------------ -- Returns true if the global configuration property is set to true/on. -- ------------------------------ function Is_On (Name : in String) return Boolean is Value : constant String := Global_Config.Get (Name, ""); begin return Value = "on" or Value = "true" or Value = "1"; end Is_On; -- Initialize the drivers which are available. procedure Initialize is separate; end ADO.Drivers;
Update header
Update header
Ada
apache-2.0
stcarrez/ada-ado
c75fae6958758a0d39b2838ea69694cdadeae027
src/ado-queries.ads
src/ado-queries.ads
----------------------------------------------------------------------- -- ado-queries -- Database Queries -- Copyright (C) 2009, 2010, 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.Strings; with Util.Refs; with ADO.SQL; with ADO.Drivers; with Interfaces; with Ada.Strings.Unbounded; with Ada.Finalization; -- == 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_Index is new Natural; type File_Index is new Natural; type Query_File is limited private; type Query_File_Access is access all Query_File; type Query_Definition is limited private; type Query_Definition_Access is access all Query_Definition; type Query_Manager is limited new Ada.Finalization.Limited_Controlled with private; type Query_Manager_Access is access all Query_Manager; -- ------------------------------ -- 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; Manager : in Query_Manager'Class) return String; function Get_SQL (From : in Query_Definition_Access; Manager : in Query_Manager; Use_Count : in Boolean) return String; private -- ------------------------------ -- 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; Query : Query_Index := 0; end record; -- ------------------------------ -- 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; -- The SHA1 hash of the query map section. Sha1_Map : Util.Strings.Name_Access; -- The first query defined for that file. Queries : Query_Definition_Access; -- The next XML query file registered in the application. Next : Query_File_Access; -- The unique file index. File : File_Index := 0; end record; 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; 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; type Query_Info_Access is access all Query_Info; 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; subtype Query_Index_Table is Query_Index range 1 .. Query_Index'Last; subtype File_Index_Table is File_Index range 1 .. File_Index'Last; type Query_File_Info is record -- Query absolute path name (after path resolution). Path : Ada.Strings.Unbounded.String_Access; -- File File : Query_File_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; 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_Info; Name : in String) return Query_Definition_Access; type Query_Table is array (Query_Index_Table range <>) of Query_Info_Ref.Atomic_Ref; type Query_Table_Access is access all Query_Table; type File_Table is array (File_Index_Table range <>) of Query_File_Info; type File_Table_Access is access all File_Table; type Query_Manager is limited new Ada.Finalization.Limited_Controlled with record Driver : ADO.Drivers.Driver_Index; Queries : Query_Table_Access; Files : File_Table_Access; end record; overriding procedure Finalize (Manager : in out Query_Manager); end ADO.Queries;
----------------------------------------------------------------------- -- ado-queries -- Database Queries -- Copyright (C) 2009, 2010, 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.Strings; with Util.Refs; with ADO.SQL; with ADO.Drivers; with Interfaces; with Ada.Strings.Unbounded; with Ada.Finalization; -- == 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_Index is new Natural; type File_Index is new Natural; type Query_File is limited private; type Query_File_Access is access all Query_File; type Query_Definition is limited private; type Query_Definition_Access is access all Query_Definition; type Query_Manager is limited new Ada.Finalization.Limited_Controlled with private; type Query_Manager_Access is access all Query_Manager; -- ------------------------------ -- 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; Manager : in Query_Manager'Class) return String; function Get_SQL (From : in Query_Definition_Access; Manager : in Query_Manager; Use_Count : in Boolean) return String; private -- ------------------------------ -- 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; Query : Query_Index := 0; end record; -- ------------------------------ -- 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; -- The SHA1 hash of the query map section. Sha1_Map : Util.Strings.Name_Access; -- The first query defined for that file. Queries : Query_Definition_Access; -- The next XML query file registered in the application. Next : Query_File_Access; -- The unique file index. File : File_Index := 0; end record; 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; 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; type Query_Info_Access is access all Query_Info; 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; subtype Query_Index_Table is Query_Index range 1 .. Query_Index'Last; subtype File_Index_Table is File_Index range 1 .. File_Index'Last; type Query_File_Info is record -- Query absolute path name (after path resolution). Path : Ada.Strings.Unbounded.Unbounded_String; -- File File : Query_File_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; 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_Info; Name : in String) return Query_Definition_Access; type Query_Table is array (Query_Index_Table range <>) of Query_Info_Ref.Atomic_Ref; type Query_Table_Access is access all Query_Table; type File_Table is array (File_Index_Table range <>) of Query_File_Info; type File_Table_Access is access all File_Table; type Query_Manager is limited new Ada.Finalization.Limited_Controlled with record Driver : ADO.Drivers.Driver_Index; Queries : Query_Table_Access; Files : File_Table_Access; end record; overriding procedure Finalize (Manager : in out Query_Manager); end ADO.Queries;
Use a Unbounded_String to hold the file's path
Use a Unbounded_String to hold the file's path
Ada
apache-2.0
stcarrez/ada-ado
5e3542ac0d092a1cded44ef6ec3f3b9155da81da
src/gen-model-tables.adb
src/gen-model-tables.adb
----------------------------------------------------------------------- -- gen-model-tables -- Database table model representation -- Copyright (C) 2009, 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; with Util.Strings; package body Gen.Model.Tables 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 : Column_Definition; Name : String) return Util.Beans.Objects.Object is use type Gen.Model.Mappings.Mapping_Definition_Access; begin if Name = "type" and From.Type_Mapping /= null then declare Bean : constant Util.Beans.Basic.Readonly_Bean_Access := From.Type_Mapping.all'Access; begin return Util.Beans.Objects.To_Object (Bean, Util.Beans.Objects.STATIC); end; elsif Name = "type" then return Util.Beans.Objects.To_Object (From.Type_Name); elsif Name = "index" then return Util.Beans.Objects.To_Object (From.Number); elsif Name = "isUnique" then return Util.Beans.Objects.To_Object (From.Unique); elsif Name = "isNull" then return Util.Beans.Objects.To_Object (not From.Not_Null); elsif Name = "isInserted" then return Util.Beans.Objects.To_Object (From.Is_Inserted); elsif Name = "isUpdated" then return Util.Beans.Objects.To_Object (From.Is_Updated); elsif Name = "sqlType" then return Util.Beans.Objects.To_Object (From.Sql_Type); elsif Name = "sqlName" then return Util.Beans.Objects.To_Object (From.Sql_Name); elsif Name = "isVersion" then return Util.Beans.Objects.To_Object (From.Is_Version); elsif Name = "isReadable" then return Util.Beans.Objects.To_Object (From.Is_Readable); elsif Name = "isPrimaryKey" then return Util.Beans.Objects.To_Object (From.Is_Key); elsif Name = "isPrimitiveType" then return Util.Beans.Objects.To_Object (From.Is_Basic_Type); elsif Name = "generator" then return From.Generator; else return Definition (From).Get_Value (Name); end if; end Get_Value; -- ------------------------------ -- Returns true if the column type is a basic type. -- ------------------------------ function Is_Basic_Type (From : Column_Definition) return Boolean is use type Gen.Model.Mappings.Mapping_Definition_Access; use type Gen.Model.Mappings.Basic_Type; Name : constant String := To_String (From.Type_Name); begin if From.Type_Mapping /= null then return From.Type_Mapping.Kind /= Gen.Model.Mappings.T_BLOB; end if; return Name = "int" or Name = "String" or Name = "ADO.Identifier" or Name = "Timestamp" or Name = "Integer" or Name = "long" or Name = "Long" or Name = "Date" or Name = "Time"; end Is_Basic_Type; -- ------------------------------ -- Returns the column type. -- ------------------------------ function Get_Type (From : Column_Definition) return String is use type Gen.Model.Mappings.Mapping_Definition_Access; begin if From.Type_Mapping /= null then return To_String (From.Type_Mapping.Target); else return To_String (From.Type_Name); end if; end Get_Type; -- ------------------------------ -- Prepare the generation of the model. -- ------------------------------ overriding procedure Prepare (O : in out Column_Definition) is use type Mappings.Mapping_Definition_Access; begin O.Type_Mapping := Gen.Model.Mappings.Find_Type (O.Type_Name); if O.Type_Mapping = null then O.Type_Mapping := O.Table.Package_Def.Find_Type (O.Type_Name); end if; end Prepare; -- ------------------------------ -- Get the value identified by the name. -- If the name cannot be found, the method should return the Null object. -- ------------------------------ overriding function Get_Value (From : Association_Definition; Name : String) return Util.Beans.Objects.Object is begin return Column_Definition (From).Get_Value (Name); end Get_Value; -- ------------------------------ -- Initialize the table definition instance. -- ------------------------------ overriding procedure Initialize (O : in out Table_Definition) is begin O.Members_Bean := Util.Beans.Objects.To_Object (O.Members'Unchecked_Access, Util.Beans.Objects.STATIC); end Initialize; -- ------------------------------ -- Create a table with the given name. -- ------------------------------ function Create_Table (Name : in Unbounded_String) return Table_Definition_Access is Table : constant Table_Definition_Access := new Table_Definition; begin Table.Name := Name; declare Pos : constant Natural := Index (Table.Name, ".", Ada.Strings.Backward); begin if Pos > 0 then Table.Pkg_Name := Unbounded_Slice (Table.Name, 1, Pos - 1); Table.Type_Name := Unbounded_Slice (Table.Name, Pos + 1, Length (Table.Name)); else Table.Pkg_Name := To_Unbounded_String ("ADO"); Table.Type_Name := Table.Name; end if; end; return Table; end Create_Table; -- ------------------------------ -- Create a table column with the given name and add it to the table. -- ------------------------------ procedure Add_Column (Table : in out Table_Definition; Name : in Unbounded_String; Column : out Column_Definition_Access) is begin Column := new Column_Definition; Column.Name := Name; Column.Sql_Name := Name; Column.Number := Table.Members.Get_Count; Table.Members.Append (Column); if Name = "version" then Table.Version_Column := Column; Column.Is_Version := True; Column.Is_Updated := False; Column.Is_Inserted := False; elsif Name = "id" then Table.Id_Column := Column; Column.Is_Key := True; end if; end Add_Column; -- ------------------------------ -- 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 Table_Definition; Name : in String) return Util.Beans.Objects.Object is begin if Name = "members" or Name = "columns" then return From.Members_Bean; elsif Name = "id" and From.Id_Column /= null then declare Bean : constant Util.Beans.Basic.Readonly_Bean_Access := From.Id_Column.all'Access; begin return Util.Beans.Objects.To_Object (Bean, Util.Beans.Objects.STATIC); end; elsif Name = "version" and From.Version_Column /= null then declare Bean : constant Util.Beans.Basic.Readonly_Bean_Access := From.Version_Column.all'Unchecked_Access; begin return Util.Beans.Objects.To_Object (Bean, Util.Beans.Objects.STATIC); end; elsif Name = "hasAssociations" then return Util.Beans.Objects.To_Object (From.Has_Associations); elsif Name = "type" then return Util.Beans.Objects.To_Object (From.Type_Name); elsif Name = "table" then return Util.Beans.Objects.To_Object (From.Name); else return Definition (From).Get_Value (Name); end if; end Get_Value; -- ------------------------------ -- Prepare the generation of the model. -- ------------------------------ overriding procedure Prepare (O : in out Table_Definition) is Iter : Column_List.Cursor := O.Members.First; begin while Column_List.Has_Element (Iter) loop Column_List.Element (Iter).Prepare; Column_List.Next (Iter); end loop; end Prepare; -- ------------------------------ -- Set the table name and determines the package name. -- ------------------------------ procedure Set_Table_Name (Table : in out Table_Definition; Name : in String) is Pos : constant Natural := Util.Strings.Rindex (Name, '.'); begin Table.Name := To_Unbounded_String (Name); if Pos > 0 then Table.Pkg_Name := To_Unbounded_String (Name (Name'First .. Pos - 1)); Table.Type_Name := To_Unbounded_String (Name (Pos + 1 .. Name'Last)); else Table.Pkg_Name := To_Unbounded_String ("ADO"); Table.Type_Name := Table.Name; end if; end Set_Table_Name; end Gen.Model.Tables;
----------------------------------------------------------------------- -- gen-model-tables -- Database table model representation -- Copyright (C) 2009, 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; with Util.Strings; package body Gen.Model.Tables 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 : Column_Definition; Name : String) return Util.Beans.Objects.Object is use type Gen.Model.Mappings.Mapping_Definition_Access; begin if Name = "type" and From.Type_Mapping /= null then declare Bean : constant Util.Beans.Basic.Readonly_Bean_Access := From.Type_Mapping.all'Access; begin return Util.Beans.Objects.To_Object (Bean, Util.Beans.Objects.STATIC); end; elsif Name = "type" then return Util.Beans.Objects.To_Object (From.Type_Name); elsif Name = "index" then return Util.Beans.Objects.To_Object (From.Number); elsif Name = "isUnique" then return Util.Beans.Objects.To_Object (From.Unique); elsif Name = "isNull" then return Util.Beans.Objects.To_Object (not From.Not_Null); elsif Name = "isInserted" then return Util.Beans.Objects.To_Object (From.Is_Inserted); elsif Name = "isUpdated" then return Util.Beans.Objects.To_Object (From.Is_Updated); elsif Name = "sqlType" then return Util.Beans.Objects.To_Object (From.Sql_Type); elsif Name = "sqlName" then return Util.Beans.Objects.To_Object (From.Sql_Name); elsif Name = "isVersion" then return Util.Beans.Objects.To_Object (From.Is_Version); elsif Name = "isReadable" then return Util.Beans.Objects.To_Object (From.Is_Readable); elsif Name = "isPrimaryKey" then return Util.Beans.Objects.To_Object (From.Is_Key); elsif Name = "isPrimitiveType" then return Util.Beans.Objects.To_Object (From.Is_Basic_Type); elsif Name = "generator" then return From.Generator; else return Definition (From).Get_Value (Name); end if; end Get_Value; -- ------------------------------ -- Returns true if the column type is a basic type. -- ------------------------------ function Is_Basic_Type (From : Column_Definition) return Boolean is use type Gen.Model.Mappings.Mapping_Definition_Access; use type Gen.Model.Mappings.Basic_Type; Name : constant String := To_String (From.Type_Name); begin if From.Type_Mapping /= null then return From.Type_Mapping.Kind /= Gen.Model.Mappings.T_BLOB; end if; return Name = "int" or Name = "String" or Name = "ADO.Identifier" or Name = "Timestamp" or Name = "Integer" or Name = "long" or Name = "Long" or Name = "Date" or Name = "Time"; end Is_Basic_Type; -- ------------------------------ -- Returns the column type. -- ------------------------------ function Get_Type (From : Column_Definition) return String is use type Gen.Model.Mappings.Mapping_Definition_Access; begin if From.Type_Mapping /= null then return To_String (From.Type_Mapping.Target); else return To_String (From.Type_Name); end if; end Get_Type; -- ------------------------------ -- Prepare the generation of the model. -- ------------------------------ overriding procedure Prepare (O : in out Column_Definition) is use type Mappings.Mapping_Definition_Access; begin O.Type_Mapping := Gen.Model.Mappings.Find_Type (O.Type_Name); if O.Type_Mapping = null then O.Type_Mapping := O.Table.Package_Def.Find_Type (O.Type_Name); end if; end Prepare; -- ------------------------------ -- Get the value identified by the name. -- If the name cannot be found, the method should return the Null object. -- ------------------------------ overriding function Get_Value (From : Association_Definition; Name : String) return Util.Beans.Objects.Object is begin return Column_Definition (From).Get_Value (Name); end Get_Value; -- ------------------------------ -- Initialize the table definition instance. -- ------------------------------ overriding procedure Initialize (O : in out Table_Definition) is begin O.Members_Bean := Util.Beans.Objects.To_Object (O.Members'Unchecked_Access, Util.Beans.Objects.STATIC); end Initialize; -- ------------------------------ -- Create a table with the given name. -- ------------------------------ function Create_Table (Name : in Unbounded_String) return Table_Definition_Access is Table : constant Table_Definition_Access := new Table_Definition; begin Table.Name := Name; declare Pos : constant Natural := Index (Table.Name, ".", Ada.Strings.Backward); begin if Pos > 0 then Table.Pkg_Name := Unbounded_Slice (Table.Name, 1, Pos - 1); Table.Type_Name := Unbounded_Slice (Table.Name, Pos + 1, Length (Table.Name)); else Table.Pkg_Name := To_Unbounded_String ("ADO"); Table.Type_Name := Table.Name; end if; end; return Table; end Create_Table; -- ------------------------------ -- Create a table column with the given name and add it to the table. -- ------------------------------ procedure Add_Column (Table : in out Table_Definition; Name : in Unbounded_String; Column : out Column_Definition_Access) is begin Column := new Column_Definition; Column.Name := Name; Column.Sql_Name := Name; Column.Number := Table.Members.Get_Count; Column.Table := Table'Unchecked_Access; Table.Members.Append (Column); if Name = "version" then Table.Version_Column := Column; Column.Is_Version := True; Column.Is_Updated := False; Column.Is_Inserted := False; elsif Name = "id" then Table.Id_Column := Column; Column.Is_Key := True; end if; end Add_Column; -- ------------------------------ -- 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 Table_Definition; Name : in String) return Util.Beans.Objects.Object is begin if Name = "members" or Name = "columns" then return From.Members_Bean; elsif Name = "id" and From.Id_Column /= null then declare Bean : constant Util.Beans.Basic.Readonly_Bean_Access := From.Id_Column.all'Access; begin return Util.Beans.Objects.To_Object (Bean, Util.Beans.Objects.STATIC); end; elsif Name = "version" and From.Version_Column /= null then declare Bean : constant Util.Beans.Basic.Readonly_Bean_Access := From.Version_Column.all'Unchecked_Access; begin return Util.Beans.Objects.To_Object (Bean, Util.Beans.Objects.STATIC); end; elsif Name = "hasAssociations" then return Util.Beans.Objects.To_Object (From.Has_Associations); elsif Name = "type" then return Util.Beans.Objects.To_Object (From.Type_Name); elsif Name = "table" then return Util.Beans.Objects.To_Object (From.Name); else return Definition (From).Get_Value (Name); end if; end Get_Value; -- ------------------------------ -- Prepare the generation of the model. -- ------------------------------ overriding procedure Prepare (O : in out Table_Definition) is Iter : Column_List.Cursor := O.Members.First; begin while Column_List.Has_Element (Iter) loop Column_List.Element (Iter).Prepare; Column_List.Next (Iter); end loop; end Prepare; -- ------------------------------ -- Set the table name and determines the package name. -- ------------------------------ procedure Set_Table_Name (Table : in out Table_Definition; Name : in String) is Pos : constant Natural := Util.Strings.Rindex (Name, '.'); begin Table.Name := To_Unbounded_String (Name); if Pos > 0 then Table.Pkg_Name := To_Unbounded_String (Name (Name'First .. Pos - 1)); Table.Type_Name := To_Unbounded_String (Name (Pos + 1 .. Name'Last)); else Table.Pkg_Name := To_Unbounded_String ("ADO"); Table.Type_Name := Table.Name; end if; end Set_Table_Name; end Gen.Model.Tables;
Fix initialization of the column to get a reference to the table
Fix initialization of the column to get a reference to the table
Ada
apache-2.0
stcarrez/dynamo,stcarrez/dynamo,stcarrez/dynamo
7d01f472455440d502752255a4d52d94586d288a
mat/src/events/mat-events-targets.ads
mat/src/events/mat-events-targets.ads
----------------------------------------------------------------------- -- mat-events-targets - Events received and collected from a target -- Copyright (C) 2014, 2015 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Containers.Ordered_Maps; with Ada.Containers.Vectors; with Util.Concurrent.Counters; with MAT.Frames; package MAT.Events.Targets is Not_Found : exception; type Event_Type is mod 16; type Probe_Index_Type is (MSG_BEGIN, MSG_END, MSG_LIBRARY, MSG_MALLOC, MSG_FREE, MSG_REALLOC ); type Event_Id_Type is new Natural; type Probe_Event_Type is record Id : Event_Id_Type; Event : MAT.Types.Uint16; Index : Probe_Index_Type; Time : MAT.Types.Target_Tick_Ref; Thread : MAT.Types.Target_Thread_Ref; Frame : MAT.Frames.Frame_Type; Addr : MAT.Types.Target_Addr; Size : MAT.Types.Target_Size; Old_Addr : MAT.Types.Target_Addr; end record; subtype Target_Event is Probe_Event_Type; package Target_Event_Vectors is new Ada.Containers.Vectors (Positive, Target_Event); subtype Target_Event_Vector is Target_Event_Vectors.Vector; subtype Target_Event_Cursor is Target_Event_Vectors.Cursor; type Target_Events is tagged limited private; type Target_Events_Access is access all Target_Events'Class; -- Add the event in the list of events and increment the event counter. procedure Insert (Target : in out Target_Events; Event : in Probe_Event_Type); procedure Get_Events (Target : in out Target_Events; Start : in MAT.Types.Target_Time; Finish : in MAT.Types.Target_Time; Into : in out Target_Event_Vector); -- Get the start and finish time for the events that have been received. procedure Get_Time_Range (Target : in out Target_Events; Start : out MAT.Types.Target_Time; Finish : out MAT.Types.Target_Time); -- Get the probe event with the given allocated unique id. function Get_Event (Target : in Target_Events; Id : in Event_Id_Type) return Probe_Event_Type; -- Get the first and last event that have been received. procedure Get_Limits (Target : in out Target_Events; First : out Probe_Event_Type; Last : out Probe_Event_Type); -- Get the current event counter. function Get_Event_Counter (Target : in Target_Events) return Integer; -- Iterate over the events starting from the <tt>Start</tt> event and until the -- <tt>Finish</tt> event is found (inclusive). Execute the <tt>Process</tt> procedure -- with each event instance. procedure Iterate (Target : in out Target_Events; Start : in Event_Id_Type; Finish : in Event_Id_Type; Process : access procedure (Event : in Probe_Event_Type)); private EVENT_BLOCK_SIZE : constant Event_Id_Type := 1024; type Probe_Event_Array is array (1 .. EVENT_BLOCK_SIZE) of Probe_Event_Type; type Event_Block is record Start : MAT.Types.Target_Time; Finish : MAT.Types.Target_Time; Count : Event_Id_Type := 0; Events : Probe_Event_Array; end record; type Event_Block_Access is access all Event_Block; use type MAT.Types.Target_Time; package Event_Maps is new Ada.Containers.Ordered_Maps (Key_Type => MAT.Types.Target_Time, Element_Type => Event_Block_Access); subtype Event_Map is Event_Maps.Map; subtype Event_Cursor is Event_Maps.Cursor; package Event_Id_Maps is new Ada.Containers.Ordered_Maps (Key_Type => Event_Id_Type, Element_Type => Event_Block_Access); subtype Event_Id_Map is Event_Id_Maps.Map; subtype Event_Id_Cursor is Event_Id_Maps.Cursor; protected type Event_Collector is -- Add the event in the list of events. procedure Insert (Event : in Probe_Event_Type); procedure Get_Events (Start : in MAT.Types.Target_Time; Finish : in MAT.Types.Target_Time; Into : in out Target_Event_Vector); -- Get the first and last event that have been received. procedure Get_Limits (First : out Probe_Event_Type; Last : out Probe_Event_Type); -- Get the start and finish time for the events that have been received. procedure Get_Time_Range (Start : out MAT.Types.Target_Time; Finish : out MAT.Types.Target_Time); -- Get the probe event with the given allocated unique id. function Get_Event (Id : in Event_Id_Type) return Probe_Event_Type; -- Iterate over the events starting from the <tt>Start</tt> event and until the -- <tt>Finish</tt> event is found (inclusive). Execute the <tt>Process</tt> procedure -- with each event instance. procedure Iterate (Start : in Event_Id_Type; Finish : in Event_Id_Type; Process : access procedure (Event : in Probe_Event_Type)); private Current : Event_Block_Access := null; Events : Event_Map; Ids : Event_Id_Map; Last_Id : Event_Id_Type := 0; end Event_Collector; type Target_Events is tagged limited record Events : Event_Collector; Event_Count : Util.Concurrent.Counters.Counter; end record; end MAT.Events.Targets;
----------------------------------------------------------------------- -- mat-events-targets - Events received and collected from a target -- Copyright (C) 2014, 2015 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Containers.Ordered_Maps; with Ada.Containers.Vectors; with Util.Concurrent.Counters; with MAT.Frames; package MAT.Events.Targets is Not_Found : exception; type Event_Type is mod 16; type Probe_Index_Type is (MSG_BEGIN, MSG_END, MSG_LIBRARY, MSG_MALLOC, MSG_FREE, MSG_REALLOC ); type Event_Id_Type is new Natural; type Probe_Event_Type is record Id : Event_Id_Type; Event : MAT.Types.Uint16; Index : Probe_Index_Type; Time : MAT.Types.Target_Tick_Ref; Thread : MAT.Types.Target_Thread_Ref; Frame : MAT.Frames.Frame_Type; Addr : MAT.Types.Target_Addr; Size : MAT.Types.Target_Size; Old_Addr : MAT.Types.Target_Addr; end record; subtype Target_Event is Probe_Event_Type; package Target_Event_Vectors is new Ada.Containers.Vectors (Positive, Target_Event); subtype Target_Event_Vector is Target_Event_Vectors.Vector; subtype Target_Event_Cursor is Target_Event_Vectors.Cursor; -- Find in the list the first event with the given type. -- Raise <tt>Not_Found</tt> if the list does not contain such event. function Find (List : in Target_Event_Vector; Kind : in Probe_Index_Type) return Probe_Event_Type; type Target_Events is tagged limited private; type Target_Events_Access is access all Target_Events'Class; -- Add the event in the list of events and increment the event counter. procedure Insert (Target : in out Target_Events; Event : in Probe_Event_Type); procedure Get_Events (Target : in out Target_Events; Start : in MAT.Types.Target_Time; Finish : in MAT.Types.Target_Time; Into : in out Target_Event_Vector); -- Get the start and finish time for the events that have been received. procedure Get_Time_Range (Target : in out Target_Events; Start : out MAT.Types.Target_Time; Finish : out MAT.Types.Target_Time); -- Get the probe event with the given allocated unique id. function Get_Event (Target : in Target_Events; Id : in Event_Id_Type) return Probe_Event_Type; -- Get the first and last event that have been received. procedure Get_Limits (Target : in out Target_Events; First : out Probe_Event_Type; Last : out Probe_Event_Type); -- Get the current event counter. function Get_Event_Counter (Target : in Target_Events) return Integer; -- Iterate over the events starting from the <tt>Start</tt> event and until the -- <tt>Finish</tt> event is found (inclusive). Execute the <tt>Process</tt> procedure -- with each event instance. procedure Iterate (Target : in out Target_Events; Start : in Event_Id_Type; Finish : in Event_Id_Type; Process : access procedure (Event : in Probe_Event_Type)); private EVENT_BLOCK_SIZE : constant Event_Id_Type := 1024; type Probe_Event_Array is array (1 .. EVENT_BLOCK_SIZE) of Probe_Event_Type; type Event_Block is record Start : MAT.Types.Target_Time; Finish : MAT.Types.Target_Time; Count : Event_Id_Type := 0; Events : Probe_Event_Array; end record; type Event_Block_Access is access all Event_Block; use type MAT.Types.Target_Time; package Event_Maps is new Ada.Containers.Ordered_Maps (Key_Type => MAT.Types.Target_Time, Element_Type => Event_Block_Access); subtype Event_Map is Event_Maps.Map; subtype Event_Cursor is Event_Maps.Cursor; package Event_Id_Maps is new Ada.Containers.Ordered_Maps (Key_Type => Event_Id_Type, Element_Type => Event_Block_Access); subtype Event_Id_Map is Event_Id_Maps.Map; subtype Event_Id_Cursor is Event_Id_Maps.Cursor; protected type Event_Collector is -- Add the event in the list of events. procedure Insert (Event : in Probe_Event_Type); procedure Get_Events (Start : in MAT.Types.Target_Time; Finish : in MAT.Types.Target_Time; Into : in out Target_Event_Vector); -- Get the first and last event that have been received. procedure Get_Limits (First : out Probe_Event_Type; Last : out Probe_Event_Type); -- Get the start and finish time for the events that have been received. procedure Get_Time_Range (Start : out MAT.Types.Target_Time; Finish : out MAT.Types.Target_Time); -- Get the probe event with the given allocated unique id. function Get_Event (Id : in Event_Id_Type) return Probe_Event_Type; -- Iterate over the events starting from the <tt>Start</tt> event and until the -- <tt>Finish</tt> event is found (inclusive). Execute the <tt>Process</tt> procedure -- with each event instance. procedure Iterate (Start : in Event_Id_Type; Finish : in Event_Id_Type; Process : access procedure (Event : in Probe_Event_Type)); private Current : Event_Block_Access := null; Events : Event_Map; Ids : Event_Id_Map; Last_Id : Event_Id_Type := 0; end Event_Collector; type Target_Events is tagged limited record Events : Event_Collector; Event_Count : Util.Concurrent.Counters.Counter; end record; end MAT.Events.Targets;
Declare the Find function to find a specific event type in a list
Declare the Find function to find a specific event type in a list
Ada
apache-2.0
stcarrez/mat,stcarrez/mat,stcarrez/mat
3951d4ea53e2fca9b0ae32f2a9c2a65094d2a823
src/asf-components-html-lists.adb
src/asf-components-html-lists.adb
----------------------------------------------------------------------- -- html.lists -- List of items -- 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 Util.Log.Loggers; with Util.Beans.Basic; with ASF.Components.Base; package body ASF.Components.Html.Lists is use Util.Log; use type EL.Objects.Data_Type; Log : constant Loggers.Logger := Loggers.Create ("ASF.Components.Html.Lists"); -- ------------------------------ -- Get the value to write on the output. -- ------------------------------ function Get_Value (UI : in UIList) return EL.Objects.Object is begin return UI.Get_Attribute (UI.Get_Context.all, "value"); end Get_Value; -- ------------------------------ -- Set the value to write on the output. -- ------------------------------ procedure Set_Value (UI : in out UIList; Value : in EL.Objects.Object) is begin null; end Set_Value; -- ------------------------------ -- Get the variable name -- ------------------------------ function Get_Var (UI : in UIList) return String is Var : constant EL.Objects.Object := UI.Get_Attribute (UI.Get_Context.all, "var"); begin return EL.Objects.To_String (Var); end Get_Var; procedure Encode_Children (UI : in UIList; Context : in out Faces_Context'Class) is begin if not UI.Is_Rendered (Context) then return; end if; declare Value : EL.Objects.Object := Get_Value (UI); Kind : constant EL.Objects.Data_Type := EL.Objects.Get_Type (Value); Name : constant String := UI.Get_Var; Bean : access Util.Beans.Basic.Readonly_Bean'Class; Is_Reverse : constant Boolean := UI.Get_Attribute ("reverse", Context, False); List : Util.Beans.Basic.List_Bean_Access; Count : Natural; begin -- Check that we have a List_Bean but do not complain if we have a null value. if Kind /= EL.Objects.TYPE_BEAN then if Kind /= EL.Objects.TYPE_NULL then Log.Error ("Invalid list bean (found a {0})", EL.Objects.Get_Type_Name (Value)); end if; return; end if; Bean := EL.Objects.To_Bean (Value); if Bean = null or else not (Bean.all in Util.Beans.Basic.List_Bean'Class) then Log.Error ("Invalid list bean: it does not implement 'List_Bean' interface"); return; end if; List := Util.Beans.Basic.List_Bean'Class (Bean.all)'Unchecked_Access; Count := List.Get_Count; if Is_Reverse then for I in reverse 1 .. Count loop List.Set_Row_Index (I); Value := List.Get_Row; Context.Set_Attribute (Name, Value); Log.Debug ("Set variable {0}", Name); Base.UIComponent (UI).Encode_Children (Context); end loop; else for I in 1 .. Count loop List.Set_Row_Index (I); Value := List.Get_Row; Context.Set_Attribute (Name, Value); Log.Debug ("Set variable {0}", Name); Base.UIComponent (UI).Encode_Children (Context); end loop; end if; end; end Encode_Children; end ASF.Components.Html.Lists;
----------------------------------------------------------------------- -- html.lists -- List of items -- Copyright (C) 2009, 2010, 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.Log.Loggers; with Util.Beans.Basic; with ASF.Components.Base; package body ASF.Components.Html.Lists is use Util.Log; use type EL.Objects.Data_Type; Log : constant Loggers.Logger := Loggers.Create ("ASF.Components.Html.Lists"); -- ------------------------------ -- Get the value to write on the output. -- ------------------------------ function Get_Value (UI : in UIList) return EL.Objects.Object is begin return UI.Get_Attribute (UI.Get_Context.all, "value"); end Get_Value; -- ------------------------------ -- Set the value to write on the output. -- ------------------------------ procedure Set_Value (UI : in out UIList; Value : in EL.Objects.Object) is begin null; end Set_Value; -- ------------------------------ -- Get the variable name -- ------------------------------ function Get_Var (UI : in UIList) return String is Var : constant EL.Objects.Object := UI.Get_Attribute (UI.Get_Context.all, "var"); begin return EL.Objects.To_String (Var); end Get_Var; procedure Encode_Children (UI : in UIList; Context : in out Faces_Context'Class) is begin if not UI.Is_Rendered (Context) then return; end if; declare Value : EL.Objects.Object := Get_Value (UI); Kind : constant EL.Objects.Data_Type := EL.Objects.Get_Type (Value); Name : constant String := UI.Get_Var; Bean : access Util.Beans.Basic.Readonly_Bean'Class; Is_Reverse : constant Boolean := UI.Get_Attribute ("reverse", Context, False); List : Util.Beans.Basic.List_Bean_Access; Count : Natural; begin -- Check that we have a List_Bean but do not complain if we have a null value. if Kind /= EL.Objects.TYPE_BEAN then if Kind /= EL.Objects.TYPE_NULL then ASF.Components.Base.Log_Error (UI, "Invalid list bean (found a {0})", EL.Objects.Get_Type_Name (Value)); end if; return; end if; Bean := EL.Objects.To_Bean (Value); if Bean = null or else not (Bean.all in Util.Beans.Basic.List_Bean'Class) then ASF.Components.Base.Log_Error (UI, "Invalid list bean: " & "it does not implement 'List_Bean' interface"); return; end if; List := Util.Beans.Basic.List_Bean'Class (Bean.all)'Unchecked_Access; Count := List.Get_Count; if Is_Reverse then for I in reverse 1 .. Count loop List.Set_Row_Index (I); Value := List.Get_Row; Context.Set_Attribute (Name, Value); Log.Debug ("Set variable {0}", Name); Base.UIComponent (UI).Encode_Children (Context); end loop; else for I in 1 .. Count loop List.Set_Row_Index (I); Value := List.Get_Row; Context.Set_Attribute (Name, Value); Log.Debug ("Set variable {0}", Name); Base.UIComponent (UI).Encode_Children (Context); end loop; end if; end; end Encode_Children; end ASF.Components.Html.Lists;
Use the Log_Error procedure to report the error message and associate the error with the view file and line number
Use the Log_Error procedure to report the error message and associate the error with the view file and line number
Ada
apache-2.0
Letractively/ada-asf,Letractively/ada-asf,Letractively/ada-asf
86cbf7e168b4ccd66c1f6ce7199feee586b2b12b
awa/plugins/awa-workspaces/regtests/awa-workspaces-tests.ads
awa/plugins/awa-workspaces/regtests/awa-workspaces-tests.ads
----------------------------------------------------------------------- -- awa-workspaces-tests -- Unit tests for workspaces and invitations -- 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 AWA.Tests; package AWA.Workspaces.Tests is procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite); type Test is new AWA.Tests.Test with null record; -- Test sending an invitation. procedure Test_Invite_User (T : in out Test); end AWA.Workspaces.Tests;
----------------------------------------------------------------------- -- awa-workspaces-tests -- Unit tests for workspaces and invitations -- 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 AWA.Tests; package AWA.Workspaces.Tests is procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite); type Test is new AWA.Tests.Test with null record; -- Verify the anonymous access for the invitation page. procedure Verify_Anonymous (T : in out Test; Key : in String); -- Test sending an invitation. procedure Test_Invite_User (T : in out Test); end AWA.Workspaces.Tests;
Declare the Verify_Anonymous procedure to check the invitation page
Declare the Verify_Anonymous procedure to check the invitation page
Ada
apache-2.0
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
652a3461832d7291af037237a7d0151f90cb9da1
regtests/util-streams-files-tests.adb
regtests/util-streams-files-tests.adb
----------------------------------------------------------------------- -- streams.files.tests -- Unit tests for buffered streams -- Copyright (C) 2010, 2011, 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.Strings.Unbounded; with Util.Test_Caller; with Util.Files; with Util.Streams.Texts; package body Util.Streams.Files.Tests is use Util.Tests; use Ada.Streams.Stream_IO; package Caller is new Util.Test_Caller (Test, "Streams.Files"); procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is begin Caller.Add_Test (Suite, "Test Util.Streams.Files.Create, Write, Flush, Close", Test_Read_Write'Access); Caller.Add_Test (Suite, "Test Util.Streams.Files.Write, Flush", Test_Write'Access); end Add_Tests; -- ------------------------------ -- Test reading and writing on a buffered stream with various buffer sizes -- ------------------------------ procedure Test_Read_Write (T : in out Test) is Stream : aliased File_Stream; Buffer : Util.Streams.Texts.Print_Stream; begin for I in 1 .. 32 loop Buffer.Initialize (Output => Stream'Access, Size => I); Stream.Create (Mode => Out_File, Name => "test-stream.txt"); Buffer.Write ("abcd"); Buffer.Write (" fghij"); Buffer.Flush; Stream.Close; declare Content : Ada.Strings.Unbounded.Unbounded_String; begin Util.Files.Read_File (Path => "test-stream.txt", Into => Content, Max_Size => 10000); Assert_Equals (T, "abcd fghij", Content, "Invalid content written to the file stream"); end; end loop; end Test_Read_Write; procedure Test_Write (T : in out Test) is begin null; end Test_Write; end Util.Streams.Files.Tests;
----------------------------------------------------------------------- -- streams.files.tests -- Unit tests for buffered streams -- Copyright (C) 2010, 2011, 2017, 2019, 2021 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Strings.Unbounded; with Util.Test_Caller; with Util.Files; with Util.Streams.Texts; package body Util.Streams.Files.Tests is use Util.Tests; use Ada.Streams.Stream_IO; package Caller is new Util.Test_Caller (Test, "Streams.Files"); procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is begin Caller.Add_Test (Suite, "Test Util.Streams.Files.Create, Write, Flush, Close", Test_Read_Write'Access); Caller.Add_Test (Suite, "Test Util.Streams.Files.Write, Flush", Test_Write'Access); Caller.Add_Test (Suite, "Test Util.Streams.Copy", Test_Copy_Stream'Access); end Add_Tests; -- ------------------------------ -- Test reading and writing on a buffered stream with various buffer sizes -- ------------------------------ procedure Test_Read_Write (T : in out Test) is Stream : aliased File_Stream; Buffer : Util.Streams.Texts.Print_Stream; begin for I in 1 .. 32 loop Buffer.Initialize (Output => Stream'Access, Size => I); Stream.Create (Mode => Out_File, Name => "test-stream.txt"); Buffer.Write ("abcd"); Buffer.Write (" fghij"); Buffer.Flush; Stream.Close; declare Content : Ada.Strings.Unbounded.Unbounded_String; begin Util.Files.Read_File (Path => "test-stream.txt", Into => Content, Max_Size => 10000); Assert_Equals (T, "abcd fghij", Content, "Invalid content written to the file stream"); end; end loop; end Test_Read_Write; procedure Test_Write (T : in out Test) is begin null; end Test_Write; procedure Test_Copy_Stream (T : in out Test) is Path : constant String := Util.Tests.Get_Path ("regtests/files/utf-8.txt"); Target : constant String := Util.Tests.Get_Test_Path ("copy-stream.txt"); Output : Util.Streams.Files.File_Stream; Input : Util.Streams.Files.File_Stream; begin Output.Create (Name => Target, Mode => Ada.Streams.Stream_IO.Out_File); Input.Open (Name => Path, Mode => Ada.Streams.Stream_IO.In_File); Util.Streams.Copy (From => Input, Into => Output); Input.Close; Output.Close; Util.Tests.Assert_Equal_Files (T, Path, Target, "Copy stream failed"); end Test_Copy_Stream; end Util.Streams.Files.Tests;
Implement the Test_Copy_Stream procedure and register it for execution
Implement the Test_Copy_Stream procedure and register it for execution
Ada
apache-2.0
stcarrez/ada-util,stcarrez/ada-util
99af4fc4ebb5444efa8b74a38bf581f7a6db0c4d
src/security-openid.ads
src/security-openid.ads
----------------------------------------------------------------------- -- security-openid -- Open ID 2.0 Support -- Copyright (C) 2009, 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 Ada.Calendar; with Ada.Finalization; -- with Security.Permissions; -- == OpenID == -- The <b>Security.Openid</b> package implements an authentication framework based -- on OpenID 2.0. -- -- See OpenID Authentication 2.0 - Final -- http://openid.net/specs/openid-authentication-2_0.html -- -- The authentication process is the following: -- -- * The <b>Initialize</b> procedure is called to configure the OpenID realm and set the -- OpenID return callback CB. -- * The <b>Discover</b> procedure is called to retrieve from the OpenID provider the XRDS -- stream and identify the provider. An <b>End_Point</b> is returned. -- * The <b>Associate</b> procedure is called to make the association with the <b>End_Point</b>. -- The <b>Association</b> record holds session, and authentication. -- * The <b>Get_Authentication_URL</b> builds the provider OpenID authentication -- URL for the association. -- * The application should redirected the user to the authentication URL. -- * The OpenID provider authenticate the user and redirects the user to the callback CB. -- * The association is decoded from the callback parameter. -- * The <b>Verify</b> procedure is called with the association to check the result and -- obtain the authentication results. -- -- There are basically two steps that an application must implement. -- -- [http://ada-security.googlecode.com/svn/wiki/OpenID.png] -- -- == Discovery: creating the authentication URL == -- The first step is to create an authentication URL to which the user must be redirected. -- In this step, we have to create an OpenId manager, discover the OpenID provider, -- do the association and get an <b>End_Point</b>. -- -- Mgr : Openid.Manager; -- OP : Openid.End_Point; -- Assoc : constant Association_Access := new Association; -- -- The -- -- Server.Initialize (Mgr); -- Mgr.Discover (Provider, OP); -- Yadis discovery (get the XRDS file). -- Mgr.Associate (OP, Assoc.all);-- Associate and get an end-point with a key. -- -- After this first step, you must manage to save the association in the HTTP session. -- Then you must redirect to the authentication URL that is obtained by using: -- -- Auth_URL : constant String := Mgr.Get_Authentication_URL (OP, Assoc.all); -- -- == Verify: acknowledge the authentication in the callback URL == -- The second step is done when the user has finished the authentication successfully or not. -- For this step, the application must get back the association that was saved in the session. -- It must also prepare a parameters object that allows the OpenID framework to get the -- URI parameters from the return callback. -- -- Mgr : Openid.Manager; -- Assoc : Association_Access := ...; -- Get the association saved in the session. -- Auth : Openid.Authentication; -- Params : Auth_Params; -- -- The OpenID manager must be initialized and the <b>Verify</b> procedure is called with -- the association, parameters and the authentication result. The <b>Get_Status</b> function -- must be used to check that the authentication succeeded. -- -- Server.Initialize (Mgr); -- Mgr.Verify (Assoc.all, Params, Auth); -- if Openid.Get_Status (Auth) /= Openid.AUTHENTICATED then ... -- Failure. -- -- -- package Security.Openid is Invalid_End_Point : exception; Service_Error : exception; type Parameters is limited interface; function Get_Parameter (Params : in Parameters; Name : in String) return String is abstract; -- ------------------------------ -- OpenID provider -- ------------------------------ -- The <b>End_Point</b> represents the OpenID provider that will authenticate -- the user. type End_Point is private; function To_String (OP : End_Point) return String; -- ------------------------------ -- Association -- ------------------------------ -- The OpenID association contains the shared secret between the relying party -- and the OpenID provider. The association can be cached and reused to authenticate -- different users using the same OpenID provider. The association also has an -- expiration date. type Association is private; -- Dump the association as a string (for debugging purposes) function To_String (Assoc : Association) return String; type Auth_Result is (AUTHENTICATED, CANCEL, SETUP_NEEDED, UNKNOWN, INVALID_SIGNATURE); -- ------------------------------ -- OpenID provider -- ------------------------------ -- type Authentication is private; -- Get the email address function Get_Email (Auth : in Authentication) return String; -- Get the user first name. function Get_First_Name (Auth : in Authentication) return String; -- Get the user last name. function Get_Last_Name (Auth : in Authentication) return String; -- Get the user full name. function Get_Full_Name (Auth : in Authentication) return String; -- Get the user identity. function Get_Identity (Auth : in Authentication) return String; -- Get the user claimed identity. function Get_Claimed_Id (Auth : in Authentication) return String; -- Get the user language. function Get_Language (Auth : in Authentication) return String; -- Get the user country. function Get_Country (Auth : in Authentication) return String; -- Get the result of the authentication. function Get_Status (Auth : in Authentication) return Auth_Result; -- ------------------------------ -- OpenID Default principal -- ------------------------------ type Principal is new Security.Principal with private; type Principal_Access is access all Principal'Class; -- Returns true if the given role is stored in the user principal. -- function Has_Role (User : in Principal; -- Role : in Permissions.Role_Type) return Boolean; -- Get the principal name. function Get_Name (From : in Principal) return String; -- Get the user email address. function Get_Email (From : in Principal) return String; -- Get the authentication data. function Get_Authentication (From : in Principal) return Authentication; -- Create a principal with the given authentication results. function Create_Principal (Auth : in Authentication) return Principal_Access; -- ------------------------------ -- OpenID Manager -- ------------------------------ -- The <b>Manager</b> provides the core operations for the OpenID process. type Manager is tagged limited private; -- Initialize the OpenID realm. procedure Initialize (Realm : in out Manager; Name : in String; Return_To : in String); -- Discover the OpenID provider that must be used to authenticate the user. -- The <b>Name</b> can be an URL or an alias that identifies the provider. -- A cached OpenID provider can be returned. -- (See OpenID Section 7.3 Discovery) procedure Discover (Realm : in out Manager; Name : in String; Result : out End_Point); -- Associate the application (relying party) with the OpenID provider. -- The association can be cached. -- (See OpenID Section 8 Establishing Associations) procedure Associate (Realm : in out Manager; OP : in End_Point; Result : out Association); function Get_Authentication_URL (Realm : in Manager; OP : in End_Point; Assoc : in Association) return String; -- Verify the authentication result procedure Verify (Realm : in out Manager; Assoc : in Association; Request : in Parameters'Class; Result : out Authentication); -- Verify the authentication result procedure Verify_Discovered (Realm : in out Manager; Assoc : in Association; Request : in Parameters'Class; Result : out Authentication); -- Verify the signature part of the result procedure Verify_Signature (Realm : in Manager; Assoc : in Association; Request : in Parameters'Class; Result : in out Authentication); -- Read the XRDS document from the URI and initialize the OpenID provider end point. procedure Discover_XRDS (Realm : in out Manager; URI : in String; Result : out End_Point); -- Extract from the XRDS content the OpenID provider URI. -- The default implementation is very basic as it returns the first <URI> -- available in the stream without validating the XRDS document. -- Raises the <b>Invalid_End_Point</b> exception if the URI cannot be found. procedure Extract_XRDS (Realm : in out Manager; Content : in String; Result : out End_Point); private use Ada.Strings.Unbounded; type Association is record Session_Type : Unbounded_String; Assoc_Type : Unbounded_String; Assoc_Handle : Unbounded_String; Mac_Key : Unbounded_String; Expired : Ada.Calendar.Time; end record; type Authentication is record Status : Auth_Result; Identity : Unbounded_String; Claimed_Id : Unbounded_String; Email : Unbounded_String; Full_Name : Unbounded_String; First_Name : Unbounded_String; Last_Name : Unbounded_String; Language : Unbounded_String; Country : Unbounded_String; Gender : Unbounded_String; Timezone : Unbounded_String; Nickname : Unbounded_String; end record; type End_Point is record URL : Unbounded_String; Alias : Unbounded_String; Expired : Ada.Calendar.Time; end record; type Manager is new Ada.Finalization.Limited_Controlled with record Realm : Unbounded_String; Return_To : Unbounded_String; end record; type Principal is new Security.Principal with record Auth : Authentication; end record; end Security.Openid;
----------------------------------------------------------------------- -- security-openid -- Open ID 2.0 Support -- Copyright (C) 2009, 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 Ada.Calendar; with Ada.Finalization; -- with Security.Permissions; -- == OpenID == -- The <b>Security.Openid</b> package implements an authentication framework based -- on OpenID 2.0. -- -- See OpenID Authentication 2.0 - Final -- http://openid.net/specs/openid-authentication-2_0.html -- -- The authentication process is the following: -- -- * The <b>Initialize</b> procedure is called to configure the OpenID realm and set the -- OpenID return callback CB. -- * The <b>Discover</b> procedure is called to retrieve from the OpenID provider the XRDS -- stream and identify the provider. An <b>End_Point</b> is returned. -- * The <b>Associate</b> procedure is called to make the association with the <b>End_Point</b>. -- The <b>Association</b> record holds session, and authentication. -- * The <b>Get_Authentication_URL</b> builds the provider OpenID authentication -- URL for the association. -- * The application should redirected the user to the authentication URL. -- * The OpenID provider authenticate the user and redirects the user to the callback CB. -- * The association is decoded from the callback parameter. -- * The <b>Verify</b> procedure is called with the association to check the result and -- obtain the authentication results. -- -- There are basically two steps that an application must implement. -- -- [http://ada-security.googlecode.com/svn/wiki/OpenID.png] -- -- == Discovery: creating the authentication URL == -- The first step is to create an authentication URL to which the user must be redirected. -- In this step, we have to create an OpenId manager, discover the OpenID provider, -- do the association and get an <b>End_Point</b>. -- -- Mgr : Openid.Manager; -- OP : Openid.End_Point; -- Assoc : constant Association_Access := new Association; -- -- The -- -- Server.Initialize (Mgr); -- Mgr.Discover (Provider, OP); -- Yadis discovery (get the XRDS file). -- Mgr.Associate (OP, Assoc.all);-- Associate and get an end-point with a key. -- -- After this first step, you must manage to save the association in the HTTP session. -- Then you must redirect to the authentication URL that is obtained by using: -- -- Auth_URL : constant String := Mgr.Get_Authentication_URL (OP, Assoc.all); -- -- == Verify: acknowledge the authentication in the callback URL == -- The second step is done when the user has finished the authentication successfully or not. -- For this step, the application must get back the association that was saved in the session. -- It must also prepare a parameters object that allows the OpenID framework to get the -- URI parameters from the return callback. -- -- Mgr : Openid.Manager; -- Assoc : Association_Access := ...; -- Get the association saved in the session. -- Auth : Openid.Authentication; -- Params : Auth_Params; -- -- The OpenID manager must be initialized and the <b>Verify</b> procedure is called with -- the association, parameters and the authentication result. The <b>Get_Status</b> function -- must be used to check that the authentication succeeded. -- -- Server.Initialize (Mgr); -- Mgr.Verify (Assoc.all, Params, Auth); -- if Openid.Get_Status (Auth) /= Openid.AUTHENTICATED then ... -- Failure. -- -- -- package Security.Openid is Invalid_End_Point : exception; Service_Error : exception; type Parameters is limited interface; function Get_Parameter (Params : in Parameters; Name : in String) return String is abstract; -- ------------------------------ -- OpenID provider -- ------------------------------ -- The <b>End_Point</b> represents the OpenID provider that will authenticate -- the user. type End_Point is private; function To_String (OP : End_Point) return String; -- ------------------------------ -- Association -- ------------------------------ -- The OpenID association contains the shared secret between the relying party -- and the OpenID provider. The association can be cached and reused to authenticate -- different users using the same OpenID provider. The association also has an -- expiration date. type Association is private; -- Dump the association as a string (for debugging purposes) function To_String (Assoc : Association) return String; type Auth_Result is (AUTHENTICATED, CANCEL, SETUP_NEEDED, UNKNOWN, INVALID_SIGNATURE); -- ------------------------------ -- OpenID provider -- ------------------------------ -- type Authentication is private; -- Get the email address function Get_Email (Auth : in Authentication) return String; -- Get the user first name. function Get_First_Name (Auth : in Authentication) return String; -- Get the user last name. function Get_Last_Name (Auth : in Authentication) return String; -- Get the user full name. function Get_Full_Name (Auth : in Authentication) return String; -- Get the user identity. function Get_Identity (Auth : in Authentication) return String; -- Get the user claimed identity. function Get_Claimed_Id (Auth : in Authentication) return String; -- Get the user language. function Get_Language (Auth : in Authentication) return String; -- Get the user country. function Get_Country (Auth : in Authentication) return String; -- Get the result of the authentication. function Get_Status (Auth : in Authentication) return Auth_Result; -- ------------------------------ -- OpenID Default principal -- ------------------------------ type Principal is new Security.Principal with private; type Principal_Access is access all Principal'Class; -- Get the principal name. function Get_Name (From : in Principal) return String; -- Get the user email address. function Get_Email (From : in Principal) return String; -- Get the authentication data. function Get_Authentication (From : in Principal) return Authentication; -- Create a principal with the given authentication results. function Create_Principal (Auth : in Authentication) return Principal_Access; -- ------------------------------ -- OpenID Manager -- ------------------------------ -- The <b>Manager</b> provides the core operations for the OpenID process. type Manager is tagged limited private; -- Initialize the OpenID realm. procedure Initialize (Realm : in out Manager; Name : in String; Return_To : in String); -- Discover the OpenID provider that must be used to authenticate the user. -- The <b>Name</b> can be an URL or an alias that identifies the provider. -- A cached OpenID provider can be returned. -- (See OpenID Section 7.3 Discovery) procedure Discover (Realm : in out Manager; Name : in String; Result : out End_Point); -- Associate the application (relying party) with the OpenID provider. -- The association can be cached. -- (See OpenID Section 8 Establishing Associations) procedure Associate (Realm : in out Manager; OP : in End_Point; Result : out Association); function Get_Authentication_URL (Realm : in Manager; OP : in End_Point; Assoc : in Association) return String; -- Verify the authentication result procedure Verify (Realm : in out Manager; Assoc : in Association; Request : in Parameters'Class; Result : out Authentication); -- Verify the authentication result procedure Verify_Discovered (Realm : in out Manager; Assoc : in Association; Request : in Parameters'Class; Result : out Authentication); -- Verify the signature part of the result procedure Verify_Signature (Realm : in Manager; Assoc : in Association; Request : in Parameters'Class; Result : in out Authentication); -- Read the XRDS document from the URI and initialize the OpenID provider end point. procedure Discover_XRDS (Realm : in out Manager; URI : in String; Result : out End_Point); -- Extract from the XRDS content the OpenID provider URI. -- The default implementation is very basic as it returns the first <URI> -- available in the stream without validating the XRDS document. -- Raises the <b>Invalid_End_Point</b> exception if the URI cannot be found. procedure Extract_XRDS (Realm : in out Manager; Content : in String; Result : out End_Point); private use Ada.Strings.Unbounded; type Association is record Session_Type : Unbounded_String; Assoc_Type : Unbounded_String; Assoc_Handle : Unbounded_String; Mac_Key : Unbounded_String; Expired : Ada.Calendar.Time; end record; type Authentication is record Status : Auth_Result; Identity : Unbounded_String; Claimed_Id : Unbounded_String; Email : Unbounded_String; Full_Name : Unbounded_String; First_Name : Unbounded_String; Last_Name : Unbounded_String; Language : Unbounded_String; Country : Unbounded_String; Gender : Unbounded_String; Timezone : Unbounded_String; Nickname : Unbounded_String; end record; type End_Point is record URL : Unbounded_String; Alias : Unbounded_String; Expired : Ada.Calendar.Time; end record; type Manager is new Ada.Finalization.Limited_Controlled with record Realm : Unbounded_String; Return_To : Unbounded_String; end record; type Principal is new Security.Principal with record Auth : Authentication; end record; end Security.Openid;
Remove the Has_Role operation
Remove the Has_Role operation
Ada
apache-2.0
Letractively/ada-security
28bb84bd76b39463f9aa499a84e505e664c73a75
src/asf-applications-main.ads
src/asf-applications-main.ads
----------------------------------------------------------------------- -- applications -- Ada Web Application -- Copyright (C) 2009, 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.Beans.Basic; with Util.Locales; with EL.Objects; with EL.Contexts; with EL.Functions; with EL.Functions.Default; with EL.Variables.Default; with Ada.Strings.Unbounded; with ASF.Locales; with ASF.Factory; with ASF.Converters; with ASF.Validators; with ASF.Contexts.Faces; with ASF.Contexts.Exceptions; with ASF.Lifecycles; with ASF.Applications.Views; with ASF.Navigations; with ASF.Beans; with ASF.Requests; with ASF.Responses; with ASF.Servlets; with ASF.Events.Faces.Actions; with Security.Permissions; use Security; package ASF.Applications.Main is use ASF.Beans; -- ------------------------------ -- Factory for creation of lifecycle, view handler -- ------------------------------ type Application_Factory is tagged limited private; -- Create the lifecycle handler. The lifecycle handler is created during -- the initialization phase of the application. The default implementation -- creates an <b>ASF.Lifecycles.Default.Default_Lifecycle</b> object. -- It can be overriden to change the behavior of the ASF request lifecycle. function Create_Lifecycle_Handler (App : in Application_Factory) return ASF.Lifecycles.Lifecycle_Access; -- Create the view handler. The view handler is created during -- the initialization phase of the application. The default implementation -- creates an <b>ASF.Applications.Views.View_Handler</b> object. -- It can be overriden to change the views associated with the application. function Create_View_Handler (App : in Application_Factory) return ASF.Applications.Views.View_Handler_Access; -- Create the navigation handler. The navigation handler is created during -- the initialization phase of the application. The default implementation -- creates an <b>ASF.Navigations.Navigation_Handler</b> object. -- It can be overriden to change the navigations associated with the application. function Create_Navigation_Handler (App : in Application_Factory) return ASF.Navigations.Navigation_Handler_Access; -- Create the permission manager. The permission manager is created during -- the initialization phase of the application. The default implementation -- creates a <b>Security.Permissions.Permission_Manager</b> object. function Create_Permission_Manager (App : in Application_Factory) return Security.Permissions.Permission_Manager_Access; -- Create the exception handler. The exception handler is created during -- the initialization phase of the application. The default implementation -- creates a <b>ASF.Contexts.Exceptions.Exception_Handler</b> object. function Create_Exception_Handler (App : in Application_Factory) return ASF.Contexts.Exceptions.Exception_Handler_Access; -- ------------------------------ -- Application -- ------------------------------ type Application is new ASF.Servlets.Servlet_Registry and ASF.Events.Faces.Actions.Action_Listener with private; type Application_Access is access all Application'Class; -- Get the application view handler. function Get_View_Handler (App : access Application) return access Views.View_Handler'Class; -- Get the lifecycle handler. function Get_Lifecycle_Handler (App : in Application) return ASF.Lifecycles.Lifecycle_Access; -- Get the navigation handler. function Get_Navigation_Handler (App : in Application) return ASF.Navigations.Navigation_Handler_Access; -- Get the permission manager associated with this application. function Get_Permission_Manager (App : in Application) return Security.Permissions.Permission_Manager_Access; -- Get the action event listener responsible for processing action -- events and triggering the navigation to the next view using the -- navigation handler. function Get_Action_Listener (App : in Application) return ASF.Events.Faces.Actions.Action_Listener_Access; -- Process the action associated with the action event. The action returns -- and outcome which is then passed to the navigation handler to navigate to -- the next view. overriding procedure Process_Action (Listener : in Application; Event : in ASF.Events.Faces.Actions.Action_Event'Class; Context : in out Contexts.Faces.Faces_Context'Class); -- Initialize the application procedure Initialize (App : in out Application; Conf : in Config; Factory : in out Application_Factory'Class); -- 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. procedure Initialize_Components (App : in out Application); -- Initialize the application configuration properties. Properties defined in <b>Conf</b> -- are expanded by using the EL expression resolver. procedure Initialize_Config (App : in out Application; Conf : in out Config); -- Initialize the servlets provided by the application. -- This procedure is called by <b>Initialize</b>. -- It should register the application servlets. procedure Initialize_Servlets (App : in out Application); -- Initialize the filters provided by the application. -- This procedure is called by <b>Initialize</b>. -- It should register the application filters. procedure Initialize_Filters (App : in out Application); -- Finalizes the application, freeing the memory. overriding procedure Finalize (App : in out Application); -- Get the configuration parameter; function Get_Config (App : Application; Param : Config_Param) return String; -- Set a global variable in the global EL contexts. procedure Set_Global (App : in out Application; Name : in String; Value : in String); procedure Set_Global (App : in out Application; Name : in String; Value : in EL.Objects.Object); -- Resolve a global variable and return its value. -- Raises the <b>EL.Functions.No_Variable</b> exception if the variable does not exist. function Get_Global (App : in Application; Name : in Ada.Strings.Unbounded.Unbounded_String; Context : in EL.Contexts.ELContext'Class) return EL.Objects.Object; -- Get the list of supported locales for this application. function Get_Supported_Locales (App : in Application) return Util.Locales.Locale_Array; -- Add the locale to the list of supported locales. procedure Add_Supported_Locale (App : in out Application; Locale : in Util.Locales.Locale); -- Get the default locale defined by the application. function Get_Default_Locale (App : in Application) return Util.Locales.Locale; -- Set the default locale defined by the application. procedure Set_Default_Locale (App : in out Application; Locale : in Util.Locales.Locale); -- Compute the locale that must be used according to the <b>Accept-Language</b> request -- header and the application supported locales. function Calculate_Locale (Handler : in Application; Context : in ASF.Contexts.Faces.Faces_Context'Class) return Util.Locales.Locale; -- Register a bundle and bind it to a facelet variable. procedure Register (App : in out Application; Name : in String; Bundle : in String); -- Register the bean identified by <b>Name</b> and associated with the class <b>Class</b>. -- The class must have been registered by using the <b>Register</b> class operation. -- The scope defines the scope of the bean. procedure Register (App : in out Application; Name : in String; Class : in String; Params : in Parameter_Bean_Ref.Ref; Scope : in Scope_Type := REQUEST_SCOPE); -- Register under the name identified by <b>Name</b> the class instance <b>Class</b>. procedure Register_Class (App : in out Application; Name : in String; Class : in ASF.Beans.Class_Binding_Access); -- Register under the name identified by <b>Name</b> a function to create a bean. -- This is a simplified class registration. procedure Register_Class (App : in out Application; Name : in String; Handler : in ASF.Beans.Create_Bean_Access); -- Create a bean by using the create operation registered for the name procedure Create (App : in Application; Name : in Ada.Strings.Unbounded.Unbounded_String; Context : in EL.Contexts.ELContext'Class; Result : out Util.Beans.Basic.Readonly_Bean_Access; Scope : out Scope_Type); -- Add a converter in the application. The converter is referenced by -- the specified name in the XHTML files. procedure Add_Converter (App : in out Application; Name : in String; Converter : in ASF.Converters.Converter_Access); -- Register a binding library in the factory. procedure Add_Components (App : in out Application; Bindings : in ASF.Factory.Factory_Bindings_Access); -- Closes the application procedure Close (App : in out Application); -- Set the current faces context before processing a view. procedure Set_Context (App : in out Application; Context : in ASF.Contexts.Faces.Faces_Context_Access); -- Execute the lifecycle phases on the faces context. procedure Execute_Lifecycle (App : in Application; Context : in out ASF.Contexts.Faces.Faces_Context'Class); -- Dispatch the request received on a page. procedure Dispatch (App : in out Application; Page : in String; Request : in out ASF.Requests.Request'Class; Response : in out ASF.Responses.Response'Class); -- Dispatch a bean action request. -- 1. Find the bean object identified by <b>Name</b>, create it if necessary. -- 2. Resolve the bean method identified by <b>Operation</b>. -- 3. If the method is an action method (see ASF.Events.Actions), call that method. -- 4. Using the outcome action result, decide using the navigation handler what -- is the result view. -- 5. Render the result view resolved by the navigation handler. procedure Dispatch (App : in out Application; Name : in String; Operation : in String; Request : in out ASF.Requests.Request'Class; Response : in out ASF.Responses.Response'Class; Prepare : access procedure (Bean : access Util.Beans.Basic.Bean'Class)); -- Find the converter instance that was registered under the given name. -- Returns null if no such converter exist. function Find (App : in Application; Name : in EL.Objects.Object) return ASF.Converters.Converter_Access; -- Find the validator instance that was registered under the given name. -- Returns null if no such validator exist. function Find_Validator (App : in Application; Name : in EL.Objects.Object) return ASF.Validators.Validator_Access; -- Register some functions generic with procedure Set_Functions (Mapper : in out EL.Functions.Function_Mapper'Class); procedure Register_Functions (App : in out Application'Class); -- Register some bean definitions. generic with procedure Set_Beans (Factory : in out ASF.Beans.Bean_Factory); procedure Register_Beans (App : in out Application'Class); -- Load the resource bundle identified by the <b>Name</b> and for the given -- <b>Locale</b>. procedure Load_Bundle (App : in out Application; Name : in String; Locale : in String; Bundle : out ASF.Locales.Bundle); private type Application_Factory is tagged limited null record; type Application is new ASF.Servlets.Servlet_Registry and ASF.Events.Faces.Actions.Action_Listener with record View : aliased ASF.Applications.Views.View_Handler; Lifecycle : ASF.Lifecycles.Lifecycle_Access; Factory : aliased ASF.Beans.Bean_Factory; Locales : ASF.Locales.Factory; Globals : aliased EL.Variables.Default.Default_Variable_Mapper; Functions : aliased EL.Functions.Default.Default_Function_Mapper; -- The component factory Components : aliased ASF.Factory.Component_Factory; -- The action listener. Action_Listener : ASF.Events.Faces.Actions.Action_Listener_Access; -- The navigation handler. Navigation : ASF.Navigations.Navigation_Handler_Access := null; -- The permission manager. Permissions : Security.Permissions.Permission_Manager_Access := null; end record; end ASF.Applications.Main;
----------------------------------------------------------------------- -- applications -- Ada Web Application -- Copyright (C) 2009, 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.Beans.Basic; with Util.Locales; with EL.Objects; with EL.Contexts; with EL.Functions; with EL.Functions.Default; with EL.Variables.Default; with Ada.Strings.Unbounded; with ASF.Locales; with ASF.Factory; with ASF.Converters; with ASF.Validators; with ASF.Contexts.Faces; with ASF.Contexts.Exceptions; with ASF.Lifecycles; with ASF.Applications.Views; with ASF.Navigations; with ASF.Beans; with ASF.Requests; with ASF.Responses; with ASF.Servlets; with ASF.Events.Faces.Actions; with Security.Policies; use Security; package ASF.Applications.Main is use ASF.Beans; -- ------------------------------ -- Factory for creation of lifecycle, view handler -- ------------------------------ type Application_Factory is tagged limited private; -- Create the lifecycle handler. The lifecycle handler is created during -- the initialization phase of the application. The default implementation -- creates an <b>ASF.Lifecycles.Default.Default_Lifecycle</b> object. -- It can be overriden to change the behavior of the ASF request lifecycle. function Create_Lifecycle_Handler (App : in Application_Factory) return ASF.Lifecycles.Lifecycle_Access; -- Create the view handler. The view handler is created during -- the initialization phase of the application. The default implementation -- creates an <b>ASF.Applications.Views.View_Handler</b> object. -- It can be overriden to change the views associated with the application. function Create_View_Handler (App : in Application_Factory) return ASF.Applications.Views.View_Handler_Access; -- Create the navigation handler. The navigation handler is created during -- the initialization phase of the application. The default implementation -- creates an <b>ASF.Navigations.Navigation_Handler</b> object. -- It can be overriden to change the navigations associated with the application. function Create_Navigation_Handler (App : in Application_Factory) return ASF.Navigations.Navigation_Handler_Access; -- Create the security policy manager. The security policy manager is created during -- the initialization phase of the application. The default implementation -- creates a <b>Security.Policies.Policy_Manager</b> object. function Create_Security_Manager (App : in Application_Factory) return Security.Policies.Policy_Manager_Access; -- Create the exception handler. The exception handler is created during -- the initialization phase of the application. The default implementation -- creates a <b>ASF.Contexts.Exceptions.Exception_Handler</b> object. function Create_Exception_Handler (App : in Application_Factory) return ASF.Contexts.Exceptions.Exception_Handler_Access; -- ------------------------------ -- Application -- ------------------------------ type Application is new ASF.Servlets.Servlet_Registry and ASF.Events.Faces.Actions.Action_Listener with private; type Application_Access is access all Application'Class; -- Get the application view handler. function Get_View_Handler (App : access Application) return access Views.View_Handler'Class; -- Get the lifecycle handler. function Get_Lifecycle_Handler (App : in Application) return ASF.Lifecycles.Lifecycle_Access; -- Get the navigation handler. function Get_Navigation_Handler (App : in Application) return ASF.Navigations.Navigation_Handler_Access; -- Get the permission manager associated with this application. function Get_Security_Manager (App : in Application) return Security.Policies.Policy_Manager_Access; -- Get the action event listener responsible for processing action -- events and triggering the navigation to the next view using the -- navigation handler. function Get_Action_Listener (App : in Application) return ASF.Events.Faces.Actions.Action_Listener_Access; -- Process the action associated with the action event. The action returns -- and outcome which is then passed to the navigation handler to navigate to -- the next view. overriding procedure Process_Action (Listener : in Application; Event : in ASF.Events.Faces.Actions.Action_Event'Class; Context : in out Contexts.Faces.Faces_Context'Class); -- Initialize the application procedure Initialize (App : in out Application; Conf : in Config; Factory : in out Application_Factory'Class); -- 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. procedure Initialize_Components (App : in out Application); -- Initialize the application configuration properties. Properties defined in <b>Conf</b> -- are expanded by using the EL expression resolver. procedure Initialize_Config (App : in out Application; Conf : in out Config); -- Initialize the servlets provided by the application. -- This procedure is called by <b>Initialize</b>. -- It should register the application servlets. procedure Initialize_Servlets (App : in out Application); -- Initialize the filters provided by the application. -- This procedure is called by <b>Initialize</b>. -- It should register the application filters. procedure Initialize_Filters (App : in out Application); -- Finalizes the application, freeing the memory. overriding procedure Finalize (App : in out Application); -- Get the configuration parameter; function Get_Config (App : Application; Param : Config_Param) return String; -- Set a global variable in the global EL contexts. procedure Set_Global (App : in out Application; Name : in String; Value : in String); procedure Set_Global (App : in out Application; Name : in String; Value : in EL.Objects.Object); -- Resolve a global variable and return its value. -- Raises the <b>EL.Functions.No_Variable</b> exception if the variable does not exist. function Get_Global (App : in Application; Name : in Ada.Strings.Unbounded.Unbounded_String; Context : in EL.Contexts.ELContext'Class) return EL.Objects.Object; -- Get the list of supported locales for this application. function Get_Supported_Locales (App : in Application) return Util.Locales.Locale_Array; -- Add the locale to the list of supported locales. procedure Add_Supported_Locale (App : in out Application; Locale : in Util.Locales.Locale); -- Get the default locale defined by the application. function Get_Default_Locale (App : in Application) return Util.Locales.Locale; -- Set the default locale defined by the application. procedure Set_Default_Locale (App : in out Application; Locale : in Util.Locales.Locale); -- Compute the locale that must be used according to the <b>Accept-Language</b> request -- header and the application supported locales. function Calculate_Locale (Handler : in Application; Context : in ASF.Contexts.Faces.Faces_Context'Class) return Util.Locales.Locale; -- Register a bundle and bind it to a facelet variable. procedure Register (App : in out Application; Name : in String; Bundle : in String); -- Register the bean identified by <b>Name</b> and associated with the class <b>Class</b>. -- The class must have been registered by using the <b>Register</b> class operation. -- The scope defines the scope of the bean. procedure Register (App : in out Application; Name : in String; Class : in String; Params : in Parameter_Bean_Ref.Ref; Scope : in Scope_Type := REQUEST_SCOPE); -- Register under the name identified by <b>Name</b> the class instance <b>Class</b>. procedure Register_Class (App : in out Application; Name : in String; Class : in ASF.Beans.Class_Binding_Access); -- Register under the name identified by <b>Name</b> a function to create a bean. -- This is a simplified class registration. procedure Register_Class (App : in out Application; Name : in String; Handler : in ASF.Beans.Create_Bean_Access); -- Create a bean by using the create operation registered for the name procedure Create (App : in Application; Name : in Ada.Strings.Unbounded.Unbounded_String; Context : in EL.Contexts.ELContext'Class; Result : out Util.Beans.Basic.Readonly_Bean_Access; Scope : out Scope_Type); -- Add a converter in the application. The converter is referenced by -- the specified name in the XHTML files. procedure Add_Converter (App : in out Application; Name : in String; Converter : in ASF.Converters.Converter_Access); -- Register a binding library in the factory. procedure Add_Components (App : in out Application; Bindings : in ASF.Factory.Factory_Bindings_Access); -- Closes the application procedure Close (App : in out Application); -- Set the current faces context before processing a view. procedure Set_Context (App : in out Application; Context : in ASF.Contexts.Faces.Faces_Context_Access); -- Execute the lifecycle phases on the faces context. procedure Execute_Lifecycle (App : in Application; Context : in out ASF.Contexts.Faces.Faces_Context'Class); -- Dispatch the request received on a page. procedure Dispatch (App : in out Application; Page : in String; Request : in out ASF.Requests.Request'Class; Response : in out ASF.Responses.Response'Class); -- Dispatch a bean action request. -- 1. Find the bean object identified by <b>Name</b>, create it if necessary. -- 2. Resolve the bean method identified by <b>Operation</b>. -- 3. If the method is an action method (see ASF.Events.Actions), call that method. -- 4. Using the outcome action result, decide using the navigation handler what -- is the result view. -- 5. Render the result view resolved by the navigation handler. procedure Dispatch (App : in out Application; Name : in String; Operation : in String; Request : in out ASF.Requests.Request'Class; Response : in out ASF.Responses.Response'Class; Prepare : access procedure (Bean : access Util.Beans.Basic.Bean'Class)); -- Find the converter instance that was registered under the given name. -- Returns null if no such converter exist. function Find (App : in Application; Name : in EL.Objects.Object) return ASF.Converters.Converter_Access; -- Find the validator instance that was registered under the given name. -- Returns null if no such validator exist. function Find_Validator (App : in Application; Name : in EL.Objects.Object) return ASF.Validators.Validator_Access; -- Register some functions generic with procedure Set_Functions (Mapper : in out EL.Functions.Function_Mapper'Class); procedure Register_Functions (App : in out Application'Class); -- Register some bean definitions. generic with procedure Set_Beans (Factory : in out ASF.Beans.Bean_Factory); procedure Register_Beans (App : in out Application'Class); -- Load the resource bundle identified by the <b>Name</b> and for the given -- <b>Locale</b>. procedure Load_Bundle (App : in out Application; Name : in String; Locale : in String; Bundle : out ASF.Locales.Bundle); private type Application_Factory is tagged limited null record; type Application is new ASF.Servlets.Servlet_Registry and ASF.Events.Faces.Actions.Action_Listener with record View : aliased ASF.Applications.Views.View_Handler; Lifecycle : ASF.Lifecycles.Lifecycle_Access; Factory : aliased ASF.Beans.Bean_Factory; Locales : ASF.Locales.Factory; Globals : aliased EL.Variables.Default.Default_Variable_Mapper; Functions : aliased EL.Functions.Default.Default_Function_Mapper; -- The component factory Components : aliased ASF.Factory.Component_Factory; -- The action listener. Action_Listener : ASF.Events.Faces.Actions.Action_Listener_Access; -- The navigation handler. Navigation : ASF.Navigations.Navigation_Handler_Access := null; -- The permission manager. Permissions : Security.Policies.Policy_Manager_Access := null; end record; end ASF.Applications.Main;
Rename Permission_Manager into Security_Manager
Rename Permission_Manager into Security_Manager
Ada
apache-2.0
stcarrez/ada-asf,stcarrez/ada-asf,stcarrez/ada-asf
7468a01bb332e150672485b7cb13d3f5d68a3094
src/security-policies-roles.ads
src/security-policies-roles.ads
----------------------------------------------------------------------- -- 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 Ada.Strings.Unbounded; -- == Role Based Security Policy == -- The <tt>Security.Policies.Roles</tt> package implements a role based security policy. -- In this policy, users are assigned one or several roles and permissions are -- associated with roles. A permission is granted if the user has one of the roles required -- by the permission. -- -- === Policy creation === -- An instance of the <tt>Role_Policy</tt> must be created and registered in the policy manager. -- Get or declare the following variables: -- -- Manager : Security.Policies.Policy_Manager; -- Policy : Security.Policies.Roles.Role_Policy_Access; -- -- Create the role policy and register it in the policy manager as follows: -- -- Policy := new Role_Policy; -- Manager.Add_Policy (Policy.all'Access); -- -- === Policy Configuration === -- A role is represented by a name in security configuration files. A role based permission -- is associated with a list of roles. The permission is granted if the user has one of these -- roles. When the role based policy is registered in the policy manager, the following -- XML configuration is used: -- -- <policy-rules> -- <security-role> -- <role-name>admin</role-name> -- </security-role> -- <security-role> -- <role-name>manager</role-name> -- </security-role> -- <role-permission> -- <name>create-workspace</name> -- <role>admin</role> -- <role>manager</role> -- </role-permission> -- ... -- </policy-rules> -- -- This definition declares two roles: <tt>admin</tt> and <tt>manager</tt> -- It defines a permission <b>create-workspace</b> that will be granted if the -- user has either the <b>admin</b> or the <b>manager</b> role. -- -- Each role is identified by a name in the configuration file. It is represented by -- a <tt>Role_Type</tt>. To provide an efficient implementation, the <tt>Role_Type</tt> -- is represented as an integer with a limit of 64 different roles. -- -- === Assigning roles to users === -- A <tt>Security_Context</tt> must be associated with a set of roles before checking the -- permission. This is done by using the <tt>Set_Role_Context</tt> operation: -- -- Security.Policies.Roles.Set_Role_Context (Security.Contexts.Current, "admin"); -- package Security.Policies.Roles is NAME : constant String := "Role-Policy"; -- Each role is represented by a <b>Role_Type</b> number to provide a fast -- and efficient role check. type Role_Type is new Natural range 0 .. 63; for Role_Type'Size use 8; type Role_Type_Array is array (Positive range <>) of Role_Type; type Role_Name_Array is array (Positive range <>) of Ada.Strings.Unbounded.String_Access; -- The <b>Role_Map</b> represents a set of roles which are assigned to a user. -- Each role is represented by a boolean in the map. The implementation is limited -- to 64 roles (the number of different permissions can be higher). type Role_Map is array (Role_Type'Range) of Boolean; pragma Pack (Role_Map); -- Get the number of roles set in the map. function Get_Count (Map : in Role_Map) return Natural; -- ------------------------------ -- Role principal context -- ------------------------------ -- The <tt>Role_Principal_Context</tt> interface must be implemented by the user -- <tt>Principal</tt> to be able to use the role based policy. The role based policy -- controller will first check that the <tt>Principal</tt> implements that interface. -- It uses the <tt>Get_Roles</tt> function to get the current roles assigned to the user. type Role_Principal_Context is limited interface; function Get_Roles (User : in Role_Principal_Context) return Role_Map is abstract; -- ------------------------------ -- Policy context -- ------------------------------ -- The <b>Role_Policy_Context</b> gives security context information that the role -- based policy can use to verify the permission. type Role_Policy_Context is new Policy_Context with record Roles : Role_Map; end record; type Role_Policy_Context_Access is access all Role_Policy_Context'Class; -- Set the roles which are assigned to the user in the security context. -- The role policy will use these roles to verify a permission. procedure Set_Role_Context (Context : in out Security.Contexts.Security_Context'Class; Roles : in Role_Map); -- Set the roles which are assigned to the user in the security context. -- The role policy will use these roles to verify a permission. procedure Set_Role_Context (Context : in out Security.Contexts.Security_Context'Class; Roles : in String); -- ------------------------------ -- Role based policy -- ------------------------------ type Role_Policy is new Policy with private; type Role_Policy_Access is access all Role_Policy'Class; Invalid_Name : exception; -- Get the policy name. overriding function Get_Name (From : in Role_Policy) return String; -- Find the role type associated with the role name identified by <b>Name</b>. -- Raises <b>Invalid_Name</b> if there is no role type. function Find_Role (Manager : in Role_Policy; Name : in String) return Role_Type; -- Get the role name. function Get_Role_Name (Manager : in Role_Policy; Role : in Role_Type) return String; -- Get the roles that grant the given permission. function Get_Grants (Manager : in Role_Policy; Permission : in Permissions.Permission_Index) return Role_Map; -- Get the list of role names that are defined by the role map. function Get_Role_Names (Manager : in Role_Policy; Map : in Role_Map) return Role_Name_Array; -- Create a role procedure Create_Role (Manager : in out Role_Policy; Name : in String; Role : out Role_Type); -- Get or add a role type for the given name. procedure Add_Role_Type (Manager : in out Role_Policy; Name : in String; Result : out Role_Type); -- Set the roles specified in the <tt>Roles</tt> parameter. Each role is represented by -- its name and multiple roles are separated by ','. -- Raises Invalid_Name if a role was not found. procedure Set_Roles (Manager : in Role_Policy; Roles : in String; Into : out Role_Map); -- Setup the XML parser to read the <b>role-permission</b> description. overriding procedure Prepare_Config (Policy : in out Role_Policy; Reader : in out Util.Serialize.IO.XML.Parser); -- Finalize the policy manager. overriding procedure Finalize (Policy : in out Role_Policy); -- Get the role policy associated with the given policy manager. -- Returns the role policy instance or null if it was not registered in the policy manager. function Get_Role_Policy (Manager : in Security.Policies.Policy_Manager'Class) return Role_Policy_Access; private -- Array to map a permission index to a list of roles that are granted the permission. type Permission_Role_Array is array (Permission_Index) of Role_Map; type Role_Map_Name_Array is array (Role_Type'Range) of Ada.Strings.Unbounded.String_Access; type Role_Policy is new Policy with record Names : Role_Map_Name_Array := (others => null); Next_Role : Role_Type := Role_Type'First; Name : Util.Beans.Objects.Object; Roles : Role_Type_Array (1 .. Integer (Role_Type'Last)) := (others => 0); Count : Natural := 0; -- The Grants array indicates for each permission the list of roles -- that are granted the permission. This array allows a O(1) lookup. -- The implementation is limited to 256 permissions and 64 roles so this array uses 2K. -- The default is that no role is assigned to the permission. Grants : Permission_Role_Array := (others => (others => False)); end record; 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 Ada.Strings.Unbounded; -- == Role Based Security Policy == -- The <tt>Security.Policies.Roles</tt> package implements a role based security policy. -- In this policy, users are assigned one or several roles and permissions are -- associated with roles. A permission is granted if the user has one of the roles required -- by the permission. -- -- === Policy creation === -- An instance of the <tt>Role_Policy</tt> must be created and registered in the policy manager. -- Get or declare the following variables: -- -- Manager : Security.Policies.Policy_Manager; -- Policy : Security.Policies.Roles.Role_Policy_Access; -- -- Create the role policy and register it in the policy manager as follows: -- -- Policy := new Role_Policy; -- Manager.Add_Policy (Policy.all'Access); -- -- === Policy Configuration === -- A role is represented by a name in security configuration files. A role based permission -- is associated with a list of roles. The permission is granted if the user has one of these -- roles. When the role based policy is registered in the policy manager, the following -- XML configuration is used: -- -- <policy-rules> -- <security-role> -- <role-name>admin</role-name> -- </security-role> -- <security-role> -- <role-name>manager</role-name> -- </security-role> -- <role-permission> -- <name>create-workspace</name> -- <role>admin</role> -- <role>manager</role> -- </role-permission> -- ... -- </policy-rules> -- -- This definition declares two roles: <tt>admin</tt> and <tt>manager</tt> -- It defines a permission <b>create-workspace</b> that will be granted if the -- user has either the <b>admin</b> or the <b>manager</b> role. -- -- Each role is identified by a name in the configuration file. It is represented by -- a <tt>Role_Type</tt>. To provide an efficient implementation, the <tt>Role_Type</tt> -- is represented as an integer with a limit of 64 different roles. -- -- === Assigning roles to users === -- A <tt>Security_Context</tt> must be associated with a set of roles before checking the -- permission. This is done by using the <tt>Set_Role_Context</tt> operation: -- -- Security.Policies.Roles.Set_Role_Context (Security.Contexts.Current, "admin"); -- package Security.Policies.Roles is NAME : constant String := "Role-Policy"; -- Each role is represented by a <b>Role_Type</b> number to provide a fast -- and efficient role check. type Role_Type is new Natural range 0 .. 63; for Role_Type'Size use 8; type Role_Type_Array is array (Positive range <>) of Role_Type; type Role_Name_Array is array (Positive range <>) of Ada.Strings.Unbounded.String_Access; -- The <b>Role_Map</b> represents a set of roles which are assigned to a user. -- Each role is represented by a boolean in the map. The implementation is limited -- to 64 roles (the number of different permissions can be higher). type Role_Map is array (Role_Type'Range) of Boolean; pragma Pack (Role_Map); -- Get the number of roles set in the map. function Get_Count (Map : in Role_Map) return Natural; -- Return the list of role names separated by ','. function To_String (List : in Role_Name_Array) return String; -- ------------------------------ -- Role principal context -- ------------------------------ -- The <tt>Role_Principal_Context</tt> interface must be implemented by the user -- <tt>Principal</tt> to be able to use the role based policy. The role based policy -- controller will first check that the <tt>Principal</tt> implements that interface. -- It uses the <tt>Get_Roles</tt> function to get the current roles assigned to the user. type Role_Principal_Context is limited interface; function Get_Roles (User : in Role_Principal_Context) return Role_Map is abstract; -- ------------------------------ -- Policy context -- ------------------------------ -- The <b>Role_Policy_Context</b> gives security context information that the role -- based policy can use to verify the permission. type Role_Policy_Context is new Policy_Context with record Roles : Role_Map; end record; type Role_Policy_Context_Access is access all Role_Policy_Context'Class; -- Set the roles which are assigned to the user in the security context. -- The role policy will use these roles to verify a permission. procedure Set_Role_Context (Context : in out Security.Contexts.Security_Context'Class; Roles : in Role_Map); -- Set the roles which are assigned to the user in the security context. -- The role policy will use these roles to verify a permission. procedure Set_Role_Context (Context : in out Security.Contexts.Security_Context'Class; Roles : in String); -- ------------------------------ -- Role based policy -- ------------------------------ type Role_Policy is new Policy with private; type Role_Policy_Access is access all Role_Policy'Class; Invalid_Name : exception; -- Get the policy name. overriding function Get_Name (From : in Role_Policy) return String; -- Find the role type associated with the role name identified by <b>Name</b>. -- Raises <b>Invalid_Name</b> if there is no role type. function Find_Role (Manager : in Role_Policy; Name : in String) return Role_Type; -- Get the role name. function Get_Role_Name (Manager : in Role_Policy; Role : in Role_Type) return String; -- Get the roles that grant the given permission. function Get_Grants (Manager : in Role_Policy; Permission : in Permissions.Permission_Index) return Role_Map; -- Get the list of role names that are defined by the role map. function Get_Role_Names (Manager : in Role_Policy; Map : in Role_Map) return Role_Name_Array; -- Create a role procedure Create_Role (Manager : in out Role_Policy; Name : in String; Role : out Role_Type); -- Get or add a role type for the given name. procedure Add_Role_Type (Manager : in out Role_Policy; Name : in String; Result : out Role_Type); -- Set the roles specified in the <tt>Roles</tt> parameter. Each role is represented by -- its name and multiple roles are separated by ','. -- Raises Invalid_Name if a role was not found. procedure Set_Roles (Manager : in Role_Policy; Roles : in String; Into : out Role_Map); -- Setup the XML parser to read the <b>role-permission</b> description. overriding procedure Prepare_Config (Policy : in out Role_Policy; Reader : in out Util.Serialize.IO.XML.Parser); -- Finalize the policy manager. overriding procedure Finalize (Policy : in out Role_Policy); -- Get the role policy associated with the given policy manager. -- Returns the role policy instance or null if it was not registered in the policy manager. function Get_Role_Policy (Manager : in Security.Policies.Policy_Manager'Class) return Role_Policy_Access; private -- Array to map a permission index to a list of roles that are granted the permission. type Permission_Role_Array is array (Permission_Index) of Role_Map; type Role_Map_Name_Array is array (Role_Type'Range) of Ada.Strings.Unbounded.String_Access; type Role_Policy is new Policy with record Names : Role_Map_Name_Array := (others => null); Next_Role : Role_Type := Role_Type'First; Name : Util.Beans.Objects.Object; Roles : Role_Type_Array (1 .. Integer (Role_Type'Last)) := (others => 0); Count : Natural := 0; -- The Grants array indicates for each permission the list of roles -- that are granted the permission. This array allows a O(1) lookup. -- The implementation is limited to 256 permissions and 64 roles so this array uses 2K. -- The default is that no role is assigned to the permission. Grants : Permission_Role_Array := (others => (others => False)); end record; end Security.Policies.Roles;
Declare the To_String function to convert a Role_Map into a printable string
Declare the To_String function to convert a Role_Map into a printable string
Ada
apache-2.0
stcarrez/ada-security
077ac9354499952b3e5d9f4b97128cdabead2646
src/util-beans-objects-maps.ads
src/util-beans-objects-maps.ads
----------------------------------------------------------------------- -- Util.Beans.Objects.Maps -- Object maps -- Copyright (C) 2010, 2011, 2012, 2017 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Containers.Indefinite_Hashed_Maps; with Ada.Strings.Hash; with Util.Beans.Basic; package Util.Beans.Objects.Maps is package Maps is new Ada.Containers.Indefinite_Hashed_Maps (Key_Type => String, Element_Type => Object, Hash => Ada.Strings.Hash, Equivalent_Keys => "="); subtype Cursor is Maps.Cursor; subtype Map is Maps.Map; -- Make all the Maps operations available (a kind of 'use Maps' for anybody). function Length (Container : in Map) return Ada.Containers.Count_Type renames Maps.Length; function Is_Empty (Container : in Map) return Boolean renames Maps.Is_Empty; procedure Clear (Container : in out Map) renames Maps.Clear; function Key (Position : Cursor) return String renames Maps.Key; procedure Include (Container : in out Map; Key : in String; New_Item : in Object) renames Maps.Include; procedure Query_Element (Position : in Cursor; Process : not null access procedure (Key : String; Element : Object)) renames Maps.Query_Element; function Has_Element (Position : Cursor) return Boolean renames Maps.Has_Element; function Element (Position : Cursor) return Object renames Maps.Element; procedure Next (Position : in out Cursor) renames Maps.Next; function Next (Position : Cursor) return Cursor renames Maps.Next; function Equivalent_Keys (Left, Right : Cursor) return Boolean renames Maps.Equivalent_Keys; function Equivalent_Keys (Left : Cursor; Right : String) return Boolean renames Maps.Equivalent_Keys; function Equivalent_Keys (Left : String; Right : Cursor) return Boolean renames Maps.Equivalent_Keys; function Copy (Source : Maps.Map; Capacity : in Ada.Containers.Count_Type) return Maps.Map renames Maps.Copy; -- ------------------------------ -- Map Bean -- ------------------------------ -- The <b>Map_Bean</b> is a map of objects that also exposes the <b>Bean</b> interface. -- This allows the map to be available and accessed from an Object instance. type Map_Bean is new Maps.Map and Util.Beans.Basic.Bean with private; type Map_Bean_Access is access all Map_Bean'Class; -- Get the value identified by the name. -- If the name cannot be found, the method should return the Null object. function Get_Value (From : in Map_Bean; Name : in String) return Object; -- Set the value identified by the name. -- If the map contains the given name, the value changed. -- Otherwise name is added to the map and the value associated with it. procedure Set_Value (From : in out Map_Bean; Name : in String; Value : in Object); -- Create an object that contains a <tt>Map_Bean</tt> instance. function Create return Object; private type Map_Bean is new Maps.Map and Util.Beans.Basic.Bean with null record; end Util.Beans.Objects.Maps;
----------------------------------------------------------------------- -- Util.Beans.Objects.Maps -- Object maps -- Copyright (C) 2010, 2011, 2012, 2017 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Containers.Indefinite_Hashed_Maps; with Ada.Strings.Hash; with Util.Beans.Basic; package Util.Beans.Objects.Maps is package Maps is new Ada.Containers.Indefinite_Hashed_Maps (Key_Type => String, Element_Type => Object, Hash => Ada.Strings.Hash, Equivalent_Keys => "="); subtype Cursor is Maps.Cursor; subtype Map is Maps.Map; -- Make all the Maps operations available (a kind of 'use Maps' for anybody). function Length (Container : in Map) return Ada.Containers.Count_Type renames Maps.Length; function Is_Empty (Container : in Map) return Boolean renames Maps.Is_Empty; procedure Clear (Container : in out Map) renames Maps.Clear; function Key (Position : Cursor) return String renames Maps.Key; procedure Include (Container : in out Map; Key : in String; New_Item : in Object) renames Maps.Include; procedure Query_Element (Position : in Cursor; Process : not null access procedure (Key : String; Element : Object)) renames Maps.Query_Element; function Has_Element (Position : Cursor) return Boolean renames Maps.Has_Element; function Element (Position : Cursor) return Object renames Maps.Element; procedure Next (Position : in out Cursor) renames Maps.Next; function Next (Position : Cursor) return Cursor renames Maps.Next; function Equivalent_Keys (Left, Right : Cursor) return Boolean renames Maps.Equivalent_Keys; function Equivalent_Keys (Left : Cursor; Right : String) return Boolean renames Maps.Equivalent_Keys; function Equivalent_Keys (Left : String; Right : Cursor) return Boolean renames Maps.Equivalent_Keys; function Copy (Source : Maps.Map; Capacity : in Ada.Containers.Count_Type) return Maps.Map renames Maps.Copy; -- ------------------------------ -- Map Bean -- ------------------------------ -- The <b>Map_Bean</b> is a map of objects that also exposes the <b>Bean</b> interface. -- This allows the map to be available and accessed from an Object instance. type Map_Bean is new Maps.Map and Util.Beans.Basic.Bean with private; type Map_Bean_Access is access all Map_Bean'Class; -- Get the value identified by the name. -- If the name cannot be found, the method should return the Null object. function Get_Value (From : in Map_Bean; Name : in String) return Object; -- Set the value identified by the name. -- If the map contains the given name, the value changed. -- Otherwise name is added to the map and the value associated with it. procedure Set_Value (From : in out Map_Bean; Name : in String; Value : in Object); -- Create an object that contains a <tt>Map_Bean</tt> instance. function Create return Object; -- Iterate over the members of the map. procedure Iterate (From : in Object; Process : not null access procedure (Name : in String; Item : in Object)); private type Map_Bean is new Maps.Map and Util.Beans.Basic.Bean with null record; end Util.Beans.Objects.Maps;
Declare Iterate procedure
Declare Iterate procedure
Ada
apache-2.0
stcarrez/ada-util,stcarrez/ada-util
4444d16f0743a3047320d979439b3f6291c09529
regtests/babel-base-users-tests.ads
regtests/babel-base-users-tests.ads
----------------------------------------------------------------------- -- 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.Tests; package Babel.Base.Users.Tests is procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite); type Test is new Util.Tests.Test with null record; -- Test the Find function resolving some existing user. procedure Test_Find (T : in out Test); -- Test the Get_Name operation. procedure Test_Get_Name (T : in out Test); -- Test the Get_Uid operation. procedure Test_Get_Uid (T : in out Test); 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.Tests; package Babel.Base.Users.Tests is procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite); type Test is new Util.Tests.Test with null record; -- Test the Find function resolving some existing user. procedure Test_Find (T : in out Test); -- Test the Get_Name operation. procedure Test_Get_Name (T : in out Test); -- Test the Get_Uid operation. procedure Test_Get_Uid (T : in out Test); -- Test the Get_Group operation. procedure Test_Get_Group (T : in out Test); end Babel.Base.Users.Tests;
Declare the Test_Get_Group procedure
Declare the Test_Get_Group procedure
Ada
apache-2.0
stcarrez/babel
13762ac05b58fbc402ae723de1f8a4f53b815e98
awa/plugins/awa-questions/src/awa-questions-beans.adb
awa/plugins/awa-questions/src/awa-questions-beans.adb
----------------------------------------------------------------------- -- awa-questions-beans -- Beans for module questions -- 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 ADO.Queries; with ADO.Utils; with ADO.Sessions; with ADO.Sessions.Entities; with Util.Beans.Lists.Strings; with AWA.Tags.Modules; with AWA.Services.Contexts; package body AWA.Questions.Beans is package ASC renames AWA.Services.Contexts; -- ------------------------------ -- Get the value identified by the name. -- ------------------------------ overriding function Get_Value (From : in Question_Bean; Name : in String) return Util.Beans.Objects.Object is begin if Name = "tags" then return Util.Beans.Objects.To_Object (From.Tags_Bean, Util.Beans.Objects.STATIC); elsif From.Is_Null then return Util.Beans.Objects.Null_Object; else return AWA.Questions.Models.Question_Bean (From).Get_Value (Name); end if; end Get_Value; -- ------------------------------ -- Set the value identified by the name. -- ------------------------------ overriding procedure Set_Value (From : in out Question_Bean; Name : in String; Value : in Util.Beans.Objects.Object) is begin if Name = "title" then From.Set_Title (Util.Beans.Objects.To_String (Value)); elsif Name = "description" then From.Set_Description (Util.Beans.Objects.To_String (Value)); elsif Name = "id" and not Util.Beans.Objects.Is_Empty (Value) then declare Ctx : constant ASC.Service_Context_Access := AWA.Services.Contexts.Current; DB : constant ADO.Sessions.Session := AWA.Services.Contexts.Get_Session (Ctx); Id : constant ADO.Identifier := ADO.Utils.To_Identifier (Value); begin From.Service.Load_Question (From, Id); From.Tags.Load_Tags (DB, Id); end; end if; end Set_Value; -- ------------------------------ -- Create or save the question. -- ------------------------------ procedure Save (Bean : in out Question_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is pragma Unreferenced (Outcome); begin Bean.Service.Save_Question (Bean); Bean.Tags.Update_Tags (Bean.Get_Id); end Save; -- ------------------------------ -- Delete the question. -- ------------------------------ procedure Delete (Bean : in out Question_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is pragma Unreferenced (Outcome); begin Bean.Service.Delete_Question (Bean); end Delete; -- ------------------------------ -- Create the Question_Bean bean instance. -- ------------------------------ function Create_Question_Bean (Module : in AWA.Questions.Modules.Question_Module_Access) return Util.Beans.Basic.Readonly_Bean_Access is Object : constant Question_Bean_Access := new Question_Bean; begin Object.Service := Module; Object.Tags_Bean := Object.Tags'Access; Object.Tags.Set_Entity_Type (AWA.Questions.Models.QUESTION_TABLE); Object.Tags.Set_Permission ("question-edit"); return Object.all'Access; end Create_Question_Bean; -- Get the value identified by the name. overriding function Get_Value (From : in Answer_Bean; Name : in String) return Util.Beans.Objects.Object is begin if Name = "question_id" then return Util.Beans.Objects.To_Object (Long_Long_Integer (From.Question.Get_Id)); elsif From.Is_Null then return Util.Beans.Objects.Null_Object; else return AWA.Questions.Models.Answer_Bean (From).Get_Value (Name); end if; end Get_Value; -- ------------------------------ -- Set the value identified by the name. -- ------------------------------ overriding procedure Set_Value (From : in out Answer_Bean; Name : in String; Value : in Util.Beans.Objects.Object) is begin if Name = "id" and not Util.Beans.Objects.Is_Empty (Value) then From.Service.Load_Answer (From, From.Question, ADO.Utils.To_Identifier (Value)); elsif Name = "answer" then From.Set_Answer (Util.Beans.Objects.To_String (Value)); elsif Name = "question_id" and not Util.Beans.Objects.Is_Null (Value) then From.Service.Load_Question (From.Question, ADO.Utils.To_Identifier (Value)); end if; end Set_Value; -- ------------------------------ -- Create or save the answer. -- ------------------------------ procedure Save (Bean : in out Answer_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is pragma Unreferenced (Outcome); begin Bean.Service.Save_Answer (Question => Bean.Question, Answer => Bean); end Save; -- ------------------------------ -- Delete the question. -- ------------------------------ procedure Delete (Bean : in out Answer_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is pragma Unreferenced (Outcome); begin Bean.Service.Delete_Answer (Answer => Bean); end Delete; -- ------------------------------ -- Create the answer bean instance. -- ------------------------------ function Create_Answer_Bean (Module : in AWA.Questions.Modules.Question_Module_Access) return Util.Beans.Basic.Readonly_Bean_Access is Object : constant Answer_Bean_Access := new Answer_Bean; begin Object.Service := Module; return Object.all'Access; end Create_Answer_Bean; -- ------------------------------ -- Get the value identified by the name. -- ------------------------------ overriding function Get_Value (From : in Question_List_Bean; Name : in String) return Util.Beans.Objects.Object is Pos : Natural; begin if Name = "tags" then Pos := From.Questions.Get_Row_Index; if Pos = 0 then return Util.Beans.Objects.Null_Object; end if; declare Item : constant Models.Question_Info := From.Questions.List.Element (Pos - 1); begin return From.Tags.Get_Tags (Item.Id); end; elsif Name = "questions" then return Util.Beans.Objects.To_Object (Value => From.Questions_Bean, Storage => Util.Beans.Objects.STATIC); else return From.Questions.Get_Value (Name); end if; end Get_Value; -- ------------------------------ -- Set the value identified by the name. -- ------------------------------ overriding procedure Set_Value (From : in out Question_List_Bean; Name : in String; Value : in Util.Beans.Objects.Object) is begin if Name = "tag" then From.Tag := Util.Beans.Objects.To_Unbounded_String (Value); From.Load_List; end if; end Set_Value; -- ------------------------------ -- Load the list of question. If a tag was set, filter the list of questions with the tag. -- ------------------------------ procedure Load_List (Into : in out Question_List_Bean) is use AWA.Questions.Models; use AWA.Services; use type ADO.Identifier; Session : ADO.Sessions.Session := Into.Service.Get_Session; Query : ADO.Queries.Context; Tag_Id : ADO.Identifier; begin AWA.Tags.Modules.Find_Tag_Id (Session, Ada.Strings.Unbounded.To_String (Into.Tag), Tag_Id); if Tag_Id /= ADO.NO_IDENTIFIER then Query.Set_Query (AWA.Questions.Models.Query_Question_Tag_List); Query.Bind_Param (Name => "tag", Value => Tag_Id); else Query.Set_Query (AWA.Questions.Models.Query_Question_List); end if; ADO.Sessions.Entities.Bind_Param (Params => Query, Name => "entity_type", Table => AWA.Questions.Models.QUESTION_TABLE, Session => Session); AWA.Questions.Models.List (Into.Questions, Session, Query); declare List : ADO.Utils.Identifier_Vector; Iter : Question_Info_Vectors.Cursor := Into.Questions.List.First; begin while Question_Info_Vectors.Has_Element (Iter) loop List.Append (Question_Info_Vectors.Element (Iter).Id); Question_Info_Vectors.Next (Iter); end loop; Into.Tags.Load_Tags (Session, AWA.Questions.Models.QUESTION_TABLE.Table.all, List); end; end Load_List; -- ------------------------------ -- Create the Question_Info_List_Bean bean instance. -- ------------------------------ function Create_Question_List_Bean (Module : in AWA.Questions.Modules.Question_Module_Access) return Util.Beans.Basic.Readonly_Bean_Access is use AWA.Questions.Models; use AWA.Services; Object : constant Question_List_Bean_Access := new Question_List_Bean; -- Session : ADO.Sessions.Session := Module.Get_Session; -- Query : ADO.Queries.Context; begin Object.Service := Module; Object.Questions_Bean := Object.Questions'Unchecked_Access; -- Query.Set_Query (AWA.Questions.Models.Query_Question_List); -- ADO.Sessions.Entities.Bind_Param (Params => Query, -- Name => "entity_type", -- Table => AWA.Questions.Models.QUESTION_TABLE, -- Session => Session); -- AWA.Questions.Models.List (Object.Questions, Session, Query); Object.Load_List; return Object.all'Access; end Create_Question_List_Bean; -- ------------------------------ -- Get the value identified by the name. -- ------------------------------ overriding function Get_Value (From : in Question_Display_Bean; Name : in String) return Util.Beans.Objects.Object is begin if Name = "answers" then return Util.Beans.Objects.To_Object (Value => From.Answer_List_Bean, Storage => Util.Beans.Objects.STATIC); elsif Name = "question" then return Util.Beans.Objects.To_Object (Value => From.Question_Bean, Storage => Util.Beans.Objects.STATIC); elsif Name = "tags" then return Util.Beans.Objects.To_Object (Value => From.Tags_Bean, Storage => Util.Beans.Objects.STATIC); else return Util.Beans.Objects.Null_Object; end if; end Get_Value; -- ------------------------------ -- Set the value identified by the name. -- ------------------------------ overriding procedure Set_Value (From : in out Question_Display_Bean; Name : in String; Value : in Util.Beans.Objects.Object) is begin if Name = "id" and not Util.Beans.Objects.Is_Empty (Value) then declare package ASC renames AWA.Services.Contexts; use AWA.Questions.Models; use AWA.Services; Session : ADO.Sessions.Session := From.Service.Get_Session; Query : ADO.Queries.Context; List : AWA.Questions.Models.Question_Display_Info_List_Bean; Ctx : constant ASC.Service_Context_Access := ASC.Current; Id : constant ADO.Identifier := ADO.Utils.To_Identifier (Value); begin Query.Set_Query (AWA.Questions.Models.Query_Question_Info); Query.Bind_Param ("question_id", Id); Query.Bind_Param ("user_id", Ctx.Get_User_Identifier); ADO.Sessions.Entities.Bind_Param (Params => Query, Name => "entity_type", Table => AWA.Questions.Models.QUESTION_TABLE, Session => Session); AWA.Questions.Models.List (List, Session, Query); if not List.List.Is_Empty then From.Question := List.List.Element (0); end if; Query.Clear; Query.Bind_Param ("question_id", Util.Beans.Objects.To_Integer (Value)); Query.Bind_Param ("user_id", Ctx.Get_User_Identifier); ADO.Sessions.Entities.Bind_Param (Params => Query, Name => "entity_type", Table => AWA.Questions.Models.ANSWER_TABLE, Session => Session); Query.Set_Query (AWA.Questions.Models.Query_Answer_List); AWA.Questions.Models.List (From.Answer_List, Session, Query); -- Load the tags if any. From.Tags.Load_Tags (Session, Id); end; end if; end Set_Value; -- ------------------------------ -- Create the Question_Display_Bean bean instance. -- ------------------------------ function Create_Question_Display_Bean (Module : in AWA.Questions.Modules.Question_Module_Access) return Util.Beans.Basic.Readonly_Bean_Access is Object : constant Question_Display_Bean_Access := new Question_Display_Bean; begin Object.Service := Module; Object.Question_Bean := Object.Question'Access; Object.Answer_List_Bean := Object.Answer_List'Access; Object.Tags_Bean := Object.Tags'Access; Object.Tags.Set_Entity_Type (AWA.Questions.Models.QUESTION_TABLE); return Object.all'Access; end Create_Question_Display_Bean; end AWA.Questions.Beans;
----------------------------------------------------------------------- -- awa-questions-beans -- Beans for module questions -- 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 ADO.Queries; with ADO.Utils; with ADO.Sessions; with ADO.Sessions.Entities; with Util.Beans.Lists.Strings; with AWA.Tags.Modules; with AWA.Services.Contexts; package body AWA.Questions.Beans is package ASC renames AWA.Services.Contexts; -- ------------------------------ -- Get the value identified by the name. -- ------------------------------ overriding function Get_Value (From : in Question_Bean; Name : in String) return Util.Beans.Objects.Object is begin if Name = "tags" then return Util.Beans.Objects.To_Object (From.Tags_Bean, Util.Beans.Objects.STATIC); elsif From.Is_Null then return Util.Beans.Objects.Null_Object; else return AWA.Questions.Models.Question_Bean (From).Get_Value (Name); end if; end Get_Value; -- ------------------------------ -- Set the value identified by the name. -- ------------------------------ overriding procedure Set_Value (From : in out Question_Bean; Name : in String; Value : in Util.Beans.Objects.Object) is begin if Name = "title" then From.Set_Title (Util.Beans.Objects.To_String (Value)); elsif Name = "description" then From.Set_Description (Util.Beans.Objects.To_String (Value)); elsif Name = "id" and not Util.Beans.Objects.Is_Empty (Value) then declare Ctx : constant ASC.Service_Context_Access := AWA.Services.Contexts.Current; DB : constant ADO.Sessions.Session := AWA.Services.Contexts.Get_Session (Ctx); Id : constant ADO.Identifier := ADO.Utils.To_Identifier (Value); begin From.Service.Load_Question (From, Id); From.Tags.Load_Tags (DB, Id); end; end if; end Set_Value; -- ------------------------------ -- Create or save the question. -- ------------------------------ procedure Save (Bean : in out Question_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is pragma Unreferenced (Outcome); begin Bean.Service.Save_Question (Bean); Bean.Tags.Update_Tags (Bean.Get_Id); end Save; -- ------------------------------ -- Delete the question. -- ------------------------------ procedure Delete (Bean : in out Question_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is pragma Unreferenced (Outcome); begin Bean.Service.Delete_Question (Bean); end Delete; -- ------------------------------ -- Create the Question_Bean bean instance. -- ------------------------------ function Create_Question_Bean (Module : in AWA.Questions.Modules.Question_Module_Access) return Util.Beans.Basic.Readonly_Bean_Access is Object : constant Question_Bean_Access := new Question_Bean; begin Object.Service := Module; Object.Tags_Bean := Object.Tags'Access; Object.Tags.Set_Entity_Type (AWA.Questions.Models.QUESTION_TABLE); Object.Tags.Set_Permission ("question-edit"); return Object.all'Access; end Create_Question_Bean; -- Get the value identified by the name. overriding function Get_Value (From : in Answer_Bean; Name : in String) return Util.Beans.Objects.Object is begin if Name = "question_id" then return Util.Beans.Objects.To_Object (Long_Long_Integer (From.Question.Get_Id)); elsif From.Is_Null then return Util.Beans.Objects.Null_Object; else return AWA.Questions.Models.Answer_Bean (From).Get_Value (Name); end if; end Get_Value; -- ------------------------------ -- Set the value identified by the name. -- ------------------------------ overriding procedure Set_Value (From : in out Answer_Bean; Name : in String; Value : in Util.Beans.Objects.Object) is begin if Name = "id" and not Util.Beans.Objects.Is_Empty (Value) then From.Service.Load_Answer (From, From.Question, ADO.Utils.To_Identifier (Value)); elsif Name = "answer" then From.Set_Answer (Util.Beans.Objects.To_String (Value)); elsif Name = "question_id" and not Util.Beans.Objects.Is_Null (Value) then From.Service.Load_Question (From.Question, ADO.Utils.To_Identifier (Value)); end if; end Set_Value; -- ------------------------------ -- Create or save the answer. -- ------------------------------ procedure Save (Bean : in out Answer_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is pragma Unreferenced (Outcome); begin Bean.Service.Save_Answer (Question => Bean.Question, Answer => Bean); end Save; -- ------------------------------ -- Delete the question. -- ------------------------------ procedure Delete (Bean : in out Answer_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is pragma Unreferenced (Outcome); begin Bean.Service.Delete_Answer (Answer => Bean); end Delete; -- ------------------------------ -- Create the answer bean instance. -- ------------------------------ function Create_Answer_Bean (Module : in AWA.Questions.Modules.Question_Module_Access) return Util.Beans.Basic.Readonly_Bean_Access is Object : constant Answer_Bean_Access := new Answer_Bean; begin Object.Service := Module; return Object.all'Access; end Create_Answer_Bean; -- ------------------------------ -- Get the value identified by the name. -- ------------------------------ overriding function Get_Value (From : in Question_List_Bean; Name : in String) return Util.Beans.Objects.Object is Pos : Natural; begin if Name = "tags" then Pos := From.Questions.Get_Row_Index; if Pos = 0 then return Util.Beans.Objects.Null_Object; end if; declare Item : constant Models.Question_Info := From.Questions.List.Element (Pos - 1); begin return From.Tags.Get_Tags (Item.Id); end; elsif Name = "questions" then return Util.Beans.Objects.To_Object (Value => From.Questions_Bean, Storage => Util.Beans.Objects.STATIC); elsif Name = "tag" then return Util.Beans.Objects.To_Object (From.Tag); else return From.Questions.Get_Value (Name); end if; end Get_Value; -- ------------------------------ -- Set the value identified by the name. -- ------------------------------ overriding procedure Set_Value (From : in out Question_List_Bean; Name : in String; Value : in Util.Beans.Objects.Object) is begin if Name = "tag" then From.Tag := Util.Beans.Objects.To_Unbounded_String (Value); From.Load_List; end if; end Set_Value; -- ------------------------------ -- Load the list of question. If a tag was set, filter the list of questions with the tag. -- ------------------------------ procedure Load_List (Into : in out Question_List_Bean) is use AWA.Questions.Models; use AWA.Services; use type ADO.Identifier; Session : ADO.Sessions.Session := Into.Service.Get_Session; Query : ADO.Queries.Context; Tag_Id : ADO.Identifier; begin AWA.Tags.Modules.Find_Tag_Id (Session, Ada.Strings.Unbounded.To_String (Into.Tag), Tag_Id); if Tag_Id /= ADO.NO_IDENTIFIER then Query.Set_Query (AWA.Questions.Models.Query_Question_Tag_List); Query.Bind_Param (Name => "tag", Value => Tag_Id); else Query.Set_Query (AWA.Questions.Models.Query_Question_List); end if; ADO.Sessions.Entities.Bind_Param (Params => Query, Name => "entity_type", Table => AWA.Questions.Models.QUESTION_TABLE, Session => Session); AWA.Questions.Models.List (Into.Questions, Session, Query); declare List : ADO.Utils.Identifier_Vector; Iter : Question_Info_Vectors.Cursor := Into.Questions.List.First; begin while Question_Info_Vectors.Has_Element (Iter) loop List.Append (Question_Info_Vectors.Element (Iter).Id); Question_Info_Vectors.Next (Iter); end loop; Into.Tags.Load_Tags (Session, AWA.Questions.Models.QUESTION_TABLE.Table.all, List); end; end Load_List; -- ------------------------------ -- Create the Question_Info_List_Bean bean instance. -- ------------------------------ function Create_Question_List_Bean (Module : in AWA.Questions.Modules.Question_Module_Access) return Util.Beans.Basic.Readonly_Bean_Access is use AWA.Questions.Models; use AWA.Services; Object : constant Question_List_Bean_Access := new Question_List_Bean; -- Session : ADO.Sessions.Session := Module.Get_Session; -- Query : ADO.Queries.Context; begin Object.Service := Module; Object.Questions_Bean := Object.Questions'Unchecked_Access; -- Query.Set_Query (AWA.Questions.Models.Query_Question_List); -- ADO.Sessions.Entities.Bind_Param (Params => Query, -- Name => "entity_type", -- Table => AWA.Questions.Models.QUESTION_TABLE, -- Session => Session); -- AWA.Questions.Models.List (Object.Questions, Session, Query); Object.Load_List; return Object.all'Access; end Create_Question_List_Bean; -- ------------------------------ -- Get the value identified by the name. -- ------------------------------ overriding function Get_Value (From : in Question_Display_Bean; Name : in String) return Util.Beans.Objects.Object is begin if Name = "answers" then return Util.Beans.Objects.To_Object (Value => From.Answer_List_Bean, Storage => Util.Beans.Objects.STATIC); elsif Name = "question" then return Util.Beans.Objects.To_Object (Value => From.Question_Bean, Storage => Util.Beans.Objects.STATIC); elsif Name = "tags" then return Util.Beans.Objects.To_Object (Value => From.Tags_Bean, Storage => Util.Beans.Objects.STATIC); else return Util.Beans.Objects.Null_Object; end if; end Get_Value; -- ------------------------------ -- Set the value identified by the name. -- ------------------------------ overriding procedure Set_Value (From : in out Question_Display_Bean; Name : in String; Value : in Util.Beans.Objects.Object) is begin if Name = "id" and not Util.Beans.Objects.Is_Empty (Value) then declare package ASC renames AWA.Services.Contexts; use AWA.Questions.Models; use AWA.Services; Session : ADO.Sessions.Session := From.Service.Get_Session; Query : ADO.Queries.Context; List : AWA.Questions.Models.Question_Display_Info_List_Bean; Ctx : constant ASC.Service_Context_Access := ASC.Current; Id : constant ADO.Identifier := ADO.Utils.To_Identifier (Value); begin Query.Set_Query (AWA.Questions.Models.Query_Question_Info); Query.Bind_Param ("question_id", Id); Query.Bind_Param ("user_id", Ctx.Get_User_Identifier); ADO.Sessions.Entities.Bind_Param (Params => Query, Name => "entity_type", Table => AWA.Questions.Models.QUESTION_TABLE, Session => Session); AWA.Questions.Models.List (List, Session, Query); if not List.List.Is_Empty then From.Question := List.List.Element (0); end if; Query.Clear; Query.Bind_Param ("question_id", Util.Beans.Objects.To_Integer (Value)); Query.Bind_Param ("user_id", Ctx.Get_User_Identifier); ADO.Sessions.Entities.Bind_Param (Params => Query, Name => "entity_type", Table => AWA.Questions.Models.ANSWER_TABLE, Session => Session); Query.Set_Query (AWA.Questions.Models.Query_Answer_List); AWA.Questions.Models.List (From.Answer_List, Session, Query); -- Load the tags if any. From.Tags.Load_Tags (Session, Id); end; end if; end Set_Value; -- ------------------------------ -- Create the Question_Display_Bean bean instance. -- ------------------------------ function Create_Question_Display_Bean (Module : in AWA.Questions.Modules.Question_Module_Access) return Util.Beans.Basic.Readonly_Bean_Access is Object : constant Question_Display_Bean_Access := new Question_Display_Bean; begin Object.Service := Module; Object.Question_Bean := Object.Question'Access; Object.Answer_List_Bean := Object.Answer_List'Access; Object.Tags_Bean := Object.Tags'Access; Object.Tags.Set_Entity_Type (AWA.Questions.Models.QUESTION_TABLE); return Object.all'Access; end Create_Question_Display_Bean; end AWA.Questions.Beans;
Make the current tag value visible to the question list bean
Make the current tag value visible to the question list bean
Ada
apache-2.0
Letractively/ada-awa,Letractively/ada-awa,tectronics/ada-awa,tectronics/ada-awa,tectronics/ada-awa,Letractively/ada-awa
ebc7914815314152a598463d62ab4623709601cb
src/postgresql/ado-drivers-connections-postgresql.adb
src/postgresql/ado-drivers-connections-postgresql.adb
----------------------------------------------------------------------- -- ADO Postgresql Database -- Postgresql Database connections -- 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 Ada.Task_Identification; with Interfaces.C.Strings; with Util.Log; with Util.Log.Loggers; with Util.Processes.Tools; with ADO.Statements.Postgresql; with ADO.Schemas.Postgresql; with ADO.Sessions; with ADO.C; package body ADO.Drivers.Connections.Postgresql is use ADO.Statements.Postgresql; use Interfaces.C; use type PQ.PGconn_Access; Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("ADO.Databases.Postgresql"); Driver_Name : aliased constant String := "postgresql"; Driver : aliased Postgresql_Driver; -- ------------------------------ -- Get the database driver which manages this connection. -- ------------------------------ overriding function Get_Driver (Database : in Database_Connection) return ADO.Drivers.Connections.Driver_Access is pragma Unreferenced (Database); begin return Driver'Access; end Get_Driver; overriding function Create_Statement (Database : in Database_Connection; Table : in ADO.Schemas.Class_Mapping_Access) return Query_Statement_Access is begin return Create_Statement (Database => Database.Server, Table => Table); end Create_Statement; overriding function Create_Statement (Database : in Database_Connection; Query : in String) return Query_Statement_Access is begin return Create_Statement (Database => Database.Server, Query => Query); end Create_Statement; -- ------------------------------ -- Create a delete statement. -- ------------------------------ overriding function Create_Statement (Database : in Database_Connection; Table : in ADO.Schemas.Class_Mapping_Access) return Delete_Statement_Access is begin return Create_Statement (Database => Database.Server, Table => Table); end Create_Statement; -- ------------------------------ -- Create an insert statement. -- ------------------------------ overriding function Create_Statement (Database : in Database_Connection; Table : in ADO.Schemas.Class_Mapping_Access) return Insert_Statement_Access is begin return Create_Statement (Database => Database.Server, Table => Table); end Create_Statement; -- ------------------------------ -- Create an update statement. -- ------------------------------ overriding function Create_Statement (Database : in Database_Connection; Table : in ADO.Schemas.Class_Mapping_Access) return Update_Statement_Access is begin return Create_Statement (Database => Database.Server, Table => Table); end Create_Statement; -- ------------------------------ -- Start a transaction. -- ------------------------------ procedure Begin_Transaction (Database : in out Database_Connection) is begin Database.Execute ("BEGIN"); end Begin_Transaction; -- ------------------------------ -- Commit the current transaction. -- ------------------------------ procedure Commit (Database : in out Database_Connection) is begin Database.Execute ("COMMIT"); end Commit; -- ------------------------------ -- Rollback the current transaction. -- ------------------------------ procedure Rollback (Database : in out Database_Connection) is begin Database.Execute ("ROLLBACK"); end Rollback; -- ------------------------------ -- Load the database schema definition for the current database. -- ------------------------------ overriding procedure Load_Schema (Database : in Database_Connection; Schema : out ADO.Schemas.Schema_Definition) is begin ADO.Schemas.Postgresql.Load_Schema (Database, Schema, Ada.Strings.Unbounded.To_String (Database.Name)); end Load_Schema; -- ------------------------------ -- Create the database and initialize it with the schema SQL file. -- ------------------------------ overriding procedure Create_Database (Database : in Database_Connection; Config : in Configs.Configuration'Class; Schema_Path : in String; Messages : out Util.Strings.Vectors.Vector) is pragma Unreferenced (Database); Status : Integer; Command : constant String := "psql -q '" & Config.Get_URI & "' --file=" & Schema_Path; begin Util.Processes.Tools.Execute (Command, Messages, Status); if Status = 0 then Log.Info ("Database schema created successfully."); elsif Status = 255 then Log.Error ("Command not found: {0}", Command); else Log.Error ("Command {0} failed with exit code {1}", Command, Util.Strings.Image (Status)); end if; end Create_Database; -- ------------------------------ -- Execute a simple SQL statement -- ------------------------------ procedure Execute (Database : in out Database_Connection; SQL : in Query_String) is SQL_Stat : constant ADO.C.String_Ptr := ADO.C.To_String_Ptr (SQL); Result : PQ.PGresult_Access; begin Log.Debug ("Execute SQL: {0}", SQL); if Database.Server = PQ.Null_PGconn then Log.Error ("Database connection is not open"); raise ADO.Sessions.Session_Error with "Database connection is closed"; end if; Result := PQ.PQexec (Database.Server, ADO.C.To_C (SQL_Stat)); Log.Debug ("Query result: {0}", PQ.ExecStatusType'Image (PQ.PQresultStatus (Result))); PQ.PQclear (Result); end Execute; -- ------------------------------ -- Closes the database connection -- ------------------------------ overriding procedure Close (Database : in out Database_Connection) is begin if Database.Server /= PQ.Null_PGconn then Log.Info ("Closing connection {0}/{1}", Database.Name, Database.Ident); PQ.PQfinish (Database.Server); Database.Server := PQ.Null_PGconn; end if; end Close; -- ------------------------------ -- Releases the Postgresql connection if it is open -- ------------------------------ overriding procedure Finalize (Database : in out Database_Connection) is begin Log.Debug ("Release connection {0}/{1}", Database.Name, Database.Ident); Database.Close; end Finalize; -- ------------------------------ -- Initialize the database connection manager. -- -- Postgresql://localhost:3306/db -- -- ------------------------------ procedure Create_Connection (D : in out Postgresql_Driver; Config : in Configuration'Class; Result : in out Ref.Ref'Class) is use type PQ.ConnStatusType; URI : constant ADO.C.String_Ptr := ADO.C.To_String_Ptr (Config.Get_URI); Connection : PQ.PGconn_Access; begin Log.Info ("Task {0} connecting to {1}:{2}", Ada.Task_Identification.Image (Ada.Task_Identification.Current_Task), Config.Get_Server, Config.Get_Database); if Config.Get_Property ("password") = "" then Log.Debug ("Postgresql connection with user={0}", Config.Get_Property ("user")); else Log.Debug ("Postgresql connection with user={0} password=XXXXXXXX", Config.Get_Property ("user")); end if; Connection := PQ.PQconnectdb (ADO.C.To_C (URI)); if Connection = PQ.Null_PGconn then declare Message : constant String := "memory allocation error"; begin Log.Error ("Cannot connect to '{0}': {1}", Config.Get_Log_URI, Message); raise ADO.Configs.Connection_Error with "Cannot connect to Postgresql server: " & Message; end; end if; if PQ.PQstatus (Connection) /= PQ.CONNECTION_OK then declare Message : constant String := Strings.Value (PQ.PQerrorMessage (Connection)); begin Log.Error ("Cannot connect to '{0}': {1}", Config.Get_Log_URI, Message); raise ADO.Configs.Connection_Error with "Cannot connect to Postgresql server: " & Message; end; end if; D.Id := D.Id + 1; declare Ident : constant String := Util.Strings.Image (D.Id); Database : constant Database_Connection_Access := new Database_Connection; begin Database.Ident (1 .. Ident'Length) := Ident; Database.Server := Connection; Database.Name := To_Unbounded_String (Config.Get_Database); Result := Ref.Create (Database.all'Access); end; end Create_Connection; -- ------------------------------ -- Initialize the Postgresql driver. -- ------------------------------ procedure Initialize is use type Util.Strings.Name_Access; begin Log.Debug ("Initializing Postgresql driver"); if Driver.Name = null then Driver.Name := Driver_Name'Access; Register (Driver'Access); end if; end Initialize; -- ------------------------------ -- Deletes the Postgresql driver. -- ------------------------------ overriding procedure Finalize (D : in out Postgresql_Driver) is pragma Unreferenced (D); begin Log.Debug ("Deleting the Postgresql driver"); end Finalize; end ADO.Drivers.Connections.Postgresql;
----------------------------------------------------------------------- -- ADO Postgresql Database -- Postgresql Database connections -- 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 Ada.Task_Identification; with Interfaces.C.Strings; with Util.Log; with Util.Log.Loggers; with Util.Processes.Tools; with ADO.Statements.Postgresql; with ADO.Schemas.Postgresql; with ADO.Sessions; with ADO.C; package body ADO.Drivers.Connections.Postgresql is use ADO.Statements.Postgresql; use Interfaces.C; use type PQ.PGconn_Access; Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("ADO.Databases.Postgresql"); Driver_Name : aliased constant String := "postgresql"; Driver : aliased Postgresql_Driver; -- ------------------------------ -- Get the database driver which manages this connection. -- ------------------------------ overriding function Get_Driver (Database : in Database_Connection) return ADO.Drivers.Connections.Driver_Access is pragma Unreferenced (Database); begin return Driver'Access; end Get_Driver; overriding function Create_Statement (Database : in Database_Connection; Table : in ADO.Schemas.Class_Mapping_Access) return Query_Statement_Access is begin return Create_Statement (Database => Database.Server, Table => Table); end Create_Statement; overriding function Create_Statement (Database : in Database_Connection; Query : in String) return Query_Statement_Access is begin return Create_Statement (Database => Database.Server, Query => Query); end Create_Statement; -- ------------------------------ -- Create a delete statement. -- ------------------------------ overriding function Create_Statement (Database : in Database_Connection; Table : in ADO.Schemas.Class_Mapping_Access) return Delete_Statement_Access is begin return Create_Statement (Database => Database.Server, Table => Table); end Create_Statement; -- ------------------------------ -- Create an insert statement. -- ------------------------------ overriding function Create_Statement (Database : in Database_Connection; Table : in ADO.Schemas.Class_Mapping_Access) return Insert_Statement_Access is begin return Create_Statement (Database => Database.Server, Table => Table); end Create_Statement; -- ------------------------------ -- Create an update statement. -- ------------------------------ overriding function Create_Statement (Database : in Database_Connection; Table : in ADO.Schemas.Class_Mapping_Access) return Update_Statement_Access is begin return Create_Statement (Database => Database.Server, Table => Table); end Create_Statement; -- ------------------------------ -- Start a transaction. -- ------------------------------ procedure Begin_Transaction (Database : in out Database_Connection) is begin Database.Execute ("BEGIN"); end Begin_Transaction; -- ------------------------------ -- Commit the current transaction. -- ------------------------------ procedure Commit (Database : in out Database_Connection) is begin Database.Execute ("COMMIT"); end Commit; -- ------------------------------ -- Rollback the current transaction. -- ------------------------------ procedure Rollback (Database : in out Database_Connection) is begin Database.Execute ("ROLLBACK"); end Rollback; -- ------------------------------ -- Load the database schema definition for the current database. -- ------------------------------ overriding procedure Load_Schema (Database : in Database_Connection; Schema : out ADO.Schemas.Schema_Definition) is begin ADO.Schemas.Postgresql.Load_Schema (Database, Schema, Ada.Strings.Unbounded.To_String (Database.Name)); end Load_Schema; -- ------------------------------ -- Execute a simple SQL statement -- ------------------------------ procedure Execute (Database : in out Database_Connection; SQL : in Query_String) is SQL_Stat : constant ADO.C.String_Ptr := ADO.C.To_String_Ptr (SQL); Result : PQ.PGresult_Access; begin Log.Debug ("Execute SQL: {0}", SQL); if Database.Server = PQ.Null_PGconn then Log.Error ("Database connection is not open"); raise ADO.Sessions.Session_Error with "Database connection is closed"; end if; Result := PQ.PQexec (Database.Server, ADO.C.To_C (SQL_Stat)); Log.Debug ("Query result: {0}", PQ.ExecStatusType'Image (PQ.PQresultStatus (Result))); PQ.PQclear (Result); end Execute; -- ------------------------------ -- Closes the database connection -- ------------------------------ overriding procedure Close (Database : in out Database_Connection) is begin if Database.Server /= PQ.Null_PGconn then Log.Info ("Closing connection {0}/{1}", Database.Name, Database.Ident); PQ.PQfinish (Database.Server); Database.Server := PQ.Null_PGconn; end if; end Close; -- ------------------------------ -- Releases the Postgresql connection if it is open -- ------------------------------ overriding procedure Finalize (Database : in out Database_Connection) is begin Log.Debug ("Release connection {0}/{1}", Database.Name, Database.Ident); Database.Close; end Finalize; -- ------------------------------ -- Initialize the database connection manager. -- -- Postgresql://localhost:3306/db -- -- ------------------------------ procedure Create_Connection (D : in out Postgresql_Driver; Config : in Configuration'Class; Result : in out Ref.Ref'Class) is use type PQ.ConnStatusType; URI : constant ADO.C.String_Ptr := ADO.C.To_String_Ptr (Config.Get_URI); Connection : PQ.PGconn_Access; begin Log.Info ("Task {0} connecting to {1}:{2}", Ada.Task_Identification.Image (Ada.Task_Identification.Current_Task), Config.Get_Server, Config.Get_Database); if Config.Get_Property ("password") = "" then Log.Debug ("Postgresql connection with user={0}", Config.Get_Property ("user")); else Log.Debug ("Postgresql connection with user={0} password=XXXXXXXX", Config.Get_Property ("user")); end if; Connection := PQ.PQconnectdb (ADO.C.To_C (URI)); if Connection = PQ.Null_PGconn then declare Message : constant String := "memory allocation error"; begin Log.Error ("Cannot connect to '{0}': {1}", Config.Get_Log_URI, Message); raise ADO.Configs.Connection_Error with "Cannot connect to Postgresql server: " & Message; end; end if; if PQ.PQstatus (Connection) /= PQ.CONNECTION_OK then declare Message : constant String := Strings.Value (PQ.PQerrorMessage (Connection)); begin Log.Error ("Cannot connect to '{0}': {1}", Config.Get_Log_URI, Message); raise ADO.Configs.Connection_Error with "Cannot connect to Postgresql server: " & Message; end; end if; D.Id := D.Id + 1; declare Ident : constant String := Util.Strings.Image (D.Id); Database : constant Database_Connection_Access := new Database_Connection; begin Database.Ident (1 .. Ident'Length) := Ident; Database.Server := Connection; Database.Name := To_Unbounded_String (Config.Get_Database); Result := Ref.Create (Database.all'Access); end; end Create_Connection; -- ------------------------------ -- Create the database and initialize it with the schema SQL file. -- The `Admin` parameter describes the database connection with administrator access. -- The `Config` parameter describes the target database connection. -- ------------------------------ overriding procedure Create_Database (D : in out Postgresql_Driver; Admin : in Configs.Configuration'Class; Config : in Configs.Configuration'Class; Schema_Path : in String; Messages : out Util.Strings.Vectors.Vector) is pragma Unreferenced (D, Admin); Status : Integer; Command : constant String := "psql -q '" & Config.Get_URI & "' --file=" & Schema_Path; begin Util.Processes.Tools.Execute (Command, Messages, Status); if Status = 0 then Log.Info ("Database schema created successfully."); elsif Status = 255 then Log.Error ("Command not found: {0}", Command); else Log.Error ("Command {0} failed with exit code {1}", Command, Util.Strings.Image (Status)); end if; end Create_Database; -- ------------------------------ -- Initialize the Postgresql driver. -- ------------------------------ procedure Initialize is use type Util.Strings.Name_Access; begin Log.Debug ("Initializing Postgresql driver"); if Driver.Name = null then Driver.Name := Driver_Name'Access; Register (Driver'Access); end if; end Initialize; -- ------------------------------ -- Deletes the Postgresql driver. -- ------------------------------ overriding procedure Finalize (D : in out Postgresql_Driver) is pragma Unreferenced (D); begin Log.Debug ("Deleting the Postgresql driver"); end Finalize; end ADO.Drivers.Connections.Postgresql;
Move the Create_Database operation on the Driver instead of the database connection
Move the Create_Database operation on the Driver instead of the database connection
Ada
apache-2.0
stcarrez/ada-ado
34896ecbeab0f8df69a2a243a3f87d46d36782fc
src/orka/interface/orka-terminals.ads
src/orka/interface/orka-terminals.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. package Orka.Terminals is pragma Preelaborate; type Style is (Default, Bold, Dark, Italic, Underline, Blink, Reversed, Cross_Out); type Color is (Default, Grey, Red, Green, Yellow, Blue, Magenta, Cyan, White); function Colorize (Text : String; Foreground, Background : Color := Default; Attribute : Style := Default) return String; -- Colorize the given text with a foreground color, background color, -- and/or style using ANSI escape sequences end Orka.Terminals;
-- 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. private package Orka.Terminals is pragma Preelaborate; type Style is (Default, Bold, Dark, Italic, Underline, Blink, Reversed, Cross_Out); type Color is (Default, Grey, Red, Green, Yellow, Blue, Magenta, Cyan, White); function Colorize (Text : String; Foreground, Background : Color := Default; Attribute : Style := Default) return String; -- Colorize the given text with a foreground color, background color, -- and/or style using ANSI escape sequences end Orka.Terminals;
Make package Orka.Terminals private
orka: Make package Orka.Terminals private Signed-off-by: onox <[email protected]>
Ada
apache-2.0
onox/orka