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
00082625022019a8b3a010b837edd608131ed0ea
src/wiki-plugins-variables.adb
src/wiki-plugins-variables.adb
----------------------------------------------------------------------- -- wiki-plugins-variables -- Variables plugin -- Copyright (C) 2020 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Wiki.Filters.Variables; package body Wiki.Plugins.Variables is -- ------------------------------ -- Set or update a variable in the `Wiki.Filters.Variable` filter. -- ------------------------------ overriding procedure Expand (Plugin : in out Variable_Plugin; Document : in out Wiki.Documents.Document; Params : in out Wiki.Attributes.Attribute_List; Context : in Plugin_Context) is pragma Unreferenced (Plugin, Document); begin if Wiki.Attributes.Length (Params) >= 3 then declare First : Wiki.Attributes.Cursor := Wiki.Attributes.First (Params); Second : Wiki.Attributes.Cursor; begin Wiki.Attributes.Next (First); Second := First; Wiki.Attributes.Next (Second); Wiki.Filters.Variables.Add_Variable (Context.Filters, Wiki.Attributes.Get_Wide_Value (First), Wiki.Attributes.Get_Wide_Value (Second)); end; end if; end Expand; end Wiki.Plugins.Variables;
----------------------------------------------------------------------- -- wiki-plugins-variables -- Variables plugin -- Copyright (C) 2020 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Wiki.Filters.Variables; package body Wiki.Plugins.Variables is -- ------------------------------ -- Set or update a variable in the `Wiki.Filters.Variable` filter. -- ------------------------------ overriding procedure Expand (Plugin : in out Variable_Plugin; Document : in out Wiki.Documents.Document; Params : in out Wiki.Attributes.Attribute_List; Context : in out Plugin_Context) is pragma Unreferenced (Plugin, Document); begin if Wiki.Attributes.Length (Params) >= 3 then declare First : Wiki.Attributes.Cursor := Wiki.Attributes.First (Params); Second : Wiki.Attributes.Cursor; begin Wiki.Attributes.Next (First); Second := First; Wiki.Attributes.Next (Second); Wiki.Filters.Variables.Add_Variable (Context.Filters, Wiki.Attributes.Get_Wide_Value (First), Wiki.Attributes.Get_Wide_Value (Second)); end; end if; end Expand; -- ------------------------------ -- List the variables from the `Wiki.Filters.Variable` filter. -- ------------------------------ overriding procedure Expand (Plugin : in out List_Variable_Plugin; Document : in out Wiki.Documents.Document; Params : in out Wiki.Attributes.Attribute_List; Context : in out Plugin_Context) is pragma Unreferenced (Plugin); procedure Print_Variable (Name : in Wiki.Strings.WString; Value : in Wiki.Strings.WString); Has_Table : Boolean := False; Format : Format_Map := (others => False); Attributes : Wiki.Attributes.Attribute_List; procedure Print_Variable (Name : in Wiki.Strings.WString; Value : in Wiki.Strings.WString) is begin Has_Table := True; Context.Filters.Add_Row (Document); Context.Filters.Add_Column (Document, Attributes); Context.Filters.Add_Text (Document, Name, Format); Context.Filters.Add_Column (Document, Attributes); Context.Filters.Add_Text (Document, Value, Format); end Print_Variable; begin Wiki.Filters.Variables.Iterate (Context.Filters, Print_Variable'Access); if Has_Table then Context.Filters.Finish_Table (Document); end if; end Expand; end Wiki.Plugins.Variables;
Implement the Expand procedure for the List_Variables_Plugin to iterate over the filter variables and print them within a table
Implement the Expand procedure for the List_Variables_Plugin to iterate over the filter variables and print them within a table
Ada
apache-2.0
stcarrez/ada-wiki,stcarrez/ada-wiki
c235833de03785e460600071816a7ac9bd25af2e
src/babel-files-maps.adb
src/babel-files-maps.adb
----------------------------------------------------------------------- -- babel-files-maps -- Hash maps for files and directories -- Copyright (C) 2014 Stephane.Carrez -- Written by Stephane.Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- package body Babel.Files.Maps is -- ------------------------------ -- Find the file with the given name in the file map. -- ------------------------------ function Find (From : in File_Map; Name : in String) return File_Cursor is begin return From.Find (Key => Name'Unrestricted_Access); end Find; -- ------------------------------ -- Find the file with the given name in the file map. -- ------------------------------ function Find (From : in File_Map; Name : in String) return File_Type is Pos : constant File_Cursor := From.Find (Key => Name'Unrestricted_Access); begin if File_Maps.Has_Element (Pos) then return File_Maps.Element (Pos); else return NO_FILE; end if; end Find; -- ------------------------------ -- Add the file with the given name in the container. -- ------------------------------ procedure Add_File (Into : in out Differential_Container; Element : in File_Type) is use type ADO.Identifier; begin if Element.Id = ADO.NO_IDENTIFIER then Into.Known_Files.Insert (Element.Name'Unrestricted_Access, Element); end if; end Add_File; -- ------------------------------ -- Add the directory with the given name in the container. -- ------------------------------ procedure Add_Directory (Into : in out Differential_Container; Element : in Directory_Type) is use type ADO.Identifier; begin if Element.Id = ADO.NO_IDENTIFIER then Into.Known_Dirs.Insert (Element.Name'Unrestricted_Access, Element); end if; end Add_Directory; -- ------------------------------ -- Create a new file instance with the given name in the container. -- ------------------------------ function Create (Into : in Differential_Container; Name : in String) return File_Type is begin return Allocate (Name => Name, Dir => Into.Current); end Create; -- ------------------------------ -- Create a new directory instance with the given name in the container. -- ------------------------------ function Create (Into : in Differential_Container; Name : in String) return Directory_Type is begin return Allocate (Name => Name, Dir => Into.Current); end Create; -- ------------------------------ -- Find the file with the given name in this file container. -- Returns NO_FILE if the file was not found. -- ------------------------------ function Find (From : in Differential_Container; Name : in String) return File_Type is begin return Find (From.Known_Files, Name); end Find; -- ------------------------------ -- Find the directory with the given name in this file container. -- Returns NO_DIRECTORY if the directory was not found. -- ------------------------------ function Find (From : in Differential_Container; Name : in String) return Directory_Type is begin return Find (From.Known_Dirs, Name); end Find; -- ------------------------------ -- Set the directory object associated with the container. -- ------------------------------ overriding procedure Set_Directory (Into : in out Differential_Container; Directory : in Directory_Type) is begin Default_Container (Into).Set_Directory (Directory); Into.Known_Files.Clear; Into.Known_Dirs.Clear; end Set_Directory; -- ------------------------------ -- Prepare the differential container by setting up the known files and known -- directories. The <tt>Update</tt> procedure is called to give access to the -- maps that can be updated. -- ------------------------------ procedure Prepare (Container : in out Differential_Container; Update : access procedure (Files : in out File_Map; Dirs : in out Directory_Map)) is begin Update (Container.Known_Files, Container.Known_Dirs); end Prepare; end Babel.Files.Maps;
----------------------------------------------------------------------- -- babel-files-maps -- Hash maps for files and directories -- Copyright (C) 2014 Stephane.Carrez -- Written by Stephane.Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- package body Babel.Files.Maps is -- ------------------------------ -- Find the file with the given name in the file map. -- ------------------------------ function Find (From : in File_Map; Name : in String) return File_Cursor is begin return From.Find (Key => Name'Unrestricted_Access); end Find; -- ------------------------------ -- Find the file with the given name in the file map. -- ------------------------------ function Find (From : in File_Map; Name : in String) return File_Type is Pos : constant File_Cursor := From.Find (Key => Name'Unrestricted_Access); begin if File_Maps.Has_Element (Pos) then return File_Maps.Element (Pos); else return NO_FILE; end if; end Find; -- ------------------------------ -- Find the directory with the given name in the directory map. -- ------------------------------ function Find (From : in Directory_Map; Name : in String) return Directory_Cursor is begin return From.Find (Key => Name'Unrestricted_Access); end Find; -- ------------------------------ -- Find the directory with the given name in the directory map. -- ------------------------------ function Find (From : in Directory_Map; Name : in String) return Directory_Type is Pos : constant Directory_Cursor := From.Find (Key => Name'Unrestricted_Access); begin if Directory_Maps.Has_Element (Pos) then return Directory_Maps.Element (Pos); else return NO_DIRECTORY; end if; end Find; -- ------------------------------ -- Add the file with the given name in the container. -- ------------------------------ procedure Add_File (Into : in out Differential_Container; Element : in File_Type) is use type ADO.Identifier; begin if Element.Id = ADO.NO_IDENTIFIER then Into.Known_Files.Insert (Element.Name'Unrestricted_Access, Element); end if; end Add_File; -- ------------------------------ -- Add the directory with the given name in the container. -- ------------------------------ procedure Add_Directory (Into : in out Differential_Container; Element : in Directory_Type) is use type ADO.Identifier; begin if Element.Id = ADO.NO_IDENTIFIER then Into.Known_Dirs.Insert (Element.Name'Unrestricted_Access, Element); end if; end Add_Directory; -- ------------------------------ -- Create a new file instance with the given name in the container. -- ------------------------------ function Create (Into : in Differential_Container; Name : in String) return File_Type is begin return Allocate (Name => Name, Dir => Into.Current); end Create; -- ------------------------------ -- Create a new directory instance with the given name in the container. -- ------------------------------ function Create (Into : in Differential_Container; Name : in String) return Directory_Type is begin return Allocate (Name => Name, Dir => Into.Current); end Create; -- ------------------------------ -- Find the file with the given name in this file container. -- Returns NO_FILE if the file was not found. -- ------------------------------ function Find (From : in Differential_Container; Name : in String) return File_Type is begin return Find (From.Known_Files, Name); end Find; -- ------------------------------ -- Find the directory with the given name in this file container. -- Returns NO_DIRECTORY if the directory was not found. -- ------------------------------ function Find (From : in Differential_Container; Name : in String) return Directory_Type is begin return Find (From.Known_Dirs, Name); end Find; -- ------------------------------ -- Set the directory object associated with the container. -- ------------------------------ overriding procedure Set_Directory (Into : in out Differential_Container; Directory : in Directory_Type) is begin Default_Container (Into).Set_Directory (Directory); Into.Known_Files.Clear; Into.Known_Dirs.Clear; end Set_Directory; -- ------------------------------ -- Prepare the differential container by setting up the known files and known -- directories. The <tt>Update</tt> procedure is called to give access to the -- maps that can be updated. -- ------------------------------ procedure Prepare (Container : in out Differential_Container; Update : access procedure (Files : in out File_Map; Dirs : in out Directory_Map)) is begin Update (Container.Known_Files, Container.Known_Dirs); end Prepare; end Babel.Files.Maps;
Implement the Find operation to find a directory by its name
Implement the Find operation to find a directory by its name
Ada
apache-2.0
stcarrez/babel
698ded90f4e73f213b6cb856d53f7ce6c14f20f3
awa/regtests/awa-jobs-modules-tests.adb
awa/regtests/awa-jobs-modules-tests.adb
----------------------------------------------------------------------- -- jobs-tests -- Unit tests for 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.Test_Caller; with AWA.Jobs.Modules; with AWA.Jobs.Services.Tests; package body AWA.Jobs.Modules.Tests is package Caller is new Util.Test_Caller (Test, "Jobs.Modules"); procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is begin Caller.Add_Test (Suite, "Test AWA.Jobs.Modules.Register", Test_Register'Access); end Add_Tests; -- ------------------------------ -- Test the job factory. -- ------------------------------ procedure Test_Register (T : in out Test) is M : AWA.Jobs.Modules.Job_Module; begin M.Register (Definition => Services.Tests.Test_Definition.Factory'Access); Util.Tests.Assert_Equals (T, 1, Integer (M.Factory.Length), "Invalid factory length"); M.Register (Definition => Services.Tests.Work_1_Definition.Factory'Access); Util.Tests.Assert_Equals (T, 2, Integer (M.Factory.Length), "Invalid factory length"); M.Register (Definition => Services.Tests.Work_2_Definition.Factory'Access); Util.Tests.Assert_Equals (T, 3, Integer (M.Factory.Length), "Invalid factory length"); end Test_Register; end AWA.Jobs.Modules.Tests;
----------------------------------------------------------------------- -- jobs-tests -- Unit tests for 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.Test_Caller; with AWA.Jobs.Modules; with AWA.Jobs.Services.Tests; package body AWA.Jobs.Modules.Tests is package Caller is new Util.Test_Caller (Test, "Jobs.Modules"); procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is begin Caller.Add_Test (Suite, "Test AWA.Jobs.Modules.Register", Test_Register'Access); end Add_Tests; -- ------------------------------ -- Test the job factory. -- ------------------------------ procedure Test_Register (T : in out Test) is M : AWA.Jobs.Modules.Job_Module; begin M.Register (Definition => Services.Tests.Test_Definition.Factory); Util.Tests.Assert_Equals (T, 1, Integer (M.Factory.Length), "Invalid factory length"); M.Register (Definition => Services.Tests.Work_1_Definition.Factory); Util.Tests.Assert_Equals (T, 2, Integer (M.Factory.Length), "Invalid factory length"); M.Register (Definition => Services.Tests.Work_2_Definition.Factory); Util.Tests.Assert_Equals (T, 3, Integer (M.Factory.Length), "Invalid factory length"); end Test_Register; end AWA.Jobs.Modules.Tests;
Fix compilation
Fix compilation
Ada
apache-2.0
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
aba8124564250aeefba1345a8bd22a9218bd59fb
src/util-beans-basic.ads
src/util-beans-basic.ads
----------------------------------------------------------------------- -- util-beans-basic -- Interface Definition with Getter and Setters -- Copyright (C) 2009, 2010, 2017 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Beans.Objects; package Util.Beans.Basic is pragma Preelaborate; -- ------------------------------ -- Read-only Bean interface. -- ------------------------------ -- The ''Readonly_Bean'' interface allows to plug a complex -- runtime object to the expression resolver. This interface -- must be implemented by any tagged record that should be -- accessed as a variable for an expression. -- -- For example, if 'foo' is bound to an object implementing that -- interface, expressions like 'foo.name' will resolve to 'foo' -- and the 'Get_Value' method will be called with 'name'. -- type Readonly_Bean is limited interface; type Readonly_Bean_Access is access all Readonly_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 Readonly_Bean; Name : in String) return Util.Beans.Objects.Object is abstract; -- ------------------------------ -- Bean interface. -- ------------------------------ -- The ''Bean'' interface allows to modify a property value. type Bean is limited interface and Readonly_Bean; -- Set the value identified by the name. -- If the name cannot be found, the method should raise the No_Value -- exception. procedure Set_Value (From : in out Bean; Name : in String; Value : in Util.Beans.Objects.Object) is abstract; -- ------------------------------ -- List of objects -- ------------------------------ -- The <b>List_Bean</b> interface gives access to a list of objects. type List_Bean is limited interface and Readonly_Bean; type List_Bean_Access is access all List_Bean'Class; -- Get the number of elements in the list. function Get_Count (From : in List_Bean) return Natural is abstract; -- Set the current row index. Valid row indexes start at 1. procedure Set_Row_Index (From : in out List_Bean; Index : in Natural) is abstract; -- Get the element at the current row index. function Get_Row (From : in List_Bean) return Util.Beans.Objects.Object is abstract; end Util.Beans.Basic;
----------------------------------------------------------------------- -- util-beans-basic -- Interface Definition with Getter and Setters -- Copyright (C) 2009, 2010, 2017 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Beans.Objects; package Util.Beans.Basic is pragma Preelaborate; -- ------------------------------ -- Read-only Bean interface. -- ------------------------------ -- The ''Readonly_Bean'' interface allows to plug a complex -- runtime object to the expression resolver. This interface -- must be implemented by any tagged record that should be -- accessed as a variable for an expression. -- -- For example, if 'foo' is bound to an object implementing that -- interface, expressions like 'foo.name' will resolve to 'foo' -- and the 'Get_Value' method will be called with 'name'. -- type Readonly_Bean is limited interface; type Readonly_Bean_Access is access all Readonly_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 Readonly_Bean; Name : in String) return Util.Beans.Objects.Object is abstract; -- ------------------------------ -- Bean interface. -- ------------------------------ -- The ''Bean'' interface allows to modify a property value. type Bean is limited interface and Readonly_Bean; -- Set the value identified by the name. -- If the name cannot be found, the method should raise the No_Value -- exception. procedure Set_Value (From : in out Bean; Name : in String; Value : in Util.Beans.Objects.Object) is abstract; -- ------------------------------ -- List of objects -- ------------------------------ -- The <b>List_Bean</b> interface gives access to a list of objects. type List_Bean is limited interface and Readonly_Bean; type List_Bean_Access is access all List_Bean'Class; -- Get the number of elements in the list. function Get_Count (From : in List_Bean) return Natural is abstract; -- Set the current row index. Valid row indexes start at 1. procedure Set_Row_Index (From : in out List_Bean; Index : in Natural) is abstract; -- Get the element at the current row index. function Get_Row (From : in List_Bean) return Util.Beans.Objects.Object is abstract; -- ------------------------------ -- Arrays of objects -- ------------------------------ -- The <tt>Array_Bean</tt> interface gives access to an array of objects. -- Unlike the <tt>List_Bean</tt> interface, it does not maintain any current position. -- The drawback is that there is no current row concept and a position must be specified -- to return a given row. type Array_Bean is limited interface and Readonly_Bean; type Array_Bean_Access is access all Array_Bean'Class; -- Get the number of elements in the array. function Get_Count (From : in Array_Bean) return Natural is abstract; -- Get the element at the given position. function Get_Row (From : in Array_Bean; Position : in Natural) return Util.Beans.Objects.Object is abstract; end Util.Beans.Basic;
Declare the Array_Bean interface
Declare the Array_Bean interface
Ada
apache-2.0
stcarrez/ada-util,stcarrez/ada-util
a30afed48a6e3844f233da5383f9eee72d11c2ab
awa/plugins/awa-blogs/regtests/awa-blogs-tests.ads
awa/plugins/awa-blogs/regtests/awa-blogs-tests.ads
----------------------------------------------------------------------- -- awa-blogs-tests -- Unit tests for blogs module -- 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.Tests; with AWA.Tests; with Ada.Strings.Unbounded; package AWA.Blogs.Tests is procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite); type Test is new AWA.Tests.Test with record Blog_Ident : Ada.Strings.Unbounded.Unbounded_String; Post_Ident : Ada.Strings.Unbounded.Unbounded_String; Post_Uri : Ada.Strings.Unbounded.Unbounded_String; end record; -- Get some access on the blog as anonymous users. procedure Verify_Anonymous (T : in out Test; Post : in String); -- Test access to the blog as anonymous user. procedure Test_Anonymous_Access (T : in out Test); -- Test creation of blog by simulating web requests. procedure Test_Create_Blog (T : in out Test); -- Test updating a post by simulating web requests. procedure Test_Update_Post (T : in out Test); -- Test listing the blog posts. procedure Test_Admin_List_Posts (T : in out Test); -- Test listing the blog comments. procedure Test_Admin_List_Comments (T : in out Test); -- Test getting the JSON blog stats (for graphs). procedure Test_Admin_Blog_Stats (T : in out Test); end AWA.Blogs.Tests;
----------------------------------------------------------------------- -- awa-blogs-tests -- Unit tests for blogs module -- 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.Tests; with AWA.Tests; with Ada.Strings.Unbounded; package AWA.Blogs.Tests is procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite); type Test is new AWA.Tests.Test with record Blog_Ident : Ada.Strings.Unbounded.Unbounded_String; Post_Ident : Ada.Strings.Unbounded.Unbounded_String; Post_Uri : Ada.Strings.Unbounded.Unbounded_String; end record; -- Get some access on the blog as anonymous users. procedure Verify_Anonymous (T : in out Test; Post : in String); -- Test access to the blog as anonymous user. procedure Test_Anonymous_Access (T : in out Test); -- Test creation of blog by simulating web requests. procedure Test_Create_Blog (T : in out Test); -- Test updating a post by simulating web requests. procedure Test_Update_Post (T : in out Test); -- Test updating the publication date by simulating web requests. procedure Test_Update_Publish_Date (T : in out Test); -- Test listing the blog posts. procedure Test_Admin_List_Posts (T : in out Test); -- Test listing the blog comments. procedure Test_Admin_List_Comments (T : in out Test); -- Test getting the JSON blog stats (for graphs). procedure Test_Admin_Blog_Stats (T : in out Test); end AWA.Blogs.Tests;
Declare the Test_Update_Publish_Date procedure
Declare the Test_Update_Publish_Date procedure
Ada
apache-2.0
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
0b7fd1b9caa52df563f19951f47d5e94795ed6e9
matp/src/symbols/mat-symbols-targets.adb
matp/src/symbols/mat-symbols-targets.adb
----------------------------------------------------------------------- -- mat-symbols-targets - Symbol files management -- Copyright (C) 2014, 2015, 2019 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Bfd.Sections; with ELF; with Util.Strings; with Util.Files; with Util.Log.Loggers; with Ada.Directories; with MAT.Formats; package body MAT.Symbols.Targets is -- The logger Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("MAT.Symbols.Targets"); procedure Find_Nearest_Line (Symbols : in Region_Symbols; Addr : in MAT.Types.Target_Addr; Symbol : out Symbol_Info); -- ------------------------------ -- Open the binary and load the symbols from that file. -- ------------------------------ procedure Open (Symbols : in out Target_Symbols; Path : in String) is begin Log.Info ("Loading symbols from {0}", Path); -- -- Bfd.Files.Open (Symbols.File, Path, ""); -- if Bfd.Files.Check_Format (Symbols.File, Bfd.Files.OBJECT) then -- Bfd.Symbols.Read_Symbols (Symbols.File, Symbols.Symbols); -- end if; end Open; -- ------------------------------ -- Load the symbol table for the associated region. -- ------------------------------ procedure Open (Symbols : in out Region_Symbols; Path : in String; Search_Path : in String) is Pos : Natural; begin Log.Info ("Loading symbols from {0}", Path); if Ada.Directories.Exists (Path) then Bfd.Files.Open (Symbols.File, Path, ""); else Pos := Util.Strings.Rindex (Path, '/'); if Pos > 0 then Bfd.Files.Open (Symbols.File, Util.Files.Find_File_Path (Path (Pos + 1 .. Path'Last), Search_Path)); end if; end if; if Bfd.Files.Check_Format (Symbols.File, Bfd.Files.OBJECT) then Bfd.Symbols.Read_Symbols (Symbols.File, Symbols.Symbols); end if; end Open; -- ------------------------------ -- Load the symbols associated with a shared library described by the memory region. -- ------------------------------ procedure Load_Symbols (Symbols : in out Target_Symbols; Region : in MAT.Memory.Region_Info; Offset_Addr : in MAT.Types.Target_Addr) is use type Bfd.File_Flags; Pos : constant Symbols_Cursor := Symbols.Libraries.Find (Region.Start_Addr); Syms : Region_Symbols_Ref; begin if not Symbols_Maps.Has_Element (Pos) then Syms := Region_Symbols_Refs.Create; Syms.Value.Region := Region; Syms.Value.Offset := Offset_Addr; Symbols.Libraries.Insert (Region.Start_Addr, Syms); else Syms := Symbols_Maps.Element (Pos); end if; if Ada.Strings.Unbounded.Length (Region.Path) > 0 then Open (Syms.Value, Ada.Strings.Unbounded.To_String (Region.Path), Ada.Strings.Unbounded.To_String (Symbols.Search_Path)); if (Bfd.Files.Get_File_Flags (Syms.Value.File) and Bfd.Files.EXEC_P) /= 0 then Syms.Value.Offset := 0; end if; end if; end Load_Symbols; -- ------------------------------ -- Load the symbols associated with all the shared libraries described by -- the memory region map. -- ------------------------------ procedure Load_Symbols (Symbols : in out Target_Symbols; Regions : in MAT.Memory.Region_Info_Map) is use type ELF.Elf32_Word; Iter : MAT.Memory.Region_Info_Cursor := Regions.First; begin while MAT.Memory.Region_Info_Maps.Has_Element (Iter) loop declare Region : MAT.Memory.Region_Info := MAT.Memory.Region_Info_Maps.Element (Iter); Offset : MAT.Types.Target_Addr; begin if (Region.Flags and ELF.PF_X) /= 0 then if Ada.Strings.Unbounded.Length (Region.Path) = 0 then Region.Path := Symbols.Path; Offset := 0; else Offset := Region.Start_Addr; end if; MAT.Symbols.Targets.Load_Symbols (Symbols, Region, Offset); end if; exception when Bfd.OPEN_ERROR => Symbols.Console.Error ("Cannot open symbol library file '" & Ada.Strings.Unbounded.To_String (Region.Path) & "'"); end; MAT.Memory.Region_Info_Maps.Next (Iter); end loop; end Load_Symbols; -- ------------------------------ -- Demangle the symbol. -- ------------------------------ procedure Demangle (Symbols : in Target_Symbols; Symbol : in out Symbol_Info) is use type Bfd.Demangle_Flags; use Ada.Strings.Unbounded; Pos : constant Natural := Index (Symbol.File, ".", Ada.Strings.Backward); begin if Symbol.Line = 0 or else Pos = 0 or else Symbol.Symbols.Is_Null then return; end if; declare Mode : Bfd.Demangle_Flags := Symbols.Demangle; Len : constant Positive := Length (Symbol.File); Ext : constant String := Slice (Symbol.File, Pos, Len); Sym : constant String := To_String (Symbol.Name); begin if Mode = Bfd.Constants.DMGL_AUTO and then Ext = ".adb" then Mode := Bfd.Constants.DMGL_GNAT; end if; declare Name : constant String := Bfd.Symbols.Demangle (Symbol.Symbols.Value.File, Sym, Mode); begin if Name'Length > 0 then Symbol.Name := To_Unbounded_String (Name); end if; end; end; end Demangle; procedure Find_Nearest_Line (Symbols : in Region_Symbols; Addr : in MAT.Types.Target_Addr; Symbol : out Symbol_Info) is Text_Section : Bfd.Sections.Section; Pc : constant Bfd.Vma_Type := Bfd.Vma_Type (Addr); begin if not Bfd.Files.Is_Open (Symbols.File) then Symbol.File := Symbols.Region.Path; return; end if; Text_Section := Bfd.Sections.Find_Section (Symbols.File, ".text"); Bfd.Symbols.Find_Nearest_Line (File => Symbols.File, Sec => Text_Section, Symbols => Symbols.Symbols, Addr => Pc, Name => Symbol.File, Func => Symbol.Name, Line => Symbol.Line); end Find_Nearest_Line; -- ------------------------------ -- Find the nearest source file and line for the given address. -- ------------------------------ procedure Find_Nearest_Line (Symbols : in Target_Symbols; Addr : in MAT.Types.Target_Addr; Symbol : out Symbol_Info) is Pos : constant Symbols_Cursor := Symbols.Libraries.Floor (Addr); begin Symbol.Line := 0; if Symbols_Maps.Has_Element (Pos) then declare Syms : constant Region_Symbols_Ref := Symbols_Maps.Element (Pos); begin if Syms.Value.Region.End_Addr > Addr then Symbol.Symbols := Syms; Find_Nearest_Line (Symbols => Syms.Value, Addr => Addr - Syms.Value.Offset, Symbol => Symbol); Demangle (Symbols, Symbol); return; end if; end; end if; Symbol.Line := 0; Symbol.File := Ada.Strings.Unbounded.To_Unbounded_String (""); Symbol.Name := Ada.Strings.Unbounded.To_Unbounded_String (MAT.Formats.Addr (Addr)); exception when Bfd.NOT_FOUND => Symbol.Line := 0; Symbol.File := Ada.Strings.Unbounded.To_Unbounded_String (""); Symbol.Name := Ada.Strings.Unbounded.To_Unbounded_String (MAT.Formats.Addr (Addr)); end Find_Nearest_Line; -- ------------------------------ -- Find the symbol in the symbol table and return the start and end address. -- ------------------------------ procedure Find_Symbol_Range (Symbols : in Target_Symbols; Name : in String; From : out MAT.Types.Target_Addr; To : out MAT.Types.Target_Addr) is use type Bfd.Symbols.Symbol; Iter : Symbols_Cursor := Symbols.Libraries.First; begin while Symbols_Maps.Has_Element (Iter) loop declare Syms : constant Region_Symbols_Ref := Symbols_Maps.Element (Iter); Sym : Bfd.Symbols.Symbol; Sec : Bfd.Sections.Section; begin if not Syms.Is_Null and then Bfd.Files.Is_Open (Syms.Value.File) then Sym := Bfd.Symbols.Get_Symbol (Syms.Value.Symbols, Name); if Sym /= Bfd.Symbols.Null_Symbol then Sec := Bfd.Symbols.Get_Section (Sym); if not Bfd.Sections.Is_Undefined_Section (Sec) then From := MAT.Types.Target_Addr (Bfd.Symbols.Get_Value (Sym)); From := From + Syms.Value.Offset; To := From + MAT.Types.Target_Addr (Bfd.Symbols.Get_Symbol_Size (Sym)); return; end if; end if; end if; end; Symbols_Maps.Next (Iter); end loop; end Find_Symbol_Range; end MAT.Symbols.Targets;
----------------------------------------------------------------------- -- mat-symbols-targets - Symbol files management -- Copyright (C) 2014, 2015, 2019, 2021 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Bfd.Sections; with ELF; with Util.Strings; with Util.Files; with Util.Log.Loggers; with Ada.Directories; with MAT.Formats; package body MAT.Symbols.Targets is -- The logger Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("MAT.Symbols.Targets"); procedure Find_Nearest_Line (Symbols : in Region_Symbols; Addr : in MAT.Types.Target_Addr; Symbol : out Symbol_Info); -- ------------------------------ -- Open the binary and load the symbols from that file. -- ------------------------------ procedure Open (Symbols : in out Target_Symbols; Path : in String) is begin Log.Info ("Loading symbols from {0}", Path); -- -- Bfd.Files.Open (Symbols.File, Path, ""); -- if Bfd.Files.Check_Format (Symbols.File, Bfd.Files.OBJECT) then -- Bfd.Symbols.Read_Symbols (Symbols.File, Symbols.Symbols); -- end if; end Open; -- ------------------------------ -- Load the symbol table for the associated region. -- ------------------------------ procedure Open (Symbols : in out Region_Symbols; Path : in String; Search_Path : in String) is Pos : Natural; begin Log.Info ("Loading symbols from {0}", Path); if Ada.Directories.Exists (Path) then Bfd.Files.Open (Symbols.File, Path, ""); else Pos := Util.Strings.Rindex (Path, '/'); if Pos > 0 then Bfd.Files.Open (Symbols.File, Util.Files.Find_File_Path (Path (Pos + 1 .. Path'Last), Search_Path)); end if; end if; if Bfd.Files.Check_Format (Symbols.File, Bfd.Files.OBJECT) then Bfd.Symbols.Read_Symbols (Symbols.File, Symbols.Symbols); end if; end Open; -- ------------------------------ -- Load the symbols associated with a shared library described by the memory region. -- ------------------------------ procedure Load_Symbols (Symbols : in out Target_Symbols; Region : in MAT.Memory.Region_Info; Offset_Addr : in MAT.Types.Target_Addr) is use type Bfd.File_Flags; Pos : constant Symbols_Cursor := Symbols.Libraries.Find (Region.Start_Addr); Syms : Region_Symbols_Ref; begin if not Symbols_Maps.Has_Element (Pos) then Syms := Region_Symbols_Refs.Create; Syms.Value.Region := Region; Syms.Value.Offset := Offset_Addr; Symbols.Libraries.Insert (Region.Start_Addr, Syms); else Syms := Symbols_Maps.Element (Pos); end if; if Ada.Strings.Unbounded.Length (Region.Path) > 0 then Open (Syms.Value, Ada.Strings.Unbounded.To_String (Region.Path), Ada.Strings.Unbounded.To_String (Symbols.Search_Path)); if Bfd.Files.Is_Open (Syms.Value.File) and then (Bfd.Files.Get_File_Flags (Syms.Value.File) and Bfd.Files.EXEC_P) /= 0 then Syms.Value.Offset := 0; end if; end if; end Load_Symbols; -- ------------------------------ -- Load the symbols associated with all the shared libraries described by -- the memory region map. -- ------------------------------ procedure Load_Symbols (Symbols : in out Target_Symbols; Regions : in MAT.Memory.Region_Info_Map) is use type ELF.Elf32_Word; Iter : MAT.Memory.Region_Info_Cursor := Regions.First; begin while MAT.Memory.Region_Info_Maps.Has_Element (Iter) loop declare Region : MAT.Memory.Region_Info := MAT.Memory.Region_Info_Maps.Element (Iter); Offset : MAT.Types.Target_Addr; begin if (Region.Flags and ELF.PF_X) /= 0 then if Ada.Strings.Unbounded.Length (Region.Path) = 0 then Region.Path := Symbols.Path; Offset := 0; else Offset := Region.Start_Addr; end if; MAT.Symbols.Targets.Load_Symbols (Symbols, Region, Offset); end if; exception when Bfd.OPEN_ERROR => Symbols.Console.Error ("Cannot open symbol library file '" & Ada.Strings.Unbounded.To_String (Region.Path) & "'"); end; MAT.Memory.Region_Info_Maps.Next (Iter); end loop; end Load_Symbols; -- ------------------------------ -- Demangle the symbol. -- ------------------------------ procedure Demangle (Symbols : in Target_Symbols; Symbol : in out Symbol_Info) is use type Bfd.Demangle_Flags; use Ada.Strings.Unbounded; Pos : constant Natural := Index (Symbol.File, ".", Ada.Strings.Backward); begin if Symbol.Line = 0 or else Pos = 0 or else Symbol.Symbols.Is_Null then return; end if; declare Mode : Bfd.Demangle_Flags := Symbols.Demangle; Len : constant Positive := Length (Symbol.File); Ext : constant String := Slice (Symbol.File, Pos, Len); Sym : constant String := To_String (Symbol.Name); begin if Mode = Bfd.Constants.DMGL_AUTO and then Ext = ".adb" then Mode := Bfd.Constants.DMGL_GNAT; end if; declare Name : constant String := Bfd.Symbols.Demangle (Symbol.Symbols.Value.File, Sym, Mode); begin if Name'Length > 0 then Symbol.Name := To_Unbounded_String (Name); end if; end; end; end Demangle; procedure Find_Nearest_Line (Symbols : in Region_Symbols; Addr : in MAT.Types.Target_Addr; Symbol : out Symbol_Info) is Text_Section : Bfd.Sections.Section; Pc : constant Bfd.Vma_Type := Bfd.Vma_Type (Addr); begin if not Bfd.Files.Is_Open (Symbols.File) then Symbol.File := Symbols.Region.Path; return; end if; Text_Section := Bfd.Sections.Find_Section (Symbols.File, ".text"); Bfd.Symbols.Find_Nearest_Line (File => Symbols.File, Sec => Text_Section, Symbols => Symbols.Symbols, Addr => Pc, Name => Symbol.File, Func => Symbol.Name, Line => Symbol.Line); end Find_Nearest_Line; -- ------------------------------ -- Find the nearest source file and line for the given address. -- ------------------------------ procedure Find_Nearest_Line (Symbols : in Target_Symbols; Addr : in MAT.Types.Target_Addr; Symbol : out Symbol_Info) is Pos : constant Symbols_Cursor := Symbols.Libraries.Floor (Addr); begin Symbol.Line := 0; if Symbols_Maps.Has_Element (Pos) then declare Syms : constant Region_Symbols_Ref := Symbols_Maps.Element (Pos); begin if Syms.Value.Region.End_Addr > Addr then Symbol.Symbols := Syms; Find_Nearest_Line (Symbols => Syms.Value, Addr => Addr - Syms.Value.Offset, Symbol => Symbol); Demangle (Symbols, Symbol); return; end if; exception when Bfd.NOT_FOUND => Symbol.Line := 0; Symbol.File := Syms.Value.Region.Path; Symbol.Name := Ada.Strings.Unbounded.To_Unbounded_String (MAT.Formats.Addr (Addr)); return; end; end if; Symbol.Line := 0; Symbol.File := Ada.Strings.Unbounded.To_Unbounded_String (""); Symbol.Name := Ada.Strings.Unbounded.To_Unbounded_String (MAT.Formats.Addr (Addr)); end Find_Nearest_Line; -- ------------------------------ -- Find the symbol in the symbol table and return the start and end address. -- ------------------------------ procedure Find_Symbol_Range (Symbols : in Target_Symbols; Name : in String; From : out MAT.Types.Target_Addr; To : out MAT.Types.Target_Addr) is use type Bfd.Symbols.Symbol; Iter : Symbols_Cursor := Symbols.Libraries.First; begin while Symbols_Maps.Has_Element (Iter) loop declare Syms : constant Region_Symbols_Ref := Symbols_Maps.Element (Iter); Sym : Bfd.Symbols.Symbol; Sec : Bfd.Sections.Section; begin if not Syms.Is_Null and then Bfd.Files.Is_Open (Syms.Value.File) then Sym := Bfd.Symbols.Get_Symbol (Syms.Value.Symbols, Name); if Sym /= Bfd.Symbols.Null_Symbol then Sec := Bfd.Symbols.Get_Section (Sym); if not Bfd.Sections.Is_Undefined_Section (Sec) then From := MAT.Types.Target_Addr (Bfd.Symbols.Get_Value (Sym)); From := From + Syms.Value.Offset; To := From + MAT.Types.Target_Addr (Bfd.Symbols.Get_Symbol_Size (Sym)); return; end if; end if; end if; end; Symbols_Maps.Next (Iter); end loop; end Find_Symbol_Range; -- ------------------------------ -- Find the symbol region in the symbol table which contains the given address -- and return the start and end address. -- ------------------------------ procedure Find_Symbol_Range (Symbols : in Target_Symbols; Addr : in Mat.Types.Target_Addr; From : out MAT.Types.Target_Addr; To : out MAT.Types.Target_Addr) is use type Bfd.Symbols.Symbol; Pos : constant Symbols_Cursor := Symbols.Libraries.Floor (Addr); begin if Symbols_Maps.Has_Element (Pos) then declare Syms : constant Region_Symbols_Ref := Symbols_Maps.Element (Pos); Symbol : Symbol_Info; Sym : Bfd.Symbols.Symbol; Sec : Bfd.Sections.Section; begin if Syms.Value.Region.End_Addr > Addr then Symbol.Line := 0; Symbol.Symbols := Syms; Find_Nearest_Line (Symbols => Syms.Value, Addr => Addr - Syms.Value.Offset, Symbol => Symbol); Sym := Bfd.Symbols.Get_Symbol (Syms.Value.Symbols, Ada.Strings.Unbounded.To_String (Symbol.Name)); if Sym /= Bfd.Symbols.Null_Symbol then Sec := Bfd.Symbols.Get_Section (Sym); if not Bfd.Sections.Is_Undefined_Section (Sec) then From := MAT.Types.Target_Addr (Bfd.Symbols.Get_Value (Sym)); From := From + Syms.Value.Offset; To := From + MAT.Types.Target_Addr (Bfd.Symbols.Get_Symbol_Size (Sym)); return; end if; end if; end if; end; end if; From := Addr; To := Addr; exception when Bfd.NOT_FOUND => From := Addr; To := Addr; end Find_Symbol_Range; end MAT.Symbols.Targets;
Implement new Find_Symbol_Range Improvement of Find_Nearest_Line to return the region name when we don't have a symbol
Implement new Find_Symbol_Range Improvement of Find_Nearest_Line to return the region name when we don't have a symbol
Ada
apache-2.0
stcarrez/mat,stcarrez/mat,stcarrez/mat
e9602a6bc37d0a150bec74bb6522727dc952cf67
awa/plugins/awa-images/src/awa-images-modules.ads
awa/plugins/awa-images/src/awa-images-modules.ads
----------------------------------------------------------------------- -- awa-images-modules -- Image management module -- Copyright (C) 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 ASF.Applications; with AWA.Modules; with AWA.Storages.Models; with AWA.Storages.Services; with AWA.Images.Services; with AWA.Images.Models; with AWA.Jobs.Services; with AWA.Jobs.Modules; -- == Image Module == -- The <tt>Image_Module</tt> type represents the image module. An instance of the image -- module must be declared and registered when the application is created and initialized. -- The image module is associated with the image service which provides and implements -- the image management operations. -- -- When the image module is initialized, it registers itself as a listener to the storage -- module to be notified when a storage file is created, updated or removed. When a file -- is added, it looks at the file type and extracts the image information if the storage file -- is an image. package AWA.Images.Modules is NAME : constant String := "images"; -- Job worker procedure to identify an image and generate its thumnbnail. procedure Thumbnail_Worker (Job : in out AWA.Jobs.Services.Abstract_Job_Type'Class); package Thumbnail_Job_Definition is new AWA.Jobs.Services.Work_Definition (Thumbnail_Worker'Access); type Image_Module is new AWA.Modules.Module and AWA.Storages.Services.Listener with private; type Image_Module_Access is access all Image_Module'Class; -- Initialize the image module. overriding procedure Initialize (Plugin : in out Image_Module; App : in AWA.Modules.Application_Access; Props : in ASF.Applications.Config); -- Configures the module after its initialization and after having read its XML configuration. overriding procedure Configure (Plugin : in out Image_Module; Props : in ASF.Applications.Config); -- Get the image manager. function Get_Image_Manager (Plugin : in Image_Module) return Services.Image_Service_Access; -- Create an image manager. This operation can be overridden to provide another -- image service implementation. function Create_Image_Manager (Plugin : in Image_Module) return Services.Image_Service_Access; -- The `On_Create` procedure is called by `Notify_Create` to notify the creation of the item. overriding procedure On_Create (Instance : in Image_Module; Item : in AWA.Storages.Models.Storage_Ref'Class); -- The `On_Update` procedure is called by `Notify_Update` to notify the update of the item. overriding procedure On_Update (Instance : in Image_Module; Item : in AWA.Storages.Models.Storage_Ref'Class); -- The `On_Delete` procedure is called by `Notify_Delete` to notify the deletion of the item. overriding procedure On_Delete (Instance : in Image_Module; Item : in AWA.Storages.Models.Storage_Ref'Class); -- Create a thumbnail job for the image. procedure Make_Thumbnail_Job (Plugin : in Image_Module; Image : in AWA.Images.Models.Image_Ref'Class); -- Thumbnail job to identify the image dimension and produce a thumbnail. procedure Do_Thumbnail_Job (Plugin : in Image_Module; Job : in out AWA.Jobs.Services.Abstract_Job_Type'Class); -- Get the image module instance associated with the current application. function Get_Image_Module return Image_Module_Access; -- Get the image manager instance associated with the current application. function Get_Image_Manager return Services.Image_Service_Access; -- Returns true if the storage file has an image mime type. function Is_Image (File : in AWA.Storages.Models.Storage_Ref'Class) return Boolean; private type Image_Module is new AWA.Modules.Module and AWA.Storages.Services.Listener with record Manager : Services.Image_Service_Access := null; Job_Module : AWA.Jobs.Modules.Job_Module_Access; end record; -- Create an image instance. procedure Create_Image (Plugin : in Image_Module; File : in AWA.Storages.Models.Storage_Ref'Class); end AWA.Images.Modules;
----------------------------------------------------------------------- -- awa-images-modules -- Image management module -- Copyright (C) 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 ASF.Applications; with AWA.Modules; with AWA.Storages.Models; with AWA.Storages.Services; with AWA.Images.Services; with AWA.Images.Models; with AWA.Jobs.Services; with AWA.Jobs.Modules; with AWA.Images.Servlets; -- == Image Module == -- The <tt>Image_Module</tt> type represents the image module. An instance of the image -- module must be declared and registered when the application is created and initialized. -- The image module is associated with the image service which provides and implements -- the image management operations. -- -- When the image module is initialized, it registers itself as a listener to the storage -- module to be notified when a storage file is created, updated or removed. When a file -- is added, it looks at the file type and extracts the image information if the storage file -- is an image. package AWA.Images.Modules is NAME : constant String := "images"; -- Job worker procedure to identify an image and generate its thumnbnail. procedure Thumbnail_Worker (Job : in out AWA.Jobs.Services.Abstract_Job_Type'Class); package Thumbnail_Job_Definition is new AWA.Jobs.Services.Work_Definition (Thumbnail_Worker'Access); type Image_Module is new AWA.Modules.Module and AWA.Storages.Services.Listener with private; type Image_Module_Access is access all Image_Module'Class; -- Initialize the image module. overriding procedure Initialize (Plugin : in out Image_Module; App : in AWA.Modules.Application_Access; Props : in ASF.Applications.Config); -- Configures the module after its initialization and after having read its XML configuration. overriding procedure Configure (Plugin : in out Image_Module; Props : in ASF.Applications.Config); -- Get the image manager. function Get_Image_Manager (Plugin : in Image_Module) return Services.Image_Service_Access; -- Create an image manager. This operation can be overridden to provide another -- image service implementation. function Create_Image_Manager (Plugin : in Image_Module) return Services.Image_Service_Access; -- The `On_Create` procedure is called by `Notify_Create` to notify the creation of the item. overriding procedure On_Create (Instance : in Image_Module; Item : in AWA.Storages.Models.Storage_Ref'Class); -- The `On_Update` procedure is called by `Notify_Update` to notify the update of the item. overriding procedure On_Update (Instance : in Image_Module; Item : in AWA.Storages.Models.Storage_Ref'Class); -- The `On_Delete` procedure is called by `Notify_Delete` to notify the deletion of the item. overriding procedure On_Delete (Instance : in Image_Module; Item : in AWA.Storages.Models.Storage_Ref'Class); -- Create a thumbnail job for the image. procedure Make_Thumbnail_Job (Plugin : in Image_Module; Image : in AWA.Images.Models.Image_Ref'Class); -- Thumbnail job to identify the image dimension and produce a thumbnail. procedure Do_Thumbnail_Job (Plugin : in Image_Module; Job : in out AWA.Jobs.Services.Abstract_Job_Type'Class); -- Get the image module instance associated with the current application. function Get_Image_Module return Image_Module_Access; -- Get the image manager instance associated with the current application. function Get_Image_Manager return Services.Image_Service_Access; -- Returns true if the storage file has an image mime type. function Is_Image (File : in AWA.Storages.Models.Storage_Ref'Class) return Boolean; private type Image_Module is new AWA.Modules.Module and AWA.Storages.Services.Listener with record Manager : Services.Image_Service_Access := null; Job_Module : AWA.Jobs.Modules.Job_Module_Access; Image_Servlet : aliased AWA.Images.Servlets.Image_Servlet; end record; -- Create an image instance. procedure Create_Image (Plugin : in Image_Module; File : in AWA.Storages.Models.Storage_Ref'Class); end AWA.Images.Modules;
Add the image servlet to the image module plugin
Add the image servlet to the image module plugin
Ada
apache-2.0
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
68b30614a41ac605f2f5f74f1260ef0d13e240ee
mat/src/mat-readers-marshaller.adb
mat/src/mat-readers-marshaller.adb
----------------------------------------------------------------------- -- mat-readers-marshaller -- Marshalling of data in communication buffer -- Copyright (C) 2014 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Interfaces; with System; with System.Address_To_Access_Conversions; with System.Storage_Elements; with Util.Log.Loggers; package body MAT.Readers.Marshaller is use type System.Storage_Elements.Storage_Offset; use type Interfaces.Unsigned_32; use type Interfaces.Unsigned_64; -- The logger Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("MAT.Readers.Marshaller"); package Uint8_Access is new System.Address_To_Access_Conversions (MAT.Types.Uint8); package Uint32_Access is new System.Address_To_Access_Conversions (MAT.Types.Uint32); -- ------------------------------ -- Get an 8-bit value from the buffer. -- ------------------------------ function Get_Uint8 (Buffer : in Buffer_Ptr) return MAT.Types.Uint8 is use Uint8_Access; P : constant Object_Pointer := To_Pointer (Buffer.Current); begin if Buffer.Size = 0 then Log.Error ("Not enough data to get a uint8"); raise Buffer_Underflow_Error; end if; Buffer.Size := Buffer.Size - 1; Buffer.Current := Buffer.Current + System.Storage_Elements.Storage_Offset (1); return P.all; end Get_Uint8; -- ------------------------------ -- Get a 16-bit value either from big-endian or little endian. -- ------------------------------ function Get_Uint16 (Buffer : in Buffer_Ptr) return MAT.Types.Uint16 is use Uint8_Access; High : Object_Pointer; Low : Object_Pointer; begin if Buffer.Size <= 1 then Log.Error ("Not enough data to get a uint16"); raise Buffer_Underflow_Error; end if; if Buffer.Endian = LITTLE_ENDIAN then Low := To_Pointer (Buffer.Current); High := To_Pointer (Buffer.Current + System.Storage_Elements.Storage_Offset (1)); else High := To_Pointer (Buffer.Current); Low := To_Pointer (Buffer.Current + System.Storage_Elements.Storage_Offset (1)); end if; Buffer.Size := Buffer.Size - 2; Buffer.Current := Buffer.Current + System.Storage_Elements.Storage_Offset (2); return MAT.Types.Uint16 (High.all) * 256 + MAT.Types.Uint16 (Low.all); end Get_Uint16; -- ------------------------------ -- Get a 32-bit value either from big-endian or little endian. -- ------------------------------ function Get_Uint32 (Buffer : in Buffer_Ptr) return MAT.Types.Uint32 is use Uint32_Access; Low, High : MAT.Types.Uint16; begin if Buffer.Size < 4 then Log.Error ("Not enough data to get a uint32"); raise Buffer_Underflow_Error; end if; if Buffer.Endian = LITTLE_ENDIAN then Low := Get_Uint16 (Buffer); High := Get_Uint16 (Buffer); else High := Get_Uint16 (Buffer); Low := Get_Uint16 (Buffer); end if; return Interfaces.Shift_Left (MAT.Types.Uint32 (High), 16) + MAT.Types.Uint32 (Low); end Get_Uint32; -- ------------------------------ -- Get a 64-bit value either from big-endian or little endian. -- ------------------------------ function Get_Uint64 (Buffer : in Buffer_Ptr) return MAT.Types.Uint64 is Low : MAT.Types.Uint32; High : MAT.Types.Uint32; begin if Buffer.Endian = LITTLE_ENDIAN then Low := Get_Uint32 (Buffer); High := Get_Uint32 (Buffer); else High := Get_Uint32 (Buffer); Low := Get_Uint32 (Buffer); end if; return Interfaces.Shift_Left (MAT.Types.Uint64 (High), 32) + MAT.Types.Uint64 (Low); end Get_Uint64; function Get_Target_Value (Msg : in Buffer_Ptr; Kind : in MAT.Events.Attribute_Type) return Target_Type is begin case Kind is when MAT.Events.T_UINT8 => return Target_Type (Get_Uint8 (Msg)); when MAT.Events.T_UINT16 => return Target_Type (Get_Uint16 (Msg)); when MAT.Events.T_UINT32 => return Target_Type (Get_Uint32 (Msg)); when MAT.Events.T_UINT64 => return Target_Type (Get_Uint64 (Msg)); when others => Log.Error ("Invalid attribute type {0}", MAT.Events.Attribute_Type'Image (Kind)); return 0; end case; end Get_Target_Value; -- ------------------------------ -- Extract a string from the buffer. The string starts with a byte that -- indicates the string length. -- ------------------------------ function Get_String (Buffer : in Buffer_Ptr) return String is Len : constant MAT.Types.Uint8 := Get_Uint8 (Buffer); Result : String (1 .. Natural (Len)); begin for I in Result'Range loop Result (I) := Character'Val (Get_Uint8 (Buffer)); end loop; return Result; end Get_String; -- ------------------------------ -- Extract a string from the buffer. The string starts with a byte that -- indicates the string length. -- ------------------------------ function Get_String (Msg : in Buffer_Ptr) return Ada.Strings.Unbounded.Unbounded_String is begin return Ada.Strings.Unbounded.To_Unbounded_String (Get_String (Msg)); end Get_String; -- ------------------------------ -- Skip the given number of bytes from the message. -- ------------------------------ procedure Skip (Buffer : in Buffer_Ptr; Size : in Natural) is begin Buffer.Size := Buffer.Size - Size; Buffer.Current := Buffer.Current + System.Storage_Elements.Storage_Offset (Size); end Skip; function Get_Target_Size (Msg : in Buffer_Ptr; Kind : in MAT.Events.Attribute_Type) return MAT.Types.Target_Size is function Get_Value is new Get_Target_Value (MAT.Types.Target_Size); begin return Get_Value (Msg, Kind); end Get_Target_Size; function Get_Target_Addr (Msg : in Buffer_Ptr; Kind : in MAT.Events.Attribute_Type) return MAT.Types.Target_Addr is function Get_Value is new Get_Target_Value (MAT.Types.Target_Addr); begin return Get_Value (Msg, Kind); end Get_Target_Addr; function Get_Target_Uint32 (Msg : in Buffer_Ptr; Kind : in MAT.Events.Attribute_Type) return MAT.Types.Uint32 is function Get_Value is new Get_Target_Value (MAT.Types.Target_Addr); begin return Get_Value (Msg, Kind); end Get_Target_Uint32; end MAT.Readers.Marshaller;
----------------------------------------------------------------------- -- mat-readers-marshaller -- Marshalling of data in communication buffer -- Copyright (C) 2014 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Interfaces; with System; with System.Address_To_Access_Conversions; with System.Storage_Elements; with Util.Log.Loggers; package body MAT.Readers.Marshaller is use type System.Storage_Elements.Storage_Offset; use type Interfaces.Unsigned_32; use type Interfaces.Unsigned_64; -- The logger Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("MAT.Readers.Marshaller"); package Uint8_Access is new System.Address_To_Access_Conversions (MAT.Types.Uint8); package Uint32_Access is new System.Address_To_Access_Conversions (MAT.Types.Uint32); -- ------------------------------ -- Get an 8-bit value from the buffer. -- ------------------------------ function Get_Uint8 (Buffer : in Buffer_Ptr) return MAT.Types.Uint8 is use Uint8_Access; P : constant Object_Pointer := To_Pointer (Buffer.Current); begin if Buffer.Size = 0 then Log.Error ("Not enough data to get a uint8"); raise Buffer_Underflow_Error; end if; Buffer.Size := Buffer.Size - 1; Buffer.Current := Buffer.Current + System.Storage_Elements.Storage_Offset (1); return P.all; end Get_Uint8; -- ------------------------------ -- Get a 16-bit value either from big-endian or little endian. -- ------------------------------ function Get_Uint16 (Buffer : in Buffer_Ptr) return MAT.Types.Uint16 is use Uint8_Access; High : Object_Pointer; Low : Object_Pointer; begin if Buffer.Size <= 1 then Log.Error ("Not enough data to get a uint16"); raise Buffer_Underflow_Error; end if; if Buffer.Endian = LITTLE_ENDIAN then Low := To_Pointer (Buffer.Current); High := To_Pointer (Buffer.Current + System.Storage_Elements.Storage_Offset (1)); else High := To_Pointer (Buffer.Current); Low := To_Pointer (Buffer.Current + System.Storage_Elements.Storage_Offset (1)); end if; Buffer.Size := Buffer.Size - 2; Buffer.Current := Buffer.Current + System.Storage_Elements.Storage_Offset (2); return MAT.Types.Uint16 (High.all) * 256 + MAT.Types.Uint16 (Low.all); end Get_Uint16; -- ------------------------------ -- Get a 32-bit value either from big-endian or little endian. -- ------------------------------ function Get_Uint32 (Buffer : in Buffer_Ptr) return MAT.Types.Uint32 is use Uint32_Access; Low, High : MAT.Types.Uint16; begin if Buffer.Size < 4 then Log.Error ("Not enough data to get a uint32"); raise Buffer_Underflow_Error; end if; if Buffer.Endian = LITTLE_ENDIAN then Low := Get_Uint16 (Buffer); High := Get_Uint16 (Buffer); else High := Get_Uint16 (Buffer); Low := Get_Uint16 (Buffer); end if; return Interfaces.Shift_Left (MAT.Types.Uint32 (High), 16) + MAT.Types.Uint32 (Low); end Get_Uint32; -- ------------------------------ -- Get a 64-bit value either from big-endian or little endian. -- ------------------------------ function Get_Uint64 (Buffer : in Buffer_Ptr) return MAT.Types.Uint64 is Low : MAT.Types.Uint32; High : MAT.Types.Uint32; begin if Buffer.Endian = LITTLE_ENDIAN then Low := Get_Uint32 (Buffer); High := Get_Uint32 (Buffer); else High := Get_Uint32 (Buffer); Low := Get_Uint32 (Buffer); end if; return Interfaces.Shift_Left (MAT.Types.Uint64 (High), 32) + MAT.Types.Uint64 (Low); end Get_Uint64; function Get_Target_Value (Msg : in Buffer_Ptr; Kind : in MAT.Events.Attribute_Type) return Target_Type is begin case Kind is when MAT.Events.T_UINT8 => return Target_Type (Get_Uint8 (Msg)); when MAT.Events.T_UINT16 => return Target_Type (Get_Uint16 (Msg)); when MAT.Events.T_UINT32 => return Target_Type (Get_Uint32 (Msg)); when MAT.Events.T_UINT64 => return Target_Type (Get_Uint64 (Msg)); when others => Log.Error ("Invalid attribute type {0}", MAT.Events.Attribute_Type'Image (Kind)); return 0; end case; end Get_Target_Value; -- ------------------------------ -- Extract a string from the buffer. The string starts with a byte that -- indicates the string length. -- ------------------------------ function Get_String (Buffer : in Buffer_Ptr) return String is Len : constant MAT.Types.Uint16 := Get_Uint16 (Buffer); Result : String (1 .. Natural (Len)); begin for I in Result'Range loop Result (I) := Character'Val (Get_Uint8 (Buffer)); end loop; return Result; end Get_String; -- ------------------------------ -- Extract a string from the buffer. The string starts with a byte that -- indicates the string length. -- ------------------------------ function Get_String (Msg : in Buffer_Ptr) return Ada.Strings.Unbounded.Unbounded_String is begin return Ada.Strings.Unbounded.To_Unbounded_String (Get_String (Msg)); end Get_String; -- ------------------------------ -- Skip the given number of bytes from the message. -- ------------------------------ procedure Skip (Buffer : in Buffer_Ptr; Size : in Natural) is begin Buffer.Size := Buffer.Size - Size; Buffer.Current := Buffer.Current + System.Storage_Elements.Storage_Offset (Size); end Skip; function Get_Target_Size (Msg : in Buffer_Ptr; Kind : in MAT.Events.Attribute_Type) return MAT.Types.Target_Size is function Get_Value is new Get_Target_Value (MAT.Types.Target_Size); begin return Get_Value (Msg, Kind); end Get_Target_Size; function Get_Target_Addr (Msg : in Buffer_Ptr; Kind : in MAT.Events.Attribute_Type) return MAT.Types.Target_Addr is function Get_Value is new Get_Target_Value (MAT.Types.Target_Addr); begin return Get_Value (Msg, Kind); end Get_Target_Addr; function Get_Target_Uint32 (Msg : in Buffer_Ptr; Kind : in MAT.Events.Attribute_Type) return MAT.Types.Uint32 is function Get_Value is new Get_Target_Value (MAT.Types.Target_Addr); begin return Get_Value (Msg, Kind); end Get_Target_Uint32; end MAT.Readers.Marshaller;
Use 16-bit for the string length
Use 16-bit for the string length
Ada
apache-2.0
stcarrez/mat,stcarrez/mat,stcarrez/mat
dedb61a7b372a90d1eb44800c5677fbb8042fc0a
awa/plugins/awa-questions/src/awa-questions-modules.adb
awa/plugins/awa-questions/src/awa-questions-modules.adb
----------------------------------------------------------------------- -- awa-questions-modules -- 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 Util.Log.Loggers; with AWA.Modules.Beans; with AWA.Modules.Get; with AWA.Questions.Beans; with AWA.Applications; package body AWA.Questions.Modules is Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("AWA.Questions.Module"); package Register is new AWA.Modules.Beans (Module => Question_Module, Module_Access => Question_Module_Access); -- ------------------------------ -- Initialize the questions module. -- ------------------------------ overriding procedure Initialize (Plugin : in out Question_Module; App : in AWA.Modules.Application_Access; Props : in ASF.Applications.Config) is begin Log.Info ("Initializing the questions module"); -- Setup the resource bundles. App.Register ("questionMsg", "questions"); -- Edit and save a question. Register.Register (Plugin => Plugin, Name => "AWA.Questions.Beans.Question_Bean", Handler => AWA.Questions.Beans.Create_Question_Bean'Access); -- Edit and save an answer. Register.Register (Plugin => Plugin, Name => "AWA.Questions.Beans.Answer_Bean", Handler => AWA.Questions.Beans.Create_Answer_Bean'Access); -- List of questions. Register.Register (Plugin => Plugin, Name => "AWA.Questions.Beans.Question_List_Bean", Handler => AWA.Questions.Beans.Create_Question_List_Bean'Access); -- Display a question with its answers. Register.Register (Plugin => Plugin, Name => "AWA.Questions.Beans.Question_Display_Bean", Handler => AWA.Questions.Beans.Create_Question_Display_Bean'Access); AWA.Modules.Module (Plugin).Initialize (App, Props); -- Add here the creation of manager instances. Plugin.Manager := Plugin.Create_Question_Manager; end Initialize; -- ------------------------------ -- Get the question manager. -- ------------------------------ function Get_Question_Manager (Plugin : in Question_Module) return Services.Question_Service_Access is begin return Plugin.Manager; end Get_Question_Manager; -- ------------------------------ -- Create a question manager. This operation can be overridden to provide another -- question service implementation. -- ------------------------------ function Create_Question_Manager (Plugin : in Question_Module) return Services.Question_Service_Access is Result : constant Services.Question_Service_Access := new Services.Question_Service; begin Result.Initialize (Plugin); return Result; end Create_Question_Manager; -- ------------------------------ -- Get the questions module. -- ------------------------------ function Get_Question_Module return Question_Module_Access is function Get is new AWA.Modules.Get (Question_Module, Question_Module_Access, NAME); begin return Get; end Get_Question_Module; -- ------------------------------ -- Get the question manager instance associated with the current application. -- ------------------------------ function Get_Question_Manager return Services.Question_Service_Access is Module : constant Question_Module_Access := Get_Question_Module; begin if Module = null then Log.Error ("There is no active Question_Module"); return null; else return Module.Get_Question_Manager; end if; end Get_Question_Manager; end AWA.Questions.Modules;
----------------------------------------------------------------------- -- awa-questions-modules -- 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 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; with AWA.Modules.Beans; with AWA.Modules.Get; with AWA.Questions.Beans; with AWA.Applications; package body AWA.Questions.Modules is Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("AWA.Questions.Module"); package Register is new AWA.Modules.Beans (Module => Question_Module, Module_Access => Question_Module_Access); -- ------------------------------ -- Initialize the questions module. -- ------------------------------ overriding procedure Initialize (Plugin : in out Question_Module; App : in AWA.Modules.Application_Access; Props : in ASF.Applications.Config) is begin Log.Info ("Initializing the questions module"); -- Setup the resource bundles. App.Register ("questionMsg", "questions"); -- Edit and save a question. Register.Register (Plugin => Plugin, Name => "AWA.Questions.Beans.Question_Bean", Handler => AWA.Questions.Beans.Create_Question_Bean'Access); -- Edit and save an answer. Register.Register (Plugin => Plugin, Name => "AWA.Questions.Beans.Answer_Bean", Handler => AWA.Questions.Beans.Create_Answer_Bean'Access); -- List of questions. Register.Register (Plugin => Plugin, Name => "AWA.Questions.Beans.Question_List_Bean", Handler => AWA.Questions.Beans.Create_Question_List_Bean'Access); -- Display a question with its answers. Register.Register (Plugin => Plugin, Name => "AWA.Questions.Beans.Question_Display_Bean", Handler => AWA.Questions.Beans.Create_Question_Display_Bean'Access); AWA.Modules.Module (Plugin).Initialize (App, Props); end Initialize; -- ------------------------------ -- Get the questions module. -- ------------------------------ function Get_Question_Module return Question_Module_Access is function Get is new AWA.Modules.Get (Question_Module, Question_Module_Access, NAME); begin return Get; end Get_Question_Module; -- ------------------------------ -- Create or save the question. -- ------------------------------ procedure Save_Question (Model : in Question_Module; 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 Services.Contexts.Service_Context_Access := AWA.Services.Contexts.Current; User : constant AWA.Users.Models.User_Ref := Ctx.Get_User; DB : ADO.Sessions.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_Module; Question : in out AWA.Questions.Models.Question_Ref'Class) is pragma Unreferenced (Model); Ctx : constant Services.Contexts.Service_Context_Access := AWA.Services.Contexts.Current; DB : ADO.Sessions.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_Module; Question : in out AWA.Questions.Models.Question_Ref'Class; Id : in ADO.Identifier) is pragma Unreferenced (Model); Ctx : constant Services.Contexts.Service_Context_Access := AWA.Services.Contexts.Current; DB : ADO.Sessions.Session := AWA.Services.Contexts.Get_Session (Ctx); Found : Boolean; begin Question.Load (DB, Id, Found); end Load_Question; -- ------------------------------ -- Create or save the answer. -- ------------------------------ procedure Save_Answer (Model : in Question_Module; Question : in AWA.Questions.Models.Question_Ref'Class; Answer : in out AWA.Questions.Models.Answer_Ref'Class) is pragma Unreferenced (Model); Ctx : constant Services.Contexts.Service_Context_Access := AWA.Services.Contexts.Current; User : constant AWA.Users.Models.User_Ref := Ctx.Get_User; DB : ADO.Sessions.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; -- ------------------------------ -- Delete the answer. -- ------------------------------ procedure Delete_Answer (Model : in Question_Module; Answer : in out AWA.Questions.Models.Answer_Ref'Class) is pragma Unreferenced (Model); Ctx : constant Services.Contexts.Service_Context_Access := AWA.Services.Contexts.Current; DB : ADO.Sessions.Master_Session := AWA.Services.Contexts.Get_Master_Session (Ctx); begin Ctx.Start; -- Check that the user has the delete permission on the given answer. AWA.Permissions.Check (Permission => ACL_Delete_Answer.Permission, Entity => Answer); Answer.Delete (DB); Ctx.Commit; end Delete_Answer; -- ------------------------------ -- Load the answer. -- ------------------------------ procedure Load_Answer (Model : in Question_Module; 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 Services.Contexts.Service_Context_Access := AWA.Services.Contexts.Current; DB : ADO.Sessions.Session := AWA.Services.Contexts.Get_Session (Ctx); Found : Boolean; begin Answer.Load (DB, Id, Found); Question := Answer.Get_Question; end Load_Answer; end AWA.Questions.Modules;
Move the question services in the question module (simplify the implementation)
Move the question services in the question module (simplify the implementation)
Ada
apache-2.0
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
b0b8d909c7179d9f2e4acb6c67d5a50da0c3f2a9
samples/import.adb
samples/import.adb
----------------------------------------------------------------------- -- import -- Import some HTML content and generate Wiki text -- 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.Text_IO; with Ada.IO_Exceptions; with Ada.Strings.Unbounded; with Ada.Characters.Conversions; with GNAT.Command_Line; with Util.Files; with Util.Streams.Pipes; with Util.Streams.Buffered; with Util.Strings.Transforms; with Wiki.Parsers; with Wiki.Filters.Html; with Wiki.Writers.Builders; with Wiki.Render.Html; with Wiki.Render.Text; with Wiki.Render.Wiki; procedure Import is use GNAT.Command_Line; use Ada.Strings.Unbounded; use Ada.Characters.Conversions; procedure Usage; function Is_Url (Name : in String) return Boolean; procedure Parse_Url (Url : in String); procedure Parse (Content : in String); Html_Filter : aliased Wiki.Filters.Html.Html_Filter_Type; Count : Natural := 0; Html_Mode : Boolean := True; Wiki_Mode : Boolean := False; Syntax : Wiki.Parsers.Wiki_Syntax_Type := Wiki.Parsers.SYNTAX_MARKDOWN; procedure Usage is begin Ada.Text_IO.Put_Line ("Usage: import [-t] [-m] [-M] [-d] [-c] {URL | file}"); Ada.Text_IO.Put_Line (" -t Convert to text only"); Ada.Text_IO.Put_Line (" -m Convert to Markdown"); Ada.Text_IO.Put_Line (" -M Convert to Mediawiki"); Ada.Text_IO.Put_Line (" -d Convert to Dotclear"); Ada.Text_IO.Put_Line (" -c Convert to Creole"); end Usage; procedure Parse (Content : in String) is begin if Wiki_Mode then declare Writer : aliased Wiki.Writers.Builders.Writer_Builder_Type; Renderer : aliased Wiki.Render.Wiki.Wiki_Renderer; begin Renderer.Set_Writer (Writer'Unchecked_Access, Syntax); Html_Filter.Set_Document (Renderer'Unchecked_Access); Wiki.Parsers.Parse (Html_Filter'Unchecked_Access, To_Wide_Wide_String (Content), Wiki.Parsers.SYNTAX_HTML); Ada.Text_IO.Put_Line (Writer.To_String); end; elsif Html_Mode then declare Writer : aliased Wiki.Writers.Builders.Html_Writer_Type; Renderer : aliased Wiki.Render.Html.Html_Renderer; begin Renderer.Set_Writer (Writer'Unchecked_Access); Html_Filter.Set_Document (Renderer'Unchecked_Access); Wiki.Parsers.Parse (Html_Filter'Unchecked_Access, To_Wide_Wide_String (Content), Syntax); Ada.Text_IO.Put_Line (Writer.To_String); end; else declare Writer : aliased Wiki.Writers.Builders.Writer_Builder_Type; Renderer : aliased Wiki.Render.Text.Text_Renderer; begin Renderer.Set_Writer (Writer'Unchecked_Access); Html_Filter.Set_Document (Renderer'Unchecked_Access); Wiki.Parsers.Parse (Html_Filter'Unchecked_Access, To_Wide_Wide_String (Content), Syntax); Ada.Text_IO.Put_Line (Writer.To_String); end; end if; end Parse; procedure Parse_Url (Url : in String) is Command : constant String := "wget -q -O - " & Url; Pipe : aliased Util.Streams.Pipes.Pipe_Stream; Buffer : Util.Streams.Buffered.Buffered_Stream; Content : Ada.Strings.Unbounded.Unbounded_String; begin Pipe.Open (Command); Buffer.Initialize (null, Pipe'Unchecked_Access, 1024 * 1024); Buffer.Read (Content); Pipe.Close; if Pipe.Get_Exit_Status /= 0 then Ada.Text_IO.Put_Line (Command & " exited with status " & Integer'Image (Pipe.Get_Exit_Status)); else Parse (To_String (Content)); end if; end Parse_Url; function Is_Url (Name : in String) return Boolean is begin if Name'Length <= 9 then return False; else return Name (Name'First .. Name'First + 6) = "http://" or Name (Name'First .. Name'First + 7) = "https://"; end if; end Is_Url; begin loop case Getopt ("m M d c t f:") is when 'm' => Syntax := Wiki.Parsers.SYNTAX_MARKDOWN; Wiki_Mode := True; when 'M' => Syntax := Wiki.Parsers.SYNTAX_MEDIA_WIKI; Wiki_Mode := True; when 'c' => Syntax := Wiki.Parsers.SYNTAX_CREOLE; Wiki_Mode := True; when 'd' => Syntax := Wiki.Parsers.SYNTAX_DOTCLEAR; Wiki_Mode := True; when 't' => Html_Mode := False; when 'f' => declare Value : constant String := Util.Strings.Transforms.To_Upper_Case (Parameter); begin Html_Filter.Hide (Wiki.Filters.Html.Html_Tag_Type'Value (Value & "_TAG")); exception when Constraint_Error => Ada.Text_IO.Put_Line ("Invalid tag " & Value); end; when others => exit; end case; end loop; loop declare Name : constant String := GNAT.Command_Line.Get_Argument; Data : Unbounded_String; begin if Name = "" then if Count = 0 then Usage; end if; return; end if; Count := Count + 1; if Is_Url (Name) then Parse_Url (Name); else Util.Files.Read_File (Name, Data); Parse (To_String (Data)); end if; exception when Ada.IO_Exceptions.Name_Error => Ada.Text_IO.Put_Line ("Cannot read file '" & Name & "'"); end; end loop; exception when Invalid_Switch => Ada.Text_IO.Put_Line ("Invalid option."); Usage; end Import;
----------------------------------------------------------------------- -- import -- Import some HTML content and generate Wiki text -- 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.Text_IO; with Ada.IO_Exceptions; with Ada.Strings.Unbounded; with Ada.Characters.Conversions; with GNAT.Command_Line; with Util.Files; with Util.Streams.Pipes; with Util.Streams.Buffered; with Util.Strings.Transforms; with Wiki.Parsers; with Wiki.Filters.Html; with Wiki.Writers.Builders; with Wiki.Render.Html; with Wiki.Render.Text; with Wiki.Render.Wiki; procedure Import is use GNAT.Command_Line; use Ada.Strings.Unbounded; use Ada.Characters.Conversions; procedure Usage; function Is_Url (Name : in String) return Boolean; procedure Parse_Url (Url : in String); procedure Parse (Content : in String); Html_Filter : aliased Wiki.Filters.Html.Html_Filter_Type; Count : Natural := 0; Html_Mode : Boolean := True; Wiki_Mode : Boolean := False; Syntax : Wiki.Parsers.Wiki_Syntax_Type := Wiki.Parsers.SYNTAX_MARKDOWN; procedure Usage is begin Ada.Text_IO.Put_Line ("Import HTML into a target Wiki format"); Ada.Text_IO.Put_Line ("Usage: import [-t] [-m] [-M] [-d] [-c] {URL | file}"); Ada.Text_IO.Put_Line (" -t Convert to text only"); Ada.Text_IO.Put_Line (" -m Convert to Markdown"); Ada.Text_IO.Put_Line (" -M Convert to Mediawiki"); Ada.Text_IO.Put_Line (" -d Convert to Dotclear"); Ada.Text_IO.Put_Line (" -c Convert to Creole"); end Usage; procedure Parse (Content : in String) is begin if Wiki_Mode then declare Writer : aliased Wiki.Writers.Builders.Writer_Builder_Type; Renderer : aliased Wiki.Render.Wiki.Wiki_Renderer; begin Renderer.Set_Writer (Writer'Unchecked_Access, Syntax); Html_Filter.Set_Document (Renderer'Unchecked_Access); Wiki.Parsers.Parse (Html_Filter'Unchecked_Access, To_Wide_Wide_String (Content), Wiki.Parsers.SYNTAX_HTML); Ada.Text_IO.Put_Line (Writer.To_String); end; elsif Html_Mode then declare Writer : aliased Wiki.Writers.Builders.Html_Writer_Type; Renderer : aliased Wiki.Render.Html.Html_Renderer; begin Renderer.Set_Writer (Writer'Unchecked_Access); Html_Filter.Set_Document (Renderer'Unchecked_Access); Wiki.Parsers.Parse (Html_Filter'Unchecked_Access, To_Wide_Wide_String (Content), Syntax); Ada.Text_IO.Put_Line (Writer.To_String); end; else declare Writer : aliased Wiki.Writers.Builders.Writer_Builder_Type; Renderer : aliased Wiki.Render.Text.Text_Renderer; begin Renderer.Set_Writer (Writer'Unchecked_Access); Html_Filter.Set_Document (Renderer'Unchecked_Access); Wiki.Parsers.Parse (Html_Filter'Unchecked_Access, To_Wide_Wide_String (Content), Syntax); Ada.Text_IO.Put_Line (Writer.To_String); end; end if; end Parse; procedure Parse_Url (Url : in String) is Command : constant String := "wget -q -O - " & Url; Pipe : aliased Util.Streams.Pipes.Pipe_Stream; Buffer : Util.Streams.Buffered.Buffered_Stream; Content : Ada.Strings.Unbounded.Unbounded_String; begin Pipe.Open (Command); Buffer.Initialize (null, Pipe'Unchecked_Access, 1024 * 1024); Buffer.Read (Content); Pipe.Close; if Pipe.Get_Exit_Status /= 0 then Ada.Text_IO.Put_Line (Command & " exited with status " & Integer'Image (Pipe.Get_Exit_Status)); else Parse (To_String (Content)); end if; end Parse_Url; function Is_Url (Name : in String) return Boolean is begin if Name'Length <= 9 then return False; else return Name (Name'First .. Name'First + 6) = "http://" or Name (Name'First .. Name'First + 7) = "https://"; end if; end Is_Url; begin loop case Getopt ("m M d c t f:") is when 'm' => Syntax := Wiki.Parsers.SYNTAX_MARKDOWN; Wiki_Mode := True; when 'M' => Syntax := Wiki.Parsers.SYNTAX_MEDIA_WIKI; Wiki_Mode := True; when 'c' => Syntax := Wiki.Parsers.SYNTAX_CREOLE; Wiki_Mode := True; when 'd' => Syntax := Wiki.Parsers.SYNTAX_DOTCLEAR; Wiki_Mode := True; when 't' => Html_Mode := False; when 'f' => declare Value : constant String := Util.Strings.Transforms.To_Upper_Case (Parameter); begin Html_Filter.Hide (Wiki.Filters.Html.Html_Tag_Type'Value (Value & "_TAG")); exception when Constraint_Error => Ada.Text_IO.Put_Line ("Invalid tag " & Value); end; when others => exit; end case; end loop; loop declare Name : constant String := GNAT.Command_Line.Get_Argument; Data : Unbounded_String; begin if Name = "" then if Count = 0 then Usage; end if; return; end if; Count := Count + 1; if Is_Url (Name) then Parse_Url (Name); else Util.Files.Read_File (Name, Data); Parse (To_String (Data)); end if; exception when Ada.IO_Exceptions.Name_Error => Ada.Text_IO.Put_Line ("Cannot read file '" & Name & "'"); end; end loop; exception when Invalid_Switch => Ada.Text_IO.Put_Line ("Invalid option."); Usage; end Import;
Add a short usage description
Add a short usage description
Ada
apache-2.0
stcarrez/ada-wiki,stcarrez/ada-wiki
9c94fbf703424bc8e8fad1bea8453ef0ac49518c
src/ado-parameters.ads
src/ado-parameters.ads
----------------------------------------------------------------------- -- ADO Parameters -- Parameters for queries -- 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 Ada.Strings.Unbounded; with Ada.Finalization; with Ada.Calendar; with Ada.Containers.Indefinite_Vectors; with ADO.Utils; with ADO.Drivers.Dialects; -- === Query Parameters === -- Query parameters are represented by the <tt>Parameter</tt> type which can represent almost -- all database types including boolean, numbers, strings, dates and blob. Parameters are -- put in a list represented by the <tt>Abstract_List</tt> or <tt>List</tt> types. -- -- A parameter is added by using either the <tt>Bind_Param</tt> or the <tt>Add_Param</tt> -- operation. The <tt>Bind_Param</tt> operation allows to specify either the parameter name -- or its position. The <tt>Add_Param</tt> operation adds the parameter at end of the list -- and uses the last position. In most cases, it is easier to bind a parameter with a name -- as follows: -- -- Query.Bind_Param ("name", "Joe"); -- -- and the SQL can use the following construct: -- -- SELECT * FROM user WHERE name = :name -- -- When the <tt>Add_Param</tt> is used, the parameter is not associated with any name but it -- as a position index. Setting a parameter is easier: -- -- Query.Add_Param ("Joe"); -- -- but the SQL cannot make any reference to names and must use the <tt>?</tt> construct: -- -- SELECT * FROM user WHERE name = ? -- -- === Parameter Expander === -- The parameter expander is a mechanism that allows to replace or inject values in the SQL -- query by looking at an operation provided by the <tt>Expander</tt> interface. Such expander -- is useful to replace parameters that are global to a session or to an application. -- package ADO.Parameters is use Ada.Strings.Unbounded; type Token is new String; type Parameter_Type is (T_NULL, T_STRING, T_TOKEN, T_LIST, T_DATE, T_LONG_INTEGER, T_INTEGER, T_BOOLEAN, T_BLOB); type Parameter (T : Parameter_Type; Len : Natural; Value_Len : Natural) is record Position : Natural := 0; Name : String (1 .. Len); case T is when T_NULL => null; when T_LONG_INTEGER => Long_Num : Long_Long_Integer := 0; when T_INTEGER => Num : Integer; when T_BOOLEAN => Bool : Boolean; when T_DATE => Time : Ada.Calendar.Time; when T_BLOB => Data : ADO.Blob_Ref; when others => Str : String (1 .. Value_Len); end case; end record; type Expander is limited interface; type Expander_Access is access all Expander'Class; -- Expand the name from the given group into a target parameter value to be used in -- the SQL query. The expander can look in a cache or in some configuration to find -- the value associated with the name and return it. The Expander can return a -- T_NULL when a value is not found or it may also raise some exception. function Expand (Instance : in Expander; Group : in String; Name : in String) return Parameter is abstract; type Abstract_List is abstract new Ada.Finalization.Controlled with private; type Abstract_List_Access is access all Abstract_List'Class; -- Set the SQL dialect description object. procedure Set_Dialect (Params : in out Abstract_List; D : in ADO.Drivers.Dialects.Dialect_Access); -- Set the cache expander to be used when expanding the SQL. procedure Set_Expander (Params : in out Abstract_List; Expander : in ADO.Parameters.Expander_Access); -- Get the SQL dialect description object. function Get_Dialect (From : in Abstract_List) return ADO.Drivers.Dialects.Dialect_Access; -- Add the parameter in the list. procedure Add_Parameter (Params : in out Abstract_List; Param : in Parameter) is abstract; -- Set the parameters from another parameter list. procedure Set_Parameters (Parameters : in out Abstract_List; From : in Abstract_List'Class) is abstract; -- Return the number of parameters in the list. function Length (Params : in Abstract_List) return Natural is abstract; -- Return the parameter at the given position function Element (Params : in Abstract_List; Position : in Natural) return Parameter is abstract; -- Execute the <b>Process</b> procedure with the given parameter as argument. procedure Query_Element (Params : in Abstract_List; Position : in Natural; Process : not null access procedure (Element : in Parameter)) is abstract; -- Clear the list of parameters. procedure Clear (Parameters : in out Abstract_List) is abstract; -- Operations to bind a parameter procedure Bind_Param (Params : in out Abstract_List; Name : in String; Value : in Boolean); procedure Bind_Param (Params : in out Abstract_List; Name : in String; Value : in Long_Long_Integer); procedure Bind_Param (Params : in out Abstract_List; Name : in String; Value : in Identifier); procedure Bind_Param (Params : in out Abstract_List; Name : in String; Value : in Integer); procedure Bind_Param (Params : in out Abstract_List; Name : in String; Value : in ADO.Entity_Type); procedure Bind_Param (Params : in out Abstract_List; Name : in String; Value : in String); procedure Bind_Param (Params : in out Abstract_List; Name : in String; Value : in Unbounded_String); procedure Bind_Param (Params : in out Abstract_List; Name : in String; Value : in Ada.Calendar.Time); procedure Bind_Param (Params : in out Abstract_List; Name : in String; Value : in Token); procedure Bind_Param (Params : in out Abstract_List; Name : in String; Value : in ADO.Blob_Ref); procedure Bind_Param (Params : in out Abstract_List; Name : in String; Value : in ADO.Utils.Identifier_Vector); procedure Bind_Param (Params : in out Abstract_List; Position : in Natural; Value : in Boolean); procedure Bind_Param (Params : in out Abstract_List; Position : in Natural; Value : in Long_Long_Integer); procedure Bind_Param (Params : in out Abstract_List; Position : in Natural; Value : in Identifier); procedure Bind_Param (Params : in out Abstract_List; Position : in Natural; Value : in Integer); procedure Bind_Param (Params : in out Abstract_List; Position : in Natural; Value : in Entity_Type); procedure Bind_Param (Params : in out Abstract_List; Position : in Natural; Value : in String); procedure Bind_Param (Params : in out Abstract_List; Position : in Natural; Value : in Unbounded_String); procedure Bind_Param (Params : in out Abstract_List; Position : in Natural; Value : in Ada.Calendar.Time); procedure Bind_Param (Params : in out Abstract_List; Position : in Natural; Value : in ADO.Blob_Ref); procedure Bind_Null_Param (Params : in out Abstract_List; Position : in Natural); procedure Bind_Null_Param (Params : in out Abstract_List; Name : in String); procedure Add_Param (Params : in out Abstract_List; Value : in Boolean); procedure Add_Param (Params : in out Abstract_List; Value : in Long_Long_Integer); procedure Add_Param (Params : in out Abstract_List; Value : in Identifier); procedure Add_Param (Params : in out Abstract_List; Value : in Integer); procedure Add_Param (Params : in out Abstract_List; Value : in String); procedure Add_Param (Params : in out Abstract_List; Value : in Unbounded_String); procedure Add_Param (Params : in out Abstract_List; Value : in Ada.Calendar.Time); -- Add a null parameter. procedure Add_Null_Param (Params : in out Abstract_List); -- Expand the SQL string with the query parameters. The following parameters syntax -- are recognized and replaced: -- <ul> -- <li>? is replaced according to the current parameter index. The index is incremented -- after each occurrence of ? character. -- <li>:nnn is replaced by the parameter at index <b>nnn</b>. -- <li>:name is replaced by the parameter with the name <b>name</b> -- <li>$group[var-name] is replaced by using the expander interface. -- </ul> -- Parameter strings are escaped. When a parameter is not found, an empty string is used. -- Returns the expanded SQL string. function Expand (Params : in Abstract_List'Class; SQL : in String) return String; -- ------------------------------ -- List of parameters -- ------------------------------ -- The <b>List</b> is an implementation of the parameter list. type List is new Abstract_List with private; procedure Add_Parameter (Params : in out List; Param : in Parameter); procedure Set_Parameters (Params : in out List; From : in Abstract_List'Class); -- Return the number of parameters in the list. function Length (Params : in List) return Natural; -- Return the parameter at the given position function Element (Params : in List; Position : in Natural) return Parameter; -- Execute the <b>Process</b> procedure with the given parameter as argument. procedure Query_Element (Params : in List; Position : in Natural; Process : not null access procedure (Element : in Parameter)); -- Clear the list of parameters. procedure Clear (Params : in out List); private function Compare_On_Name (Left, Right : in Parameter) return Boolean; package Parameter_Vectors is new Ada.Containers.Indefinite_Vectors (Index_Type => Positive, Element_Type => Parameter, "=" => Compare_On_Name); type Abstract_List is abstract new Ada.Finalization.Controlled with record Dialect : ADO.Drivers.Dialects.Dialect_Access := null; Expander : Expander_Access; end record; type List is new Abstract_List with record Params : Parameter_Vectors.Vector; end record; end ADO.Parameters;
----------------------------------------------------------------------- -- ADO Parameters -- Parameters for queries -- 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 Ada.Strings.Unbounded; with Ada.Finalization; with Ada.Calendar; with Ada.Containers.Indefinite_Vectors; with ADO.Utils; with ADO.Drivers.Dialects; -- == Query Parameters == -- Query parameters are represented by the <tt>Parameter</tt> type which can represent almost -- all database types including boolean, numbers, strings, dates and blob. Parameters are -- put in a list represented by the <tt>Abstract_List</tt> or <tt>List</tt> types. -- -- A parameter is added by using either the <tt>Bind_Param</tt> or the <tt>Add_Param</tt> -- operation. The <tt>Bind_Param</tt> operation allows to specify either the parameter name -- or its position. The <tt>Add_Param</tt> operation adds the parameter at end of the list -- and uses the last position. In most cases, it is easier to bind a parameter with a name -- as follows: -- -- Query.Bind_Param ("name", "Joe"); -- -- and the SQL can use the following construct: -- -- SELECT * FROM user WHERE name = :name -- -- When the <tt>Add_Param</tt> is used, the parameter is not associated with any name but it -- as a position index. Setting a parameter is easier: -- -- Query.Add_Param ("Joe"); -- -- but the SQL cannot make any reference to names and must use the <tt>?</tt> construct: -- -- SELECT * FROM user WHERE name = ? -- -- === Parameter Expander === -- The parameter expander is a mechanism that allows to replace or inject values in the SQL -- query by looking at an operation provided by the <tt>Expander</tt> interface. Such expander -- is useful to replace parameters that are global to a session or to an application. -- package ADO.Parameters is use Ada.Strings.Unbounded; type Token is new String; type Parameter_Type is (T_NULL, T_STRING, T_TOKEN, T_LIST, T_DATE, T_LONG_INTEGER, T_INTEGER, T_BOOLEAN, T_BLOB); type Parameter (T : Parameter_Type; Len : Natural; Value_Len : Natural) is record Position : Natural := 0; Name : String (1 .. Len); case T is when T_NULL => null; when T_LONG_INTEGER => Long_Num : Long_Long_Integer := 0; when T_INTEGER => Num : Integer; when T_BOOLEAN => Bool : Boolean; when T_DATE => Time : Ada.Calendar.Time; when T_BLOB => Data : ADO.Blob_Ref; when others => Str : String (1 .. Value_Len); end case; end record; type Expander is limited interface; type Expander_Access is access all Expander'Class; -- Expand the name from the given group into a target parameter value to be used in -- the SQL query. The expander can look in a cache or in some configuration to find -- the value associated with the name and return it. The Expander can return a -- T_NULL when a value is not found or it may also raise some exception. function Expand (Instance : in Expander; Group : in String; Name : in String) return Parameter is abstract; type Abstract_List is abstract new Ada.Finalization.Controlled with private; type Abstract_List_Access is access all Abstract_List'Class; -- Set the SQL dialect description object. procedure Set_Dialect (Params : in out Abstract_List; D : in ADO.Drivers.Dialects.Dialect_Access); -- Set the cache expander to be used when expanding the SQL. procedure Set_Expander (Params : in out Abstract_List; Expander : in ADO.Parameters.Expander_Access); -- Get the SQL dialect description object. function Get_Dialect (From : in Abstract_List) return ADO.Drivers.Dialects.Dialect_Access; -- Add the parameter in the list. procedure Add_Parameter (Params : in out Abstract_List; Param : in Parameter) is abstract; -- Set the parameters from another parameter list. procedure Set_Parameters (Parameters : in out Abstract_List; From : in Abstract_List'Class) is abstract; -- Return the number of parameters in the list. function Length (Params : in Abstract_List) return Natural is abstract; -- Return the parameter at the given position function Element (Params : in Abstract_List; Position : in Natural) return Parameter is abstract; -- Execute the <b>Process</b> procedure with the given parameter as argument. procedure Query_Element (Params : in Abstract_List; Position : in Natural; Process : not null access procedure (Element : in Parameter)) is abstract; -- Clear the list of parameters. procedure Clear (Parameters : in out Abstract_List) is abstract; -- Operations to bind a parameter procedure Bind_Param (Params : in out Abstract_List; Name : in String; Value : in Boolean); procedure Bind_Param (Params : in out Abstract_List; Name : in String; Value : in Long_Long_Integer); procedure Bind_Param (Params : in out Abstract_List; Name : in String; Value : in Identifier); procedure Bind_Param (Params : in out Abstract_List; Name : in String; Value : in Integer); procedure Bind_Param (Params : in out Abstract_List; Name : in String; Value : in ADO.Entity_Type); procedure Bind_Param (Params : in out Abstract_List; Name : in String; Value : in String); procedure Bind_Param (Params : in out Abstract_List; Name : in String; Value : in Unbounded_String); procedure Bind_Param (Params : in out Abstract_List; Name : in String; Value : in Ada.Calendar.Time); procedure Bind_Param (Params : in out Abstract_List; Name : in String; Value : in Token); procedure Bind_Param (Params : in out Abstract_List; Name : in String; Value : in ADO.Blob_Ref); procedure Bind_Param (Params : in out Abstract_List; Name : in String; Value : in ADO.Utils.Identifier_Vector); procedure Bind_Param (Params : in out Abstract_List; Position : in Natural; Value : in Boolean); procedure Bind_Param (Params : in out Abstract_List; Position : in Natural; Value : in Long_Long_Integer); procedure Bind_Param (Params : in out Abstract_List; Position : in Natural; Value : in Identifier); procedure Bind_Param (Params : in out Abstract_List; Position : in Natural; Value : in Integer); procedure Bind_Param (Params : in out Abstract_List; Position : in Natural; Value : in Entity_Type); procedure Bind_Param (Params : in out Abstract_List; Position : in Natural; Value : in String); procedure Bind_Param (Params : in out Abstract_List; Position : in Natural; Value : in Unbounded_String); procedure Bind_Param (Params : in out Abstract_List; Position : in Natural; Value : in Ada.Calendar.Time); procedure Bind_Param (Params : in out Abstract_List; Position : in Natural; Value : in ADO.Blob_Ref); procedure Bind_Null_Param (Params : in out Abstract_List; Position : in Natural); procedure Bind_Null_Param (Params : in out Abstract_List; Name : in String); procedure Add_Param (Params : in out Abstract_List; Value : in Boolean); procedure Add_Param (Params : in out Abstract_List; Value : in Long_Long_Integer); procedure Add_Param (Params : in out Abstract_List; Value : in Identifier); procedure Add_Param (Params : in out Abstract_List; Value : in Integer); procedure Add_Param (Params : in out Abstract_List; Value : in String); procedure Add_Param (Params : in out Abstract_List; Value : in Unbounded_String); procedure Add_Param (Params : in out Abstract_List; Value : in Ada.Calendar.Time); -- Add a null parameter. procedure Add_Null_Param (Params : in out Abstract_List); -- Expand the SQL string with the query parameters. The following parameters syntax -- are recognized and replaced: -- <ul> -- <li>? is replaced according to the current parameter index. The index is incremented -- after each occurrence of ? character. -- <li>:nnn is replaced by the parameter at index <b>nnn</b>. -- <li>:name is replaced by the parameter with the name <b>name</b> -- <li>$group[var-name] is replaced by using the expander interface. -- </ul> -- Parameter strings are escaped. When a parameter is not found, an empty string is used. -- Returns the expanded SQL string. function Expand (Params : in Abstract_List'Class; SQL : in String) return String; -- ------------------------------ -- List of parameters -- ------------------------------ -- The <b>List</b> is an implementation of the parameter list. type List is new Abstract_List with private; procedure Add_Parameter (Params : in out List; Param : in Parameter); procedure Set_Parameters (Params : in out List; From : in Abstract_List'Class); -- Return the number of parameters in the list. function Length (Params : in List) return Natural; -- Return the parameter at the given position function Element (Params : in List; Position : in Natural) return Parameter; -- Execute the <b>Process</b> procedure with the given parameter as argument. procedure Query_Element (Params : in List; Position : in Natural; Process : not null access procedure (Element : in Parameter)); -- Clear the list of parameters. procedure Clear (Params : in out List); private function Compare_On_Name (Left, Right : in Parameter) return Boolean; package Parameter_Vectors is new Ada.Containers.Indefinite_Vectors (Index_Type => Positive, Element_Type => Parameter, "=" => Compare_On_Name); type Abstract_List is abstract new Ada.Finalization.Controlled with record Dialect : ADO.Drivers.Dialects.Dialect_Access := null; Expander : Expander_Access; end record; type List is new Abstract_List with record Params : Parameter_Vectors.Vector; end record; end ADO.Parameters;
Add some documentation
Add some documentation
Ada
apache-2.0
stcarrez/ada-ado
050fcb9fb65aea3fdb9c8f47246152116108b2e6
regtests/util-dates-formats-tests.ads
regtests/util-dates-formats-tests.ads
----------------------------------------------------------------------- -- util-dates-formats-tests - Test for date formats -- Copyright (C) 2011, 2013, 2014, 2015, 2016, 2018, 2020 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Tests; package Util.Dates.Formats.Tests is procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite); type Test is new Util.Tests.Test with null record; procedure Test_Format (T : in out Test); -- Test parsing a date using several formats and different locales. procedure Test_Parse (T : in out Test); -- Test parsing a date using several formats and having several errors. procedure Test_Parse_Error (T : in out Test); -- Test the Get_Day_Start operation. procedure Test_Get_Day_Start (T : in out Test); -- Test the Get_Week_Start operation. procedure Test_Get_Week_Start (T : in out Test); -- Test the Get_Month_Start operation. procedure Test_Get_Month_Start (T : in out Test); -- Test the Get_Day_End operation. procedure Test_Get_Day_End (T : in out Test); -- Test the Get_Week_End operation. procedure Test_Get_Week_End (T : in out Test); -- Test the Get_Month_End operation. procedure Test_Get_Month_End (T : in out Test); -- Test the Split operation. procedure Test_Split (T : in out Test); -- Test the Append_Date operation procedure Test_Append_Date (T : in out Test); -- Test the ISO8601 operations. procedure Test_ISO8601 (T : in out Test); end Util.Dates.Formats.Tests;
----------------------------------------------------------------------- -- util-dates-formats-tests - Test for date formats -- Copyright (C) 2011, 2013, 2014, 2015, 2016, 2018, 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 Util.Tests; package Util.Dates.Formats.Tests is procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite); type Test is new Util.Tests.Test with null record; procedure Test_Format (T : in out Test); -- Test parsing a date using several formats and different locales. procedure Test_Parse (T : in out Test); -- Test parsing a date using several formats and having several errors. procedure Test_Parse_Error (T : in out Test); -- Test the Get_Day_Start operation. procedure Test_Get_Day_Start (T : in out Test); -- Test the Get_Week_Start operation. procedure Test_Get_Week_Start (T : in out Test); -- Test the Get_Month_Start operation. procedure Test_Get_Month_Start (T : in out Test); -- Test the Get_Day_End operation. procedure Test_Get_Day_End (T : in out Test); -- Test the Get_Week_End operation. procedure Test_Get_Week_End (T : in out Test); -- Test the Get_Month_End operation. procedure Test_Get_Month_End (T : in out Test); -- Test the Split operation. procedure Test_Split (T : in out Test); -- Test the Append_Date operation procedure Test_Append_Date (T : in out Test); -- Test the ISO8601 operations. procedure Test_ISO8601 (T : in out Test); -- Test the Simple_Format option. procedure Test_Simple_Format (T : in out Test); end Util.Dates.Formats.Tests;
Declare Test_Simple_Format procedure
Declare Test_Simple_Format procedure
Ada
apache-2.0
stcarrez/ada-util,stcarrez/ada-util
aa4b6c09105203965ec5665cc5c8a7e7667f35fc
regtests/asf-navigations-tests.ads
regtests/asf-navigations-tests.ads
----------------------------------------------------------------------- -- asf-navigations-tests - Tests for ASF navigation -- Copyright (C) 2013 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Tests; package ASF.Navigations.Tests is procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite); type Test is new Util.Tests.Test with null record; -- Initialize the test application overriding procedure Set_Up (T : in out Test); -- Test a form navigation with an exact match (view, outcome, action). procedure Test_Exact_Navigation (T : in out Test); -- Test a form navigation with a partial match (view, outcome). procedure Test_Partial_Navigation (T : in out Test); -- Test a form navigation with a exception match (view, outcome). procedure Test_Exception_Navigation (T : in out Test); -- Test a form navigation with a wildcard match on the URI (view, outcome). procedure Test_Wildcard_Navigation (T : in out Test); -- Test a form navigation with a condition (view, outcome, condition). procedure Test_Conditional_Navigation (T : in out Test); -- Check the navigation for an URI and expect the result to match the regular expression. procedure Check_Navigation (T : in out Test; Name : in String; Match : in String; Raise_Flag : in Boolean := False); end ASF.Navigations.Tests;
----------------------------------------------------------------------- -- asf-navigations-tests - Tests for ASF navigation -- 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 Util.Tests; package ASF.Navigations.Tests is procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite); type Test is new Util.Tests.Test with null record; -- Initialize the test application overriding procedure Set_Up (T : in out Test); -- Test a form navigation with an exact match (view, outcome, action). procedure Test_Exact_Navigation (T : in out Test); -- Test a form navigation with a partial match (view, outcome). procedure Test_Partial_Navigation (T : in out Test); -- Test a form navigation with a exception match (view, outcome). procedure Test_Exception_Navigation (T : in out Test); -- Test a form navigation with a wildcard match on the URI (view, outcome). procedure Test_Wildcard_Navigation (T : in out Test); -- Test a form navigation with a condition (view, outcome, condition). procedure Test_Conditional_Navigation (T : in out Test); -- Test a navigation rule with a status. procedure Test_Status_Navigation (T : in out Test); -- Check the navigation for an URI and expect the result to match the regular expression. procedure Check_Navigation (T : in out Test; Name : in String; Match : in String; Raise_Flag : in Boolean := False; Status : in Natural := 200); end ASF.Navigations.Tests;
Declare the Test_Status_Navigation procedure
Declare the Test_Status_Navigation procedure
Ada
apache-2.0
stcarrez/ada-asf,stcarrez/ada-asf,stcarrez/ada-asf
120a2f05722d807f09eaf9c5e3c84ff02ed86a77
regtests/util-properties-tests.adb
regtests/util-properties-tests.adb
----------------------------------------------------------------------- -- Util -- Unit tests for properties -- Copyright (C) 2009, 2010, 2011, 2014, 2017, 2018, 2020, 2021 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Test_Caller; with Ada.Text_IO; with Util.Properties; with Util.Properties.Basic; package body Util.Properties.Tests is use Ada.Text_IO; use type Ada.Containers.Count_Type; use Util.Properties.Basic; -- Test -- Properties.Set -- Properties.Exists -- Properties.Get procedure Test_Property (T : in out Test) is Props : Properties.Manager; begin T.Assert (Exists (Props, "test") = False, "Invalid properties"); T.Assert (Exists (Props, +("test")) = False, "Invalid properties"); T.Assert (Props.Is_Empty, "Property manager should be empty"); Props.Set ("test", "toto"); T.Assert (Exists (Props, "test"), "Property was not inserted"); declare V : constant String := Props.Get ("test"); begin T.Assert (V = "toto", "Property was not set correctly"); end; declare V : constant String := Props.Get (+("test")); begin T.Assert (V = "toto", "Property was not set correctly"); end; declare V : constant Unbounded_String := Props.Get (+("test")); begin T.Assert (V = "toto", "Property was not set correctly"); end; end Test_Property; -- Test basic properties -- Get -- Set procedure Test_Integer_Property (T : in out Test) is Props : Properties.Manager; V : Integer := 23; begin Integer_Property.Set (Props, "test-integer", V); T.Assert (Props.Exists ("test-integer"), "Invalid properties"); V := Integer_Property.Get (Props, "test-integer"); T.Assert (V = 23, "Property was not inserted"); Integer_Property.Set (Props, "test-integer", 24); V := Integer_Property.Get (Props, "test-integer"); T.Assert (V = 24, "Property was not inserted"); V := Integer_Property.Get (Props, "unknown", 25); T.Assert (V = 25, "Default value must be returned for a Get"); end Test_Integer_Property; -- Test loading of property files procedure Test_Load_Property (T : in out Test) is Props : Properties.Manager; F : File_Type; begin Open (F, In_File, "regtests/test.properties"); Load_Properties (Props, F); Close (F); declare Names : Util.Strings.Vectors.Vector; begin Props.Get_Names (Names); T.Assert (Names.Length > 30, "Loading the test properties returned too few properties"); T.Assert (To_String (Props.Get ("root.dir")) = ".", "Invalid property 'root.dir'"); T.Assert (To_String (Props.Get ("console.lib")) = "${dist.lib.dir}/console.jar", "Invalid property 'console.lib'"); end; exception when Ada.Text_IO.Name_Error => Ada.Text_IO.Put_Line ("Cannot find test file: regtests/test.properties"); raise; end Test_Load_Property; -- ------------------------------ -- Test loading of property files -- ------------------------------ procedure Test_Load_Strip_Property (T : in out Test) is Props : Properties.Manager; F : File_Type; begin -- Load, filter and strip properties Open (F, In_File, "regtests/test.properties"); Load_Properties (Props, F, "tomcat.", True); Close (F); declare Names : Util.Strings.Vectors.Vector; begin Props.Get_Names (Names); T.Assert (Names.Length > 3, "Loading the test properties returned too few properties"); T.Assert (To_String (Props.Get ("version")) = "0.6", "Invalid property 'root.dir'"); end; exception when Ada.Text_IO.Name_Error => Ada.Text_IO.Put_Line ("Cannot find test file: regtests/test.properties"); raise; end Test_Load_Strip_Property; -- ------------------------------ -- Test copy of properties -- ------------------------------ procedure Test_Copy_Property (T : in out Test) is Props : Properties.Manager; begin Props.Set ("prefix.one", "1"); Props.Set ("prefix.two", "2"); Props.Set ("prefix", "Not copied"); Props.Set ("prefix.", "Copied"); declare Copy : Properties.Manager; begin Copy.Copy (From => Props, Prefix => "prefix.", Strip => True); T.Assert (Copy.Exists ("one"), "Property one not found"); T.Assert (Copy.Exists ("two"), "Property two not found"); T.Assert (Copy.Exists (""), "Property '' does not exist."); end; end Test_Copy_Property; procedure Test_Set_Preserve_Original (T : in out Test) is Props1 : Properties.Manager; begin Props1.Set ("a", "b"); Props1.Set ("c", "d"); declare Props2 : Properties.Manager; begin Props2 := Props1; T.Assert (Props2.Exists ("a"), "Property a not found in props2 after assignment"); T.Assert (Props2.Exists ("c"), "Property b not found in props2 after assignment"); Util.Tests.Assert_Equals (T, "b", String '(Props2.Get ("a")), "Invalid property a"); Props1.Set ("a", "d"); Util.Tests.Assert_Equals (T, "d", String '(Props1.Get ("a")), "Wrong property a in props1"); Util.Tests.Assert_Equals (T, "b", String '(Props2.Get ("a")), "Wrong property a in props2"); Props2 := Props1; Util.Tests.Assert_Equals (T, "d", String '(Props2.Get ("a")), "Wrong property a in props2"); Props2.Set ("e", "f"); Props2.Set ("c", "g"); Props1 := Props2; -- Release Props2 but the property manager is internally shared so the Props1 is -- not changed. end; T.Assert (Props1.Exists ("e"), "Property e not found in props1 after assignment"); T.Assert (Props1.Exists ("c"), "Property c not found in props1 after assignment"); Util.Tests.Assert_Equals (T, "g", String '(Props1.Get ("c")), "Wrong property c in props1"); end Test_Set_Preserve_Original; procedure Test_Remove_Preserve_Original (T : in out Test) is Props1 : Properties.Manager; begin Props1.Set ("a", "b"); Props1.Set ("c", "d"); declare Props2 : Properties.Manager; begin Props2 := Props1; T.Assert (Props2.Exists ("a"), "Property a not found in props2 after assignment"); T.Assert (Props2.Exists ("c"), "Property b not found in props2 after assignment"); Props1.Remove ("a"); T.Assert (not Props1.Exists ("a"), "Property a was not removed from props1"); T.Assert (Props2.Exists ("a"), "Property a was removed from props2"); Props1 := Props2; -- Release Props2 but the property manager is internally shared so the Props1 is -- not changed. end; Util.Tests.Assert_Equals (T, "b", String '(Props1.Get ("a")), "Wrong property a in props1"); end Test_Remove_Preserve_Original; procedure Test_Missing_Property (T : in out Test) is Props : Properties.Manager; V : Unbounded_String; begin T.Assert (Util.Beans.Objects.Is_Null (Props.Get_Value ("missing")), "The Get_Value operation must return a null object"); begin V := Props.Get ("missing"); T.Fail ("Exception NO_PROPERTY was not raised"); exception when NO_PROPERTY => null; end; begin V := Props.Get (+("missing")); T.Fail ("Exception NO_PROPERTY was not raised"); exception when NO_PROPERTY => null; end; T.Assert (Ada.Strings.Unbounded.Length (V) = 0, "Variable get's corrupted"); -- Check exception on Get returning a String. begin declare S : constant String := Props.Get ("missing"); pragma Unreferenced (S); begin T.Fail ("Exception NO_PROPERTY was not raised"); end; exception when NO_PROPERTY => null; end; -- Check exception on Get returning a String. begin declare S : constant String := Props.Get (+("missing")); pragma Unreferenced (S); begin T.Fail ("Exception NO_PROPERTY was not raised"); end; exception when NO_PROPERTY => null; end; Props.Set ("a", "b"); T.Assert (Util.Beans.Objects.Is_Null (Props.Get_Value ("missing")), "The Get_Value operation must return a null object"); begin V := Props.Get ("missing"); T.Fail ("Exception NO_PROPERTY was not raised"); exception when NO_PROPERTY => null; end; end Test_Missing_Property; procedure Test_Load_Ini_Property (T : in out Test) is Props : Properties.Manager; F : File_Type; begin Open (F, In_File, "regtests/files/my.cnf"); Load_Properties (Props, F); Close (F); declare V : Util.Properties.Value; P : Properties.Manager; begin V := Props.Get_Value ("mysqld"); T.Assert (Util.Properties.Is_Manager (V), "Value 'mysqld' must be a property manager"); P := Util.Properties.To_Manager (V); T.Assert (P.Exists ("user"), "The [mysqld] property manager should contain a 'user' property"); V := Props.Get_Value ("mysqld_safe"); T.Assert (Util.Properties.Is_Manager (V), "Value 'mysqld_safe' must be a property manager"); P := Util.Properties.To_Manager (V); T.Assert (P.Exists ("socket"), "The [mysqld] property manager should contain a 'socket' property"); end; declare P : Properties.Manager; begin P := Props.Get ("mysqld"); T.Assert (P.Exists ("user"), "The [mysqld] property manager should contain a 'user' property"); P := Props.Get ("mysqld_safe"); T.Assert (P.Exists ("socket"), "The [mysqld] property manager should contain a 'socket' property"); end; declare P : Properties.Manager with Unreferenced; begin P := Props.Get ("bad"); T.Fail ("No exception raised for Get()"); exception when NO_PROPERTY => null; end; exception when Ada.Text_IO.Name_Error => Ada.Text_IO.Put_Line ("Cannot find test file: regtests/files/my.cnf"); raise; end Test_Load_Ini_Property; procedure Test_Save_Properties (T : in out Test) is Path : constant String := Util.Tests.Get_Test_Path ("save-props.properties"); begin declare Props : Properties.Manager; F : File_Type; begin Open (F, In_File, "regtests/files/my.cnf"); Load_Properties (Props, F); Close (F); Props.Set ("New-Property", "Some-Value"); Props.Remove ("mysqld"); T.Assert (not Props.Exists ("mysqld"), "mysqld property was not removed"); Props.Save_Properties (Path); end; declare Props : Properties.Manager; V : Util.Properties.Value; P : Properties.Manager; begin Props.Load_Properties (Path => Path); T.Assert (not Props.Exists ("mysqld"), "mysqld property was not removed (2)"); T.Assert (Props.Exists ("New-Property"), "Invalid Save_Properties"); V := Props.Get_Value ("mysqld_safe"); T.Assert (Util.Properties.Is_Manager (V), "Value 'mysqld_safe' must be a property manager"); P := Util.Properties.To_Manager (V); T.Assert (P.Exists ("socket"), "The [mysqld] property manager should contain a 'socket' property"); end; end Test_Save_Properties; package Caller is new Util.Test_Caller (Test, "Properties"); procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is begin Caller.Add_Test (Suite, "Test Util.Properties.Set", Test_Property'Access); Caller.Add_Test (Suite, "Test Util.Properties.Get", Test_Property'Access); Caller.Add_Test (Suite, "Test Util.Properties.Exists", Test_Property'Access); Caller.Add_Test (Suite, "Test Util.Properties.Get (NO_PROPERTY)", Test_Missing_Property'Access); Caller.Add_Test (Suite, "Test Util.Properties.Discrete.Get", Test_Integer_Property'Access); Caller.Add_Test (Suite, "Test Util.Properties.Discrete.Set", Test_Integer_Property'Access); Caller.Add_Test (Suite, "Test Util.Properties.Load_Properties", Test_Load_Property'Access); Caller.Add_Test (Suite, "Test Util.Properties.Load_Properties (INI)", Test_Load_Ini_Property'Access); Caller.Add_Test (Suite, "Test Util.Properties.Load_Strip_Properties", Test_Load_Strip_Property'Access); Caller.Add_Test (Suite, "Test Util.Properties.Copy", Test_Copy_Property'Access); Caller.Add_Test (Suite, "Test Util.Properties.Set+Assign", Test_Set_Preserve_Original'Access); Caller.Add_Test (Suite, "Test Util.Properties.Set+Assign+Remove", Test_Remove_Preserve_Original'Access); Caller.Add_Test (Suite, "Test Util.Properties.Save_Properties", Test_Save_Properties'Access); end Add_Tests; end Util.Properties.Tests;
----------------------------------------------------------------------- -- util-properties-tests -- Tests for properties -- Copyright (C) 2009, 2010, 2011, 2014, 2017, 2018, 2020, 2021 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Test_Caller; with Ada.Text_IO; with Util.Properties; with Util.Properties.Basic; package body Util.Properties.Tests is use Ada.Text_IO; use type Ada.Containers.Count_Type; use Util.Properties.Basic; -- Test -- Properties.Set -- Properties.Exists -- Properties.Get procedure Test_Property (T : in out Test) is Props : Properties.Manager; begin T.Assert (Exists (Props, "test") = False, "Invalid properties"); T.Assert (Exists (Props, +("test")) = False, "Invalid properties"); T.Assert (Props.Is_Empty, "Property manager should be empty"); Props.Set ("test", "toto"); T.Assert (Exists (Props, "test"), "Property was not inserted"); declare V : constant String := Props.Get ("test"); begin T.Assert (V = "toto", "Property was not set correctly"); end; declare V : constant String := Props.Get (+("test")); begin T.Assert (V = "toto", "Property was not set correctly"); end; declare V : constant Unbounded_String := Props.Get (+("test")); begin T.Assert (V = "toto", "Property was not set correctly"); end; end Test_Property; -- Test basic properties -- Get -- Set procedure Test_Integer_Property (T : in out Test) is Props : Properties.Manager; V : Integer := 23; begin Integer_Property.Set (Props, "test-integer", V); T.Assert (Props.Exists ("test-integer"), "Invalid properties"); V := Integer_Property.Get (Props, "test-integer"); T.Assert (V = 23, "Property was not inserted"); Integer_Property.Set (Props, "test-integer", 24); V := Integer_Property.Get (Props, "test-integer"); T.Assert (V = 24, "Property was not inserted"); V := Integer_Property.Get (Props, "unknown", 25); T.Assert (V = 25, "Default value must be returned for a Get"); end Test_Integer_Property; -- Test loading of property files procedure Test_Load_Property (T : in out Test) is Props : Properties.Manager; F : File_Type; begin Open (F, In_File, "regtests/test.properties"); Load_Properties (Props, F); Close (F); declare Names : Util.Strings.Vectors.Vector; begin Props.Get_Names (Names); T.Assert (Names.Length > 30, "Loading the test properties returned too few properties"); T.Assert (To_String (Props.Get ("root.dir")) = ".", "Invalid property 'root.dir'"); T.Assert (To_String (Props.Get ("console.lib")) = "${dist.lib.dir}/console.jar", "Invalid property 'console.lib'"); end; exception when Ada.Text_IO.Name_Error => Ada.Text_IO.Put_Line ("Cannot find test file: regtests/test.properties"); raise; end Test_Load_Property; -- ------------------------------ -- Test loading of property files -- ------------------------------ procedure Test_Load_Strip_Property (T : in out Test) is Props : Properties.Manager; F : File_Type; begin -- Load, filter and strip properties Open (F, In_File, "regtests/test.properties"); Load_Properties (Props, F, "tomcat.", True); Close (F); declare Names : Util.Strings.Vectors.Vector; begin Props.Get_Names (Names); T.Assert (Names.Length > 3, "Loading the test properties returned too few properties"); T.Assert (To_String (Props.Get ("version")) = "0.6", "Invalid property 'root.dir'"); end; exception when Ada.Text_IO.Name_Error => Ada.Text_IO.Put_Line ("Cannot find test file: regtests/test.properties"); raise; end Test_Load_Strip_Property; -- ------------------------------ -- Test copy of properties -- ------------------------------ procedure Test_Copy_Property (T : in out Test) is Props : Properties.Manager; begin Props.Set ("prefix.one", "1"); Props.Set ("prefix.two", "2"); Props.Set ("prefix", "Not copied"); Props.Set ("prefix.", "Copied"); declare Copy : Properties.Manager; begin Copy.Copy (From => Props, Prefix => "prefix.", Strip => True); T.Assert (Copy.Exists ("one"), "Property one not found"); T.Assert (Copy.Exists ("two"), "Property two not found"); T.Assert (Copy.Exists (""), "Property '' does not exist."); end; end Test_Copy_Property; procedure Test_Set_Preserve_Original (T : in out Test) is Props1 : Properties.Manager; begin Props1.Set ("a", "b"); Props1.Set ("c", "d"); declare Props2 : Properties.Manager; begin Props2 := Props1; T.Assert (Props2.Exists ("a"), "Property a not found in props2 after assignment"); T.Assert (Props2.Exists ("c"), "Property b not found in props2 after assignment"); Util.Tests.Assert_Equals (T, "b", String '(Props2.Get ("a")), "Invalid property a"); Props1.Set ("a", "d"); Util.Tests.Assert_Equals (T, "d", String '(Props1.Get ("a")), "Wrong property a in props1"); Util.Tests.Assert_Equals (T, "b", String '(Props2.Get ("a")), "Wrong property a in props2"); Props2 := Props1; Util.Tests.Assert_Equals (T, "d", String '(Props2.Get ("a")), "Wrong property a in props2"); Props2.Set ("e", "f"); Props2.Set ("c", "g"); Props1 := Props2; -- Release Props2 but the property manager is internally shared so the Props1 is -- not changed. end; T.Assert (Props1.Exists ("e"), "Property e not found in props1 after assignment"); T.Assert (Props1.Exists ("c"), "Property c not found in props1 after assignment"); Util.Tests.Assert_Equals (T, "g", String '(Props1.Get ("c")), "Wrong property c in props1"); end Test_Set_Preserve_Original; procedure Test_Remove_Preserve_Original (T : in out Test) is Props1 : Properties.Manager; begin Props1.Set ("a", "b"); Props1.Set ("c", "d"); declare Props2 : Properties.Manager; begin Props2 := Props1; T.Assert (Props2.Exists ("a"), "Property a not found in props2 after assignment"); T.Assert (Props2.Exists ("c"), "Property b not found in props2 after assignment"); Props1.Remove ("a"); T.Assert (not Props1.Exists ("a"), "Property a was not removed from props1"); T.Assert (Props2.Exists ("a"), "Property a was removed from props2"); Props1 := Props2; -- Release Props2 but the property manager is internally shared so the Props1 is -- not changed. end; Util.Tests.Assert_Equals (T, "b", String '(Props1.Get ("a")), "Wrong property a in props1"); end Test_Remove_Preserve_Original; procedure Test_Missing_Property (T : in out Test) is Props : Properties.Manager; V : Unbounded_String; begin T.Assert (Util.Beans.Objects.Is_Null (Props.Get_Value ("missing")), "The Get_Value operation must return a null object"); begin V := Props.Get ("missing"); T.Fail ("Exception NO_PROPERTY was not raised"); exception when NO_PROPERTY => null; end; begin V := Props.Get (+("missing")); T.Fail ("Exception NO_PROPERTY was not raised"); exception when NO_PROPERTY => null; end; T.Assert (Ada.Strings.Unbounded.Length (V) = 0, "Variable get's corrupted"); -- Check exception on Get returning a String. begin declare S : constant String := Props.Get ("missing"); pragma Unreferenced (S); begin T.Fail ("Exception NO_PROPERTY was not raised"); end; exception when NO_PROPERTY => null; end; -- Check exception on Get returning a String. begin declare S : constant String := Props.Get (+("missing")); pragma Unreferenced (S); begin T.Fail ("Exception NO_PROPERTY was not raised"); end; exception when NO_PROPERTY => null; end; Props.Set ("a", "b"); T.Assert (Util.Beans.Objects.Is_Null (Props.Get_Value ("missing")), "The Get_Value operation must return a null object"); begin V := Props.Get ("missing"); T.Fail ("Exception NO_PROPERTY was not raised"); exception when NO_PROPERTY => null; end; end Test_Missing_Property; procedure Test_Load_Ini_Property (T : in out Test) is Props : Properties.Manager; F : File_Type; begin Open (F, In_File, "regtests/files/my.cnf"); Load_Properties (Props, F); Close (F); declare V : Util.Properties.Value; P : Properties.Manager; begin V := Props.Get_Value ("mysqld"); T.Assert (Util.Properties.Is_Manager (V), "Value 'mysqld' must be a property manager"); P := Util.Properties.To_Manager (V); T.Assert (P.Exists ("user"), "The [mysqld] property manager should contain a 'user' property"); V := Props.Get_Value ("mysqld_safe"); T.Assert (Util.Properties.Is_Manager (V), "Value 'mysqld_safe' must be a property manager"); P := Util.Properties.To_Manager (V); T.Assert (P.Exists ("socket"), "The [mysqld] property manager should contain a 'socket' property"); end; declare P : Properties.Manager; begin P := Props.Get ("mysqld"); T.Assert (P.Exists ("user"), "The [mysqld] property manager should contain a 'user' property"); P := Props.Get ("mysqld_safe"); T.Assert (P.Exists ("socket"), "The [mysqld] property manager should contain a 'socket' property"); end; declare P : Properties.Manager with Unreferenced; begin P := Props.Get ("bad"); T.Fail ("No exception raised for Get()"); exception when NO_PROPERTY => null; end; exception when Ada.Text_IO.Name_Error => Ada.Text_IO.Put_Line ("Cannot find test file: regtests/files/my.cnf"); raise; end Test_Load_Ini_Property; procedure Test_Save_Properties (T : in out Test) is Path : constant String := Util.Tests.Get_Test_Path ("save-props.properties"); begin declare Props : Properties.Manager; F : File_Type; begin Open (F, In_File, "regtests/files/my.cnf"); Load_Properties (Props, F); Close (F); Props.Set ("New-Property", "Some-Value"); Props.Remove ("mysqld"); T.Assert (not Props.Exists ("mysqld"), "mysqld property was not removed"); Props.Save_Properties (Path); end; declare Props : Properties.Manager; V : Util.Properties.Value; P : Properties.Manager; begin Props.Load_Properties (Path => Path); T.Assert (not Props.Exists ("mysqld"), "mysqld property was not removed (2)"); T.Assert (Props.Exists ("New-Property"), "Invalid Save_Properties"); V := Props.Get_Value ("mysqld_safe"); T.Assert (Util.Properties.Is_Manager (V), "Value 'mysqld_safe' must be a property manager"); P := Util.Properties.To_Manager (V); T.Assert (P.Exists ("socket"), "The [mysqld] property manager should contain a 'socket' property"); end; end Test_Save_Properties; procedure Test_Remove_Property (T : in out Test) is Props : Properties.Manager; begin begin Props.Remove ("missing"); T.Fail ("Remove should raise exception"); exception when NO_PROPERTY => null; end; begin Props.Remove (+("missing")); T.Fail ("Remove should raise exception"); exception when NO_PROPERTY => null; end; Props.Set ("a", "b"); T.Assert (Props.Exists ("a"), "Property not inserted"); Props.Remove ("a"); T.Assert (not Props.Exists ("a"), "Property not removed"); Props.Set ("a", +("b")); T.Assert (Props.Exists ("a"), "Property not inserted"); Props.Remove (+("a")); T.Assert (not Props.Exists ("a"), "Property not removed"); end Test_Remove_Property; package Caller is new Util.Test_Caller (Test, "Properties"); procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is begin Caller.Add_Test (Suite, "Test Util.Properties.Set", Test_Property'Access); Caller.Add_Test (Suite, "Test Util.Properties.Get", Test_Property'Access); Caller.Add_Test (Suite, "Test Util.Properties.Exists", Test_Property'Access); Caller.Add_Test (Suite, "Test Util.Properties.Remove", Test_Remove_Property'Access); Caller.Add_Test (Suite, "Test Util.Properties.Get (NO_PROPERTY)", Test_Missing_Property'Access); Caller.Add_Test (Suite, "Test Util.Properties.Discrete.Get", Test_Integer_Property'Access); Caller.Add_Test (Suite, "Test Util.Properties.Discrete.Set", Test_Integer_Property'Access); Caller.Add_Test (Suite, "Test Util.Properties.Load_Properties", Test_Load_Property'Access); Caller.Add_Test (Suite, "Test Util.Properties.Load_Properties (INI)", Test_Load_Ini_Property'Access); Caller.Add_Test (Suite, "Test Util.Properties.Load_Strip_Properties", Test_Load_Strip_Property'Access); Caller.Add_Test (Suite, "Test Util.Properties.Copy", Test_Copy_Property'Access); Caller.Add_Test (Suite, "Test Util.Properties.Set+Assign", Test_Set_Preserve_Original'Access); Caller.Add_Test (Suite, "Test Util.Properties.Set+Assign+Remove", Test_Remove_Preserve_Original'Access); Caller.Add_Test (Suite, "Test Util.Properties.Save_Properties", Test_Save_Properties'Access); end Add_Tests; end Util.Properties.Tests;
Implement the Test_Remove_Property and register it for execution
Implement the Test_Remove_Property and register it for execution
Ada
apache-2.0
stcarrez/ada-util,stcarrez/ada-util
282b9a0c5a582f2043c5a2a4d8816ba6cc9b068c
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; with Util.Refs; 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; type Document is tagged 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 new Util.Refs.Ref_Entity with 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); package Node_List_Refs is new Util.Refs.References (Node_List, Node_List_Access); subtype Node_List_Ref is Node_List_Refs.Ref; type Document is new Ada.Finalization.Controlled with record Nodes : Node_List_Ref; 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; with Util.Refs; 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_PREFORMAT, 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 N_PREFORMAT => Preformatted : WString (1 .. Len); when others => null; end case; end record; type Document is tagged 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 new Util.Refs.Ref_Entity with 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); package Node_List_Refs is new Util.Refs.References (Node_List, Node_List_Access); subtype Node_List_Ref is Node_List_Refs.Ref; type Document is new Ada.Finalization.Controlled with record Nodes : Node_List_Ref; Current : Node_Type_Access; end record; overriding procedure Initialize (Doc : in out Document); end Wiki.Nodes;
Add N_PREFORMAT node type
Add N_PREFORMAT node type
Ada
apache-2.0
stcarrez/ada-wiki,stcarrez/ada-wiki
f022f99e4ca49c736aab8bdad284cf69bce58127
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; -- == 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 -- -- There are basically two steps that an application must implement: -- -- * <b>Discovery</b>: to resolve and use the OpenID provider and redirect the user to the -- provider authentication form. -- * <b>Verify</b>: to decode the authentication and check its result. -- -- [http://ada-security.googlecode.com/svn/wiki/OpenID.png] -- -- The authentication process is the following: -- -- * The application should redirect 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. -- -- === Initialization === -- The initialization process must be done before each two steps (discovery and verify). -- The OpenID manager must be declared and configured. -- -- Mgr : Openid.Manager; -- -- For the configuration, the <b>Initialize</b> procedure is called to configure -- the OpenID realm and set the OpenID return callback CB. The return callback -- must be a valid URL that is based on the realm. Example: -- -- Mgr.Initialize (Name => "http://app.site.com/auth", -- Return_To => "http://app.site.com/auth/verify"); -- -- After this initialization, the OpenID manager can be used in the authentication process. -- -- === 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>. -- -- OP : Openid.End_Point; -- Assoc : constant Association_Access := new Association; -- -- The following steps are performed: -- -- * 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 in <tt>OP</tt>. -- * 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. -- -- 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. -- -- 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. -- -- 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;
----------------------------------------------------------------------- -- 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; -- == 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 -- -- There are basically two steps that an application must implement: -- -- * <b>Discovery</b>: to resolve and use the OpenID provider and redirect the user to the -- provider authentication form. -- * <b>Verify</b>: to decode the authentication and check its result. -- -- [http://ada-security.googlecode.com/svn/wiki/OpenID.png] -- -- The authentication process is the following: -- -- * The application should redirect 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. -- -- === Initialization === -- The initialization process must be done before each two steps (discovery and verify). -- The OpenID manager must be declared and configured. -- -- Mgr : Openid.Manager; -- -- For the configuration, the <b>Initialize</b> procedure is called to configure -- the OpenID realm and set the OpenID return callback URL. The return callback -- must be a valid URL that is based on the realm. Example: -- -- Mgr.Initialize (Name => "http://app.site.com/auth", -- Return_To => "http://app.site.com/auth/verify"); -- -- After this initialization, the OpenID manager can be used in the authentication process. -- -- === 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>. The OpenID provider is specified as an -- URL, below is an example for Google OpenID: -- -- Provider : constant String := "https://www.google.com/accounts/o8/id"; -- OP : Openid.End_Point; -- Assoc : constant Association_Access := new Association; -- -- The following steps are performed: -- -- * 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 in <tt>OP</tt>. -- * 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. -- -- 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. -- -- 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. -- -- 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;
Update the documentation
Update the documentation
Ada
apache-2.0
Letractively/ada-security
c2aa1cdc9fb0fd09b178b8686b1a3ed5d9e8a338
src/wiki-render.ads
src/wiki-render.ads
----------------------------------------------------------------------- -- wiki-render -- Wiki renderer -- 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.Wide_Wide_Unbounded; with Wiki.Documents; with Wiki.Attributes; with Wiki.Nodes; package Wiki.Render is pragma Preelaborate; use Ada.Strings.Wide_Wide_Unbounded; type Link_Renderer is limited interface; type Link_Renderer_Access is access all Link_Renderer'Class; -- Get the image link that must be rendered from the wiki image link. procedure Make_Image_Link (Renderer : in Link_Renderer; Link : in Unbounded_Wide_Wide_String; URI : out Unbounded_Wide_Wide_String; Width : out Natural; Height : out Natural) is abstract; -- Get the page link that must be rendered from the wiki page link. procedure Make_Page_Link (Renderer : in Link_Renderer; Link : in Unbounded_Wide_Wide_String; URI : out Unbounded_Wide_Wide_String; Exists : out Boolean) is abstract; type Default_Link_Renderer is new Link_Renderer with null record; -- Get the image link that must be rendered from the wiki image link. overriding procedure Make_Image_Link (Renderer : in Default_Link_Renderer; Link : in Unbounded_Wide_Wide_String; URI : out Unbounded_Wide_Wide_String; Width : out Natural; Height : out Natural); -- Get the page link that must be rendered from the wiki page link. overriding procedure Make_Page_Link (Renderer : in Default_Link_Renderer; Link : in Unbounded_Wide_Wide_String; URI : out Unbounded_Wide_Wide_String; Exists : out Boolean); -- ------------------------------ -- Document renderer -- ------------------------------ type Renderer is limited interface; type Renderer_Access is access all Renderer'Class; -- Render the node instance from the document. procedure Render (Engine : in out Renderer; Doc : in Wiki.Nodes.Document; Node : in Wiki.Nodes.Node_Type) is abstract; -- Finish the rendering after complete wiki document nodes are rendered. procedure Finish (Document : in out Renderer) is abstract; end Wiki.Render;
----------------------------------------------------------------------- -- wiki-render -- Wiki renderer -- 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.Wide_Wide_Unbounded; with Wiki.Nodes; package Wiki.Render is pragma Preelaborate; use Ada.Strings.Wide_Wide_Unbounded; type Link_Renderer is limited interface; type Link_Renderer_Access is access all Link_Renderer'Class; -- Get the image link that must be rendered from the wiki image link. procedure Make_Image_Link (Renderer : in Link_Renderer; Link : in Unbounded_Wide_Wide_String; URI : out Unbounded_Wide_Wide_String; Width : out Natural; Height : out Natural) is abstract; -- Get the page link that must be rendered from the wiki page link. procedure Make_Page_Link (Renderer : in Link_Renderer; Link : in Unbounded_Wide_Wide_String; URI : out Unbounded_Wide_Wide_String; Exists : out Boolean) is abstract; type Default_Link_Renderer is new Link_Renderer with null record; -- Get the image link that must be rendered from the wiki image link. overriding procedure Make_Image_Link (Renderer : in Default_Link_Renderer; Link : in Unbounded_Wide_Wide_String; URI : out Unbounded_Wide_Wide_String; Width : out Natural; Height : out Natural); -- Get the page link that must be rendered from the wiki page link. overriding procedure Make_Page_Link (Renderer : in Default_Link_Renderer; Link : in Unbounded_Wide_Wide_String; URI : out Unbounded_Wide_Wide_String; Exists : out Boolean); -- ------------------------------ -- Document renderer -- ------------------------------ type Renderer is limited interface; type Renderer_Access is access all Renderer'Class; -- Render the node instance from the document. procedure Render (Engine : in out Renderer; Doc : in Wiki.Nodes.Document; Node : in Wiki.Nodes.Node_Type) is abstract; -- Finish the rendering after complete wiki document nodes are rendered. procedure Finish (Document : in out Renderer) is abstract; -- Render the list of nodes from the document. procedure Render (Engine : in out Renderer'Class; Doc : in Wiki.Nodes.Document; List : in Wiki.Nodes.Node_List_Access); end Wiki.Render;
Declare the Render procedure
Declare the Render procedure
Ada
apache-2.0
stcarrez/ada-wiki,stcarrez/ada-wiki
d19eeee3c9d7d33bf45cc9cd37c4e57ac71d4de3
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 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES 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 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); declare Ctx : EL.Contexts.Default.Default_Context; Command : constant String := Module.Get_Config (PARAM_THUMBNAIL_COMMAND); begin Service.Thumbnail_Command := EL.Expressions.Create_Expression (Command, Ctx); exception when E : others => Log.Error ("Invalid thumbnail command: ", E, True); end; end Initialize; procedure Create_Thumbnail (Service : in Image_Service; Source : in String; Into : in String; Width : out Natural; Height : 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)); 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); Input.Initialize (null, Pipe'Unchecked_Access, 1024); while not Input.Is_Eof loop declare 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 (Ada.Strings.Unbounded.Slice (Line, Pos + 1, Sep - 1)); Height := Natural'Value (Ada.Strings.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; -- Save the data object contained in the <b>Data</b> part element into the -- target storage represented by <b>Into</b>. procedure Build_Thumbnail (Service : in Image_Service; Id : in ADO.Identifier; File : in AWA.Storages.Models.Storage_Ref'Class) 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; Local_Path : Ada.Strings.Unbounded.Unbounded_String; Target_File : AWA.Storages.Storage_File; Local_File : AWA.Storages.Storage_File; Width : Natural; Height : Natural; begin Img.Load (DB, Id); Storage_Service.Get_Local_File (From => Img.Get_Storage.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); Img.Set_Width (Width); Img.Set_Height (Height); Img.Set_Thumb_Width (64); Img.Set_Thumb_Height (64); Ctx.Start; Img.Save (DB); -- Storage_Service.Save (Target_File); Ctx.Commit; 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 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.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; end AWA.Images.Services;
----------------------------------------------------------------------- -- awa-images-services -- Image service -- 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.Processes; with Util.Beans.Objects; with Util.Log.Loggers; with Util.Streams.Pipes; with Util.Streams.Texts; 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); declare Ctx : EL.Contexts.Default.Default_Context; Command : constant String := Module.Get_Config (PARAM_THUMBNAIL_COMMAND); begin Service.Thumbnail_Command := EL.Expressions.Create_Expression (Command, Ctx); exception when E : others => Log.Error ("Invalid thumbnail command: ", E, True); end; end Initialize; procedure Create_Thumbnail (Service : in Image_Service; Source : in String; Into : in String; Width : out Natural; Height : 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)); 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); Input.Initialize (null, Pipe'Unchecked_Access, 1024); while not Input.Is_Eof loop declare 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 (Ada.Strings.Unbounded.Slice (Line, Pos + 1, Sep - 1)); Height := Natural'Value (Ada.Strings.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; -- Save the data object contained in the <b>Data</b> part element into the -- target storage represented by <b>Into</b>. procedure Build_Thumbnail (Service : in Image_Service; Id : in ADO.Identifier; File : in AWA.Storages.Models.Storage_Ref'Class) 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; Local_Path : Ada.Strings.Unbounded.Unbounded_String; Target_File : AWA.Storages.Storage_File; Local_File : AWA.Storages.Storage_File; Width : Natural; Height : Natural; begin Img.Load (DB, Id); Storage_Service.Get_Local_File (From => Img.Get_Storage.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); Img.Set_Width (Width); Img.Set_Height (Height); Img.Set_Thumb_Width (64); Img.Set_Thumb_Height (64); Ctx.Start; Img.Save (DB); -- Storage_Service.Save (Target_File); Ctx.Commit; 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 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.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; end AWA.Images.Services;
Fix compilation warning
Fix compilation warning
Ada
apache-2.0
Letractively/ada-awa,tectronics/ada-awa,tectronics/ada-awa,tectronics/ada-awa,Letractively/ada-awa,Letractively/ada-awa
096d79c529d3f6b414f03a284dd8feadc9ae042c
mat/src/mat-targets.ads
mat/src/mat-targets.ads
----------------------------------------------------------------------- -- mat-targets - Representation of target information -- 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 Ada.Containers.Ordered_Maps; with GNAT.Sockets; with MAT.Types; with MAT.Memory.Targets; with MAT.Symbols.Targets; with MAT.Readers.Streams.Sockets; with MAT.Readers; with MAT.Consoles; package MAT.Targets is -- Exception raised if some option is invalid. Usage_Error : exception; -- The options that can be configured through the command line. type Options_Type is record -- Enable and enter in the interactive TTY console mode. Interactive : Boolean := True; -- Try to load the symbol file automatically when a new process is recieved. Load_Symbols : Boolean := True; -- Enable the graphical mode (when available). Graphical : Boolean := False; -- Define the server listening address. Address : GNAT.Sockets.Sock_Addr_Type := (Port => 4096, others => <>); end record; type Target_Process_Type is tagged limited record Pid : MAT.Types.Target_Process_Ref; Path : Ada.Strings.Unbounded.Unbounded_String; Memory : MAT.Memory.Targets.Target_Memory; Symbols : MAT.Symbols.Targets.Target_Symbols_Ref; Console : MAT.Consoles.Console_Access; end record; type Target_Process_Type_Access is access all Target_Process_Type'Class; type Target_Type is tagged limited private; type Target_Type_Access is access all Target_Type'Class; -- Get the console instance. function Console (Target : in Target_Type) return MAT.Consoles.Console_Access; -- Set the console instance. procedure Console (Target : in out Target_Type; Console : in MAT.Consoles.Console_Access); -- Get the current process instance. function Process (Target : in Target_Type) return Target_Process_Type_Access; -- Initialize the target object to manage the memory slots, the stack frames -- and setup the reader to analyze the memory and other events. procedure Initialize (Target : in out Target_Type; Reader : in out MAT.Readers.Manager_Base'Class); -- Create a process instance to hold and keep track of memory and other information about -- the given process ID. procedure Create_Process (Target : in out Target_Type; Pid : in MAT.Types.Target_Process_Ref; Path : in Ada.Strings.Unbounded.Unbounded_String; Process : out Target_Process_Type_Access); -- Find the process instance from the process ID. function Find_Process (Target : in Target_Type; Pid : in MAT.Types.Target_Process_Ref) return Target_Process_Type_Access; -- Parse the command line arguments and configure the target instance. procedure Initialize_Options (Target : in out MAT.Targets.Target_Type); -- Start the server to listen to MAT event socket streams. procedure Start (Target : in out Target_Type); -- Convert the string to a socket address. The string can have two forms: -- port -- host:port function To_Sock_Addr_Type (Param : in String) return GNAT.Sockets.Sock_Addr_Type; -- Print the application usage. procedure Usage; private -- Define a map of <tt>Target_Process_Type_Access</tt> keyed by the process Id. -- This map allows to retrieve the information about a process. use type MAT.Types.Target_Process_Ref; package Process_Maps is new Ada.Containers.Ordered_Maps (Key_Type => MAT.Types.Target_Process_Ref, Element_Type => Target_Process_Type_Access); subtype Process_Map is Process_Maps.Map; subtype Process_Cursor is Process_Maps.Cursor; type Target_Type is tagged limited record Current : Target_Process_Type_Access; Processes : Process_Map; Console : MAT.Consoles.Console_Access; Options : Options_Type; Server : MAT.Readers.Streams.Sockets.Socket_Listener_Type; end record; end MAT.Targets;
----------------------------------------------------------------------- -- mat-targets - Representation of target information -- 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 Ada.Containers.Ordered_Maps; with GNAT.Sockets; with MAT.Types; with MAT.Memory.Targets; with MAT.Symbols.Targets; with MAT.Readers.Streams.Sockets; with MAT.Readers; with MAT.Consoles; package MAT.Targets is -- Exception raised if some option is invalid. Usage_Error : exception; -- The options that can be configured through the command line. type Options_Type is record -- Enable and enter in the interactive TTY console mode. Interactive : Boolean := True; -- Try to load the symbol file automatically when a new process is recieved. Load_Symbols : Boolean := True; -- Enable the graphical mode (when available). Graphical : Boolean := False; -- Define the server listening address. Address : GNAT.Sockets.Sock_Addr_Type := (Port => 4096, others => <>); end record; type Target_Process_Type is tagged limited record Pid : MAT.Types.Target_Process_Ref; Path : Ada.Strings.Unbounded.Unbounded_String; Memory : MAT.Memory.Targets.Target_Memory; Symbols : MAT.Symbols.Targets.Target_Symbols_Ref; Console : MAT.Consoles.Console_Access; end record; type Target_Process_Type_Access is access all Target_Process_Type'Class; type Target_Type is tagged limited private; type Target_Type_Access is access all Target_Type'Class; -- Get the console instance. function Console (Target : in Target_Type) return MAT.Consoles.Console_Access; -- Set the console instance. procedure Console (Target : in out Target_Type; Console : in MAT.Consoles.Console_Access); -- Get the current process instance. function Process (Target : in Target_Type) return Target_Process_Type_Access; -- Initialize the target object to manage the memory slots, the stack frames -- and setup the reader to analyze the memory and other events. procedure Initialize (Target : in out Target_Type; Reader : in out MAT.Readers.Manager_Base'Class); -- Create a process instance to hold and keep track of memory and other information about -- the given process ID. procedure Create_Process (Target : in out Target_Type; Pid : in MAT.Types.Target_Process_Ref; Path : in Ada.Strings.Unbounded.Unbounded_String; Process : out Target_Process_Type_Access); -- Find the process instance from the process ID. function Find_Process (Target : in Target_Type; Pid : in MAT.Types.Target_Process_Ref) return Target_Process_Type_Access; -- Parse the command line arguments and configure the target instance. procedure Initialize_Options (Target : in out Target_Type); -- Start the server to listen to MAT event socket streams. procedure Start (Target : in out Target_Type); -- Stop the server thread. procedure Stop (Target : in out Target_Type); -- Convert the string to a socket address. The string can have two forms: -- port -- host:port function To_Sock_Addr_Type (Param : in String) return GNAT.Sockets.Sock_Addr_Type; -- Print the application usage. procedure Usage; private -- Define a map of <tt>Target_Process_Type_Access</tt> keyed by the process Id. -- This map allows to retrieve the information about a process. use type MAT.Types.Target_Process_Ref; package Process_Maps is new Ada.Containers.Ordered_Maps (Key_Type => MAT.Types.Target_Process_Ref, Element_Type => Target_Process_Type_Access); subtype Process_Map is Process_Maps.Map; subtype Process_Cursor is Process_Maps.Cursor; type Target_Type is tagged limited record Current : Target_Process_Type_Access; Processes : Process_Map; Console : MAT.Consoles.Console_Access; Options : Options_Type; Server : MAT.Readers.Streams.Sockets.Socket_Listener_Type; end record; end MAT.Targets;
Declare the Stop procedure
Declare the Stop procedure
Ada
apache-2.0
stcarrez/mat,stcarrez/mat,stcarrez/mat
6d346bfbff24e2770cf9a6b25fa7fd25a8177325
src/util-properties-basic.adb
src/util-properties-basic.adb
----------------------------------------------------------------------- -- basic properties -- Basic types properties -- Copyright (C) 2001, 2002, 2003, 2006, 2008, 2009, 2010 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- package body Util.Properties.Basic is end Util.Properties.Basic;
----------------------------------------------------------------------- -- util-properties-basic -- Basic types properties -- Copyright (C) 2001, 2002, 2003, 2006, 2008, 2009, 2010, 2018 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- package body Util.Properties.Basic is end Util.Properties.Basic;
Fix header style
Fix header style
Ada
apache-2.0
stcarrez/ada-util,stcarrez/ada-util
a2d7c6974637eb6dad313248a3271d6f0d66067e
src/util-streams-buffered.adb
src/util-streams-buffered.adb
----------------------------------------------------------------------- -- Util.Streams.Buffered -- Buffered streams Stream utilities -- Copyright (C) 2010, 2011, 2013, 2014, 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 Interfaces; with Ada.IO_Exceptions; with Ada.Unchecked_Deallocation; package body Util.Streams.Buffered is procedure Free_Buffer is new Ada.Unchecked_Deallocation (Object => Stream_Element_Array, Name => Buffer_Access); -- ------------------------------ -- Initialize the stream to read or write on the given streams. -- An internal buffer is allocated for writing the stream. -- ------------------------------ procedure Initialize (Stream : in out Buffered_Stream; Output : in Output_Stream_Access; Input : in Input_Stream_Access; Size : in Positive) is begin Free_Buffer (Stream.Buffer); Stream.Last := Stream_Element_Offset (Size); Stream.Buffer := new Stream_Element_Array (1 .. Stream.Last); Stream.Output := Output; Stream.Input := Input; Stream.Write_Pos := 1; Stream.Read_Pos := 1; Stream.No_Flush := False; end Initialize; -- ------------------------------ -- Initialize the stream to read from the string. -- ------------------------------ procedure Initialize (Stream : in out Buffered_Stream; Content : in String) is begin Free_Buffer (Stream.Buffer); Stream.Last := Stream_Element_Offset (Content'Length); Stream.Buffer := new Stream_Element_Array (1 .. Content'Length); Stream.Output := null; Stream.Input := null; Stream.Write_Pos := Stream.Last + 1; Stream.Read_Pos := 1; Stream.No_Flush := False; for I in Content'Range loop Stream.Buffer (Stream_Element_Offset (I - Content'First + 1)) := Character'Pos (Content (I)); end loop; end Initialize; -- ------------------------------ -- Initialize the stream with a buffer of <b>Size</b> bytes. -- ------------------------------ procedure Initialize (Stream : in out Buffered_Stream; Size : in Positive) is begin Stream.Initialize (Output => null, Input => null, Size => Size); Stream.No_Flush := True; Stream.Read_Pos := 1; end Initialize; -- ------------------------------ -- Close the sink. -- ------------------------------ overriding procedure Close (Stream : in out Buffered_Stream) is begin if Stream.Output /= null then Buffered_Stream'Class (Stream).Flush; Stream.Output.Close; end if; end Close; -- ------------------------------ -- Get the direct access to the buffer. -- ------------------------------ function Get_Buffer (Stream : in Buffered_Stream) return Buffer_Access is begin return Stream.Buffer; end Get_Buffer; -- ------------------------------ -- Get the number of element in the stream. -- ------------------------------ function Get_Size (Stream : in Buffered_Stream) return Natural is begin return Natural (Stream.Write_Pos - Stream.Read_Pos); end Get_Size; -- ------------------------------ -- Write a raw character on the stream. -- ------------------------------ procedure Write (Stream : in out Buffered_Stream; Char : in Character) is begin if Stream.Write_Pos > Stream.Last then Stream.Flush; if Stream.Write_Pos > Stream.Last then raise Ada.IO_Exceptions.End_Error with "Buffer is full"; end if; end if; Stream.Buffer (Stream.Write_Pos) := Stream_Element (Character'Pos (Char)); Stream.Write_Pos := Stream.Write_Pos + 1; end Write; -- ------------------------------ -- Write a wide character on the stream doing some conversion if necessary. -- The default implementation translates the wide character to a UTF-8 sequence. -- ------------------------------ procedure Write_Wide (Stream : in out Buffered_Stream; Item : in Wide_Wide_Character) is use Interfaces; Val : Unsigned_32; begin -- UTF-8 conversion -- 7 U+0000 U+007F 1 0xxxxxxx -- 11 U+0080 U+07FF 2 110xxxxx 10xxxxxx -- 16 U+0800 U+FFFF 3 1110xxxx 10xxxxxx 10xxxxxx -- 21 U+10000 U+1FFFFF 4 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx Val := Wide_Wide_Character'Pos (Item); if Val <= 16#7f# then Stream.Write (Character'Val (Val)); elsif Val <= 16#07FF# then Stream.Write (Character'Val (16#C0# or Shift_Right (Val, 6))); Stream.Write (Character'Val (16#80# or (Val and 16#03F#))); elsif Val <= 16#0FFFF# then Stream.Write (Character'Val (16#E0# or Shift_Right (Val, 12))); Val := Val and 16#0FFF#; Stream.Write (Character'Val (16#80# or Shift_Right (Val, 6))); Stream.Write (Character'Val (16#80# or (Val and 16#03F#))); else Val := Val and 16#1FFFFF#; Stream.Write (Character'Val (16#F0# or Shift_Right (Val, 18))); Val := Val and 16#3FFFF#; Stream.Write (Character'Val (16#80# or Shift_Right (Val, 12))); Val := Val and 16#0FFF#; Stream.Write (Character'Val (16#80# or Shift_Right (Val, 6))); Stream.Write (Character'Val (16#80# or (Val and 16#03F#))); end if; end Write_Wide; -- ------------------------------ -- Write a raw string on the stream. -- ------------------------------ procedure Write (Stream : in out Buffered_Stream; Item : in String) is Start : Positive := Item'First; Pos : Stream_Element_Offset := Stream.Write_Pos; Avail : Natural; Size : Natural; Char : Character; begin while Start <= Item'Last loop Size := Item'Last - Start + 1; Avail := Natural (Stream.Last - Pos + 1); if Avail = 0 then Stream.Flush; Pos := Stream.Write_Pos; Avail := Natural (Stream.Last - Pos + 1); if Avail = 0 then raise Ada.IO_Exceptions.End_Error with "Buffer is full"; end if; end if; if Avail < Size then Size := Avail; end if; while Size > 0 loop Char := Item (Start); Stream.Buffer (Pos) := Stream_Element (Character'Pos (Char)); Pos := Pos + 1; Start := Start + 1; Size := Size - 1; end loop; Stream.Write_Pos := Pos; end loop; end Write; -- ------------------------------ -- Write a raw string on the stream. -- ------------------------------ procedure Write (Stream : in out Buffered_Stream; Item : in Ada.Strings.Unbounded.Unbounded_String) is Count : constant Natural := Ada.Strings.Unbounded.Length (Item); begin if Count > 0 then for I in 1 .. Count loop Stream.Write (Char => Ada.Strings.Unbounded.Element (Item, I)); end loop; end if; end Write; -- ------------------------------ -- Write a raw string on the stream. -- ------------------------------ procedure Write (Stream : in out Buffered_Stream; Item : in Ada.Strings.Wide_Wide_Unbounded.Unbounded_Wide_Wide_String) is Count : constant Natural := Ada.Strings.Wide_Wide_Unbounded.Length (Item); C : Wide_Wide_Character; begin if Count > 0 then for I in 1 .. Count loop C := Ada.Strings.Wide_Wide_Unbounded.Element (Item, I); Stream.Write (Char => Character'Val (Wide_Wide_Character'Pos (C))); end loop; end if; end Write; -- ------------------------------ -- Write the buffer array to the output stream. -- ------------------------------ overriding procedure Write (Stream : in out Buffered_Stream; Buffer : in Ada.Streams.Stream_Element_Array) is Start : Stream_Element_Offset := Buffer'First; Pos : Stream_Element_Offset := Stream.Write_Pos; Avail : Stream_Element_Offset; Size : Stream_Element_Offset; begin while Start <= Buffer'Last loop Size := Buffer'Last - Start + 1; Avail := Stream.Last - Pos + 1; if Avail = 0 then Stream.Flush; Pos := Stream.Write_Pos; Avail := Stream.Last - Pos + 1; if Avail = 0 then raise Ada.IO_Exceptions.End_Error with "Buffer is full"; end if; end if; if Avail < Size then Size := Avail; end if; Stream.Buffer (Pos .. Pos + Size - 1) := Buffer (Start .. Start + Size - 1); Start := Start + Size; Pos := Pos + Size; Stream.Write_Pos := Pos; -- If we have still more data that the buffer size, flush and write -- the buffer directly. if Start < Buffer'Last and then Buffer'Last - Start > Stream.Buffer'Length then Stream.Flush; Stream.Output.Write (Buffer (Start .. Buffer'Last)); return; end if; end loop; end Write; -- ------------------------------ -- Flush the stream. -- ------------------------------ overriding procedure Flush (Stream : in out Buffered_Stream) is begin if Stream.Write_Pos > 1 and not Stream.No_Flush then if Stream.Output = null then raise Ada.IO_Exceptions.Data_Error with "Output buffer is full"; else Stream.Output.Write (Stream.Buffer (1 .. Stream.Write_Pos - 1)); Stream.Output.Flush; end if; Stream.Write_Pos := 1; end if; end Flush; -- ------------------------------ -- Fill the buffer by reading the input stream. -- Raises Data_Error if there is no input stream; -- ------------------------------ procedure Fill (Stream : in out Buffered_Stream) is begin if Stream.Input = null then Stream.Eof := True; else Stream.Input.Read (Stream.Buffer (1 .. Stream.Last - 1), Stream.Write_Pos); Stream.Eof := Stream.Write_Pos < 1; if not Stream.Eof then Stream.Write_Pos := Stream.Write_Pos + 1; end if; Stream.Read_Pos := 1; end if; end Fill; -- ------------------------------ -- Read one character from the input stream. -- ------------------------------ procedure Read (Stream : in out Buffered_Stream; Char : out Character) is begin if Stream.Read_Pos >= Stream.Write_Pos then Stream.Fill; if Stream.Eof then raise Ada.IO_Exceptions.Data_Error with "End of buffer"; end if; end if; Char := Character'Val (Stream.Buffer (Stream.Read_Pos)); Stream.Read_Pos := Stream.Read_Pos + 1; end Read; -- ------------------------------ -- Read into the buffer as many bytes as possible and return in -- <b>last</b> the position of the last byte read. -- ------------------------------ overriding procedure Read (Stream : in out Buffered_Stream; Into : out Ada.Streams.Stream_Element_Array; Last : out Ada.Streams.Stream_Element_Offset) is Start : Stream_Element_Offset := Into'First; Pos : Stream_Element_Offset := Stream.Read_Pos; Avail : Stream_Element_Offset; Size : Stream_Element_Offset; Total : Stream_Element_Offset := 0; begin while Start <= Into'Last loop Size := Into'Last - Start + 1; Avail := Stream.Write_Pos - Pos; if Avail = 0 then Stream.Fill; Pos := Stream.Read_Pos; Avail := Stream.Write_Pos - Pos; exit when Avail <= 0; end if; if Avail < Size then Size := Avail; end if; Into (Start .. Start + Size - 1) := Stream.Buffer (Pos .. Pos + Size - 1); Start := Start + Size; Pos := Pos + Size; Total := Total + Size; Stream.Read_Pos := Pos; end loop; Last := Total; end Read; -- ------------------------------ -- Read into the buffer as many bytes as possible and return in -- <b>last</b> the position of the last byte read. -- ------------------------------ procedure Read (Stream : in out Buffered_Stream; Into : in out Ada.Strings.Unbounded.Unbounded_String) is Pos : Stream_Element_Offset := Stream.Read_Pos; Avail : Stream_Element_Offset; begin loop Avail := Stream.Write_Pos - Pos; if Avail = 0 then Stream.Fill; if Stream.Eof then return; end if; Pos := Stream.Read_Pos; Avail := Stream.Write_Pos - Pos; end if; for I in 1 .. Avail loop Ada.Strings.Unbounded.Append (Into, Character'Val (Stream.Buffer (Pos))); Pos := Pos + 1; end loop; Stream.Read_Pos := Pos; end loop; end Read; -- ------------------------------ -- Flush the stream and release the buffer. -- ------------------------------ overriding procedure Finalize (Object : in out Buffered_Stream) is begin if Object.Buffer /= null then if Object.Output /= null then Object.Flush; end if; Free_Buffer (Object.Buffer); end if; end Finalize; -- ------------------------------ -- Returns True if the end of the stream is reached. -- ------------------------------ function Is_Eof (Stream : in Buffered_Stream) return Boolean is begin return Stream.Eof; end Is_Eof; end Util.Streams.Buffered;
----------------------------------------------------------------------- -- util-streams-buffered -- Buffered streams Stream utilities -- Copyright (C) 2010, 2011, 2013, 2014, 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 Interfaces; with Ada.IO_Exceptions; with Ada.Unchecked_Deallocation; package body Util.Streams.Buffered is procedure Free_Buffer is new Ada.Unchecked_Deallocation (Object => Stream_Element_Array, Name => Buffer_Access); -- ------------------------------ -- Initialize the stream to read or write on the given streams. -- An internal buffer is allocated for writing the stream. -- ------------------------------ procedure Initialize (Stream : in out Buffered_Stream; Output : in Output_Stream_Access; Input : in Input_Stream_Access; Size : in Positive) is begin Free_Buffer (Stream.Buffer); Stream.Last := Stream_Element_Offset (Size); Stream.Buffer := new Stream_Element_Array (1 .. Stream.Last); Stream.Output := Output; Stream.Input := Input; Stream.Write_Pos := 1; Stream.Read_Pos := 1; Stream.No_Flush := False; end Initialize; -- ------------------------------ -- Initialize the stream to read from the string. -- ------------------------------ procedure Initialize (Stream : in out Buffered_Stream; Content : in String) is begin Free_Buffer (Stream.Buffer); Stream.Last := Stream_Element_Offset (Content'Length); Stream.Buffer := new Stream_Element_Array (1 .. Content'Length); Stream.Output := null; Stream.Input := null; Stream.Write_Pos := Stream.Last + 1; Stream.Read_Pos := 1; Stream.No_Flush := False; for I in Content'Range loop Stream.Buffer (Stream_Element_Offset (I - Content'First + 1)) := Character'Pos (Content (I)); end loop; end Initialize; -- ------------------------------ -- Initialize the stream with a buffer of <b>Size</b> bytes. -- ------------------------------ procedure Initialize (Stream : in out Buffered_Stream; Size : in Positive) is begin Stream.Initialize (Output => null, Input => null, Size => Size); Stream.No_Flush := True; Stream.Read_Pos := 1; end Initialize; -- ------------------------------ -- Close the sink. -- ------------------------------ overriding procedure Close (Stream : in out Buffered_Stream) is begin if Stream.Output /= null then Buffered_Stream'Class (Stream).Flush; Stream.Output.Close; end if; end Close; -- ------------------------------ -- Get the direct access to the buffer. -- ------------------------------ function Get_Buffer (Stream : in Buffered_Stream) return Buffer_Access is begin return Stream.Buffer; end Get_Buffer; -- ------------------------------ -- Get the number of element in the stream. -- ------------------------------ function Get_Size (Stream : in Buffered_Stream) return Natural is begin return Natural (Stream.Write_Pos - Stream.Read_Pos); end Get_Size; -- ------------------------------ -- Write the buffer array to the output stream. -- ------------------------------ overriding procedure Write (Stream : in out Buffered_Stream; Buffer : in Ada.Streams.Stream_Element_Array) is Start : Stream_Element_Offset := Buffer'First; Pos : Stream_Element_Offset := Stream.Write_Pos; Avail : Stream_Element_Offset; Size : Stream_Element_Offset; begin while Start <= Buffer'Last loop Size := Buffer'Last - Start + 1; Avail := Stream.Last - Pos + 1; if Avail = 0 then Stream.Flush; Pos := Stream.Write_Pos; Avail := Stream.Last - Pos + 1; if Avail = 0 then raise Ada.IO_Exceptions.End_Error with "Buffer is full"; end if; end if; if Avail < Size then Size := Avail; end if; Stream.Buffer (Pos .. Pos + Size - 1) := Buffer (Start .. Start + Size - 1); Start := Start + Size; Pos := Pos + Size; Stream.Write_Pos := Pos; -- If we have still more data that the buffer size, flush and write -- the buffer directly. if Start < Buffer'Last and then Buffer'Last - Start > Stream.Buffer'Length then Stream.Flush; Stream.Output.Write (Buffer (Start .. Buffer'Last)); return; end if; end loop; end Write; -- ------------------------------ -- Flush the stream. -- ------------------------------ overriding procedure Flush (Stream : in out Buffered_Stream) is begin if Stream.Write_Pos > 1 and not Stream.No_Flush then if Stream.Output = null then raise Ada.IO_Exceptions.Data_Error with "Output buffer is full"; else Stream.Output.Write (Stream.Buffer (1 .. Stream.Write_Pos - 1)); Stream.Output.Flush; end if; Stream.Write_Pos := 1; end if; end Flush; -- ------------------------------ -- Fill the buffer by reading the input stream. -- Raises Data_Error if there is no input stream; -- ------------------------------ procedure Fill (Stream : in out Buffered_Stream) is begin if Stream.Input = null then Stream.Eof := True; else Stream.Input.Read (Stream.Buffer (1 .. Stream.Last - 1), Stream.Write_Pos); Stream.Eof := Stream.Write_Pos < 1; if not Stream.Eof then Stream.Write_Pos := Stream.Write_Pos + 1; end if; Stream.Read_Pos := 1; end if; end Fill; -- ------------------------------ -- Read one character from the input stream. -- ------------------------------ procedure Read (Stream : in out Buffered_Stream; Char : out Character) is begin if Stream.Read_Pos >= Stream.Write_Pos then Stream.Fill; if Stream.Eof then raise Ada.IO_Exceptions.Data_Error with "End of buffer"; end if; end if; Char := Character'Val (Stream.Buffer (Stream.Read_Pos)); Stream.Read_Pos := Stream.Read_Pos + 1; end Read; -- ------------------------------ -- Read into the buffer as many bytes as possible and return in -- <b>last</b> the position of the last byte read. -- ------------------------------ overriding procedure Read (Stream : in out Buffered_Stream; Into : out Ada.Streams.Stream_Element_Array; Last : out Ada.Streams.Stream_Element_Offset) is Start : Stream_Element_Offset := Into'First; Pos : Stream_Element_Offset := Stream.Read_Pos; Avail : Stream_Element_Offset; Size : Stream_Element_Offset; Total : Stream_Element_Offset := 0; begin while Start <= Into'Last loop Size := Into'Last - Start + 1; Avail := Stream.Write_Pos - Pos; if Avail = 0 then Stream.Fill; Pos := Stream.Read_Pos; Avail := Stream.Write_Pos - Pos; exit when Avail <= 0; end if; if Avail < Size then Size := Avail; end if; Into (Start .. Start + Size - 1) := Stream.Buffer (Pos .. Pos + Size - 1); Start := Start + Size; Pos := Pos + Size; Total := Total + Size; Stream.Read_Pos := Pos; end loop; Last := Total; end Read; -- ------------------------------ -- Read into the buffer as many bytes as possible and return in -- <b>last</b> the position of the last byte read. -- ------------------------------ procedure Read (Stream : in out Buffered_Stream; Into : in out Ada.Strings.Unbounded.Unbounded_String) is Pos : Stream_Element_Offset := Stream.Read_Pos; Avail : Stream_Element_Offset; begin loop Avail := Stream.Write_Pos - Pos; if Avail = 0 then Stream.Fill; if Stream.Eof then return; end if; Pos := Stream.Read_Pos; Avail := Stream.Write_Pos - Pos; end if; for I in 1 .. Avail loop Ada.Strings.Unbounded.Append (Into, Character'Val (Stream.Buffer (Pos))); Pos := Pos + 1; end loop; Stream.Read_Pos := Pos; end loop; end Read; -- ------------------------------ -- Flush the stream and release the buffer. -- ------------------------------ overriding procedure Finalize (Object : in out Buffered_Stream) is begin if Object.Buffer /= null then if Object.Output /= null then Object.Flush; end if; Free_Buffer (Object.Buffer); end if; end Finalize; -- ------------------------------ -- Returns True if the end of the stream is reached. -- ------------------------------ function Is_Eof (Stream : in Buffered_Stream) return Boolean is begin return Stream.Eof; end Is_Eof; end Util.Streams.Buffered;
Refactor Buffered_Stream and Print_Stream - move character related Write operation to the Texts package (Print_Stream)
Refactor Buffered_Stream and Print_Stream - move character related Write operation to the Texts package (Print_Stream)
Ada
apache-2.0
stcarrez/ada-util,stcarrez/ada-util
6e59bcd32420d8cc9de54fdb4f543a5fcc77cb41
samples/json.adb
samples/json.adb
----------------------------------------------------------------------- -- json -- JSON Reader -- Copyright (C) 2010, 2011, 2014, 2017 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Strings.Unbounded; with Ada.Text_IO; with Ada.Command_Line; with Util.Serialize.IO.JSON; with Ada.Containers; with Mapping; with Util.Serialize.Mappers.Vector_Mapper; with Util.Streams.Texts; with Util.Streams.Buffered; procedure Json is use Util.Streams.Buffered; use Ada.Strings.Unbounded; use type Mapping.Person_Access; use type Ada.Containers.Count_Type; use Mapping; Reader : Util.Serialize.IO.JSON.Parser; Mapper : Util.Serialize.Mappers.Processing; Count : constant Natural := Ada.Command_Line.Argument_Count; package Person_Vector_Mapper is new Util.Serialize.Mappers.Vector_Mapper (Vectors => Person_Vector, Element_Mapper => Person_Mapper); subtype Person_Vector_Context is Person_Vector_Mapper.Vector_Data; -- Mapping for a list of Person records (stored as a Vector). Person_Vector_Mapping : aliased Person_Vector_Mapper.Mapper; procedure Print (P : in Mapping.Person_Vector.Cursor); procedure Print (P : in Mapping.Person); procedure Print (P : in Mapping.Person) is begin Ada.Text_IO.Put_Line ("Name : " & To_String (P.Name)); Ada.Text_IO.Put_Line ("first_name : " & To_String (P.First_Name)); Ada.Text_IO.Put_Line ("last_name : " & To_String (P.Last_Name)); Ada.Text_IO.Put_Line ("Age : " & Natural'Image (P.Age)); Ada.Text_IO.Put_Line ("Street : " & To_String (P.Addr.Street)); Ada.Text_IO.Put_Line ("City : " & To_String (P.Addr.City)); Ada.Text_IO.Put_Line ("Zip : " & Natural'Image (P.Addr.Zip)); Ada.Text_IO.Put_Line ("Country : " & To_String (P.Addr.Country)); Ada.Text_IO.Put_Line ("Info : " & To_String (P.Addr.Info.Name) & "=" & To_String (P.Addr.Info.Value)); end Print; procedure Print (P : in Mapping.Person_Vector.Cursor) is begin Print (Mapping.Person_Vector.Element (P)); end Print; begin if Count = 0 then Ada.Text_IO.Put_Line ("Usage: json file..."); return; end if; Person_Vector_Mapping.Set_Mapping (Mapping.Get_Person_Mapper); Mapper.Add_Mapping ("/list", Person_Vector_Mapping'Unchecked_Access); Mapper.Add_Mapping ("/person", Mapping.Get_Person_Mapper.all'Access); for I in 1 .. Count loop declare S : constant String := Ada.Command_Line.Argument (I); List : aliased Mapping.Person_Vector.Vector; P : aliased Mapping.Person; begin Person_Vector_Mapper.Set_Context (Mapper, List'Unchecked_Access); Mapping.Person_Mapper.Set_Context (Mapper, P'Unchecked_Access); Reader.Parse (S, Mapper); -- The list now contains our elements. List.Iterate (Process => Print'Access); if List.Length = 0 then Print (P); end if; declare Buffer : aliased Util.Streams.Buffered.Buffered_Stream; Print : aliased Util.Streams.Texts.Print_Stream; Output : Util.Serialize.IO.JSON.Output_Stream; begin Buffer.Initialize (Size => 10000); Print.Initialize (Buffer'Unchecked_Access); Output.Initialize (Print'Unchecked_Access); Mapping.Get_Person_Mapper.Write (Output, P); Ada.Text_IO.Put_Line ("Person: " & Util.Streams.Texts.To_String (Print)); end; declare Buffer : aliased Util.Streams.Buffered.Buffered_Stream; Print : aliased Util.Streams.Texts.Print_Stream; Output : Util.Serialize.IO.JSON.Output_Stream; begin Buffer.Initialize (Size => 10000); Print.Initialize (Buffer'Unchecked_Access); Output.Initialize (Print'Unchecked_Access); Output.Write ("{""list"":"); Person_Vector_Mapping.Write (Output, List); Output.Write ("}"); Ada.Text_IO.Put_Line ("IO:"); Ada.Text_IO.Put_Line (Util.Streams.Texts.To_String (Buffered_Stream (Print))); end; end; end loop; end Json;
----------------------------------------------------------------------- -- json -- JSON Reader -- Copyright (C) 2010, 2011, 2014, 2017 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Strings.Unbounded; with Ada.Text_IO; with Ada.Command_Line; with Util.Serialize.IO.JSON; with Ada.Containers; with Mapping; with Util.Serialize.Mappers.Vector_Mapper; with Util.Streams.Texts; with Util.Streams.Buffered; procedure Json is use Util.Streams.Buffered; use Ada.Strings.Unbounded; use type Mapping.Person_Access; use type Ada.Containers.Count_Type; use Mapping; Reader : Util.Serialize.IO.JSON.Parser; Mapper : Util.Serialize.Mappers.Processing; Count : constant Natural := Ada.Command_Line.Argument_Count; package Person_Vector_Mapper is new Util.Serialize.Mappers.Vector_Mapper (Vectors => Person_Vector, Element_Mapper => Person_Mapper); subtype Person_Vector_Context is Person_Vector_Mapper.Vector_Data; -- Mapping for a list of Person records (stored as a Vector). Person_Vector_Mapping : aliased Person_Vector_Mapper.Mapper; procedure Print (P : in Mapping.Person_Vector.Cursor); procedure Print (P : in Mapping.Person); procedure Print (P : in Mapping.Person) is begin Ada.Text_IO.Put_Line ("Name : " & To_String (P.Name)); Ada.Text_IO.Put_Line ("first_name : " & To_String (P.First_Name)); Ada.Text_IO.Put_Line ("last_name : " & To_String (P.Last_Name)); Ada.Text_IO.Put_Line ("Age : " & Natural'Image (P.Age)); Ada.Text_IO.Put_Line ("Street : " & To_String (P.Addr.Street)); Ada.Text_IO.Put_Line ("City : " & To_String (P.Addr.City)); Ada.Text_IO.Put_Line ("Zip : " & Natural'Image (P.Addr.Zip)); Ada.Text_IO.Put_Line ("Country : " & To_String (P.Addr.Country)); Ada.Text_IO.Put_Line ("Info : " & To_String (P.Addr.Info.Name) & "=" & To_String (P.Addr.Info.Value)); end Print; procedure Print (P : in Mapping.Person_Vector.Cursor) is begin Print (Mapping.Person_Vector.Element (P)); end Print; begin if Count = 0 then Ada.Text_IO.Put_Line ("Usage: json file..."); return; end if; Person_Vector_Mapping.Set_Mapping (Mapping.Get_Person_Mapper); Mapper.Add_Mapping ("/list", Person_Vector_Mapping'Unchecked_Access); Mapper.Add_Mapping ("/person", Mapping.Get_Person_Mapper.all'Access); for I in 1 .. Count loop declare S : constant String := Ada.Command_Line.Argument (I); List : aliased Mapping.Person_Vector.Vector; P : aliased Mapping.Person; begin Person_Vector_Mapper.Set_Context (Mapper, List'Unchecked_Access); Mapping.Person_Mapper.Set_Context (Mapper, P'Unchecked_Access); Reader.Parse (S, Mapper); -- The list now contains our elements. List.Iterate (Process => Print'Access); if List.Length = 0 then Print (P); end if; declare Buffer : aliased Util.Streams.Buffered.Output_Buffer_Stream; Print : aliased Util.Streams.Texts.Print_Stream; Output : Util.Serialize.IO.JSON.Output_Stream; begin Buffer.Initialize (Size => 10000); Print.Initialize (Buffer'Unchecked_Access); Output.Initialize (Print'Unchecked_Access); Mapping.Get_Person_Mapper.Write (Output, P); Ada.Text_IO.Put_Line ("Person: " & Util.Streams.Texts.To_String (Print)); end; declare Buffer : aliased Util.Streams.Buffered.Output_Buffer_Stream; Print : aliased Util.Streams.Texts.Print_Stream; Output : Util.Serialize.IO.JSON.Output_Stream; begin Buffer.Initialize (Size => 10000); Print.Initialize (Buffer'Unchecked_Access); Output.Initialize (Print'Unchecked_Access); Output.Write ("{""list"":"); Person_Vector_Mapping.Write (Output, List); Output.Write ("}"); Ada.Text_IO.Put_Line ("IO:"); Ada.Text_IO.Put_Line (Util.Streams.Texts.To_String (Print)); end; end; end loop; end Json;
Use the Output_Buffer_Stream
Use the Output_Buffer_Stream
Ada
apache-2.0
stcarrez/ada-util,stcarrez/ada-util
0dbe64f98ae92fda6ef9367d2239160e7c66ad35
src/util-beans-objects-readers.ads
src/util-beans-objects-readers.ads
----------------------------------------------------------------------- -- util-beans-objects-readers -- 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 Util.Beans.Objects.Maps; with Util.Beans.Objects.Vectors; with Util.Serialize.IO; with Util.Stacks; with Util.Log; package Util.Beans.Objects.Readers is type Reader is limited new Util.Serialize.IO.Reader with private; -- Start a document. overriding procedure Start_Document (Handler : in out Reader); -- 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); -- 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); overriding procedure Start_Array (Handler : in out Reader; Name : in String; Logger : in out Util.Log.Logging'Class); overriding procedure Finish_Array (Handler : in out Reader; Name : in String; Count : in Natural; Logger : in out Util.Log.Logging'Class); -- 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); private type Object_Context is record Map : Util.Beans.Objects.Maps.Map_Bean_Access; List : Util.Beans.Objects.Vectors.Vector_Bean_Access; end record; type Object_Context_Access is access all Object_Context; package Object_Stack is new Util.Stacks (Element_Type => Object_Context, Element_Type_Access => Object_Context_Access); type Reader is limited new Util.Serialize.IO.Reader with record Context : Object_Stack.Stack; end record; end Util.Beans.Objects.Readers;
----------------------------------------------------------------------- -- util-beans-objects-readers -- 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 Util.Beans.Objects.Maps; with Util.Beans.Objects.Vectors; with Util.Serialize.IO; with Util.Stacks; with Util.Log; package Util.Beans.Objects.Readers is type Reader is limited new Util.Serialize.IO.Reader with private; -- Start a document. overriding procedure Start_Document (Handler : in out Reader); -- 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); -- 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); overriding procedure Start_Array (Handler : in out Reader; Name : in String; Logger : in out Util.Log.Logging'Class); overriding procedure Finish_Array (Handler : in out Reader; Name : in String; Count : in Natural; Logger : in out Util.Log.Logging'Class); -- 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); -- Get the root object. function Get_Root (Handler : in Reader) return Object; private type Object_Context is record Map : Util.Beans.Objects.Maps.Map_Bean_Access; List : Util.Beans.Objects.Vectors.Vector_Bean_Access; end record; type Object_Context_Access is access all Object_Context; package Object_Stack is new Util.Stacks (Element_Type => Object_Context, Element_Type_Access => Object_Context_Access); type Reader is limited new Util.Serialize.IO.Reader with record Context : Object_Stack.Stack; Root : Util.Beans.Objects.Object; end record; end Util.Beans.Objects.Readers;
Declare the Get_Root function and add a Root member to the Reader type
Declare the Get_Root function and add a Root member to the Reader type
Ada
apache-2.0
stcarrez/ada-util,stcarrez/ada-util
f199837025563f9eec951269b5de8d3d9da7da96
mat/src/events/mat-events.ads
mat/src/events/mat-events.ads
----------------------------------------------------------------------- -- gprofiler-events - Profiler Events Description -- 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 Interfaces; with Ada.Strings.Unbounded; with MAT.Types; with Util.Strings; package MAT.Events is use Interfaces; type Attribute_Type is (T_UINT8, T_UINT16, T_UINT32, T_UINT64, T_POINTER, T_PROBE, T_FRAME, T_THREAD, T_TIME, T_SIZE_T); type Event_Type is (EVENT_BEGIN, EVENT_END, EVENT_MALLOC, EVENT_FREE, EVENT_REALLOC); subtype Internal_Reference is Natural; type Attribute is record Name : Util.Strings.Name_Access; Size : Natural := 0; Kind : Attribute_Type := T_UINT8; Ref : Internal_Reference := 0; end record; -- Logical description of an event attribute. type Attribute_Table is array (Natural range <>) of Attribute; type Attribute_Table_Ptr is access all Attribute_Table; type Const_Attribute_Table_Access is access constant Attribute_Table; type Event_Description (Nb_Attributes : Natural) is record Name : Ada.Strings.Unbounded.Unbounded_String; Id : Unsigned_32; Kind : Event_Type; Def : Attribute_Table (1 .. Nb_Attributes); end record; type Event_Description_Access is access all Event_Description; subtype Addr is MAT.Types.Uint32; type Frame_Table is array (Natural range <>) of Addr; type Rusage_Info is record Minflt : Unsigned_32; Majflt : Unsigned_32; Nswap : Unsigned_32; end record; type Frame_Info (Depth : Natural) is record Time : MAT.Types.Target_Time; Thread : MAT.Types.Target_Thread_Ref; Stack : MAT.Types.Target_Addr; Rusage : Rusage_Info; Cur_Depth : Natural; Frame : Frame_Table (1 .. Depth); end record; type Event_Data is record Kind : Attribute_Type; U8 : MAT.Types.Uint8; U16 : MAT.Types.Uint16; U32 : MAT.Types.Uint32; U64 : MAT.Types.Uint64; Probe : Frame_Info (Depth => 10); end record; type Event_Data_Table is array (Natural range <>) of Event_Data; procedure Dump (Table : in Event_Data_Table; Def : in Event_Description); end MAT.Events;
----------------------------------------------------------------------- -- gprofiler-events - Profiler Events Description -- 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 Interfaces; with Ada.Strings.Unbounded; with MAT.Types; with Util.Strings; package MAT.Events is use Interfaces; type Attribute_Type is (T_UINT8, T_UINT16, T_UINT32, T_UINT64, T_POINTER, T_PROBE, T_FRAME, T_THREAD, T_TIME, T_SIZE_T); type Event_Type is (EVENT_BEGIN, EVENT_END, EVENT_MALLOC, EVENT_FREE, EVENT_REALLOC); subtype Internal_Reference is Natural; type Attribute is record Name : Util.Strings.Name_Access; Size : Natural := 0; Kind : Attribute_Type := T_UINT8; Ref : Internal_Reference := 0; end record; -- Logical description of an event attribute. type Attribute_Table is array (Natural range <>) of Attribute; type Attribute_Table_Ptr is access all Attribute_Table; type Const_Attribute_Table_Access is access constant Attribute_Table; type Event_Description (Nb_Attributes : Natural) is record Name : Ada.Strings.Unbounded.Unbounded_String; Id : Unsigned_32; Kind : Event_Type; Def : Attribute_Table (1 .. Nb_Attributes); end record; type Event_Description_Access is access all Event_Description; -- subtype Addr is MAT.Types.Uint32; type Frame_Table is array (Natural range <>) of MAT.Types.Target_Addr; type Rusage_Info is record Minflt : Unsigned_32; Majflt : Unsigned_32; Nswap : Unsigned_32; end record; type Frame_Info (Depth : Natural) is record Time : MAT.Types.Target_Time; Thread : MAT.Types.Target_Thread_Ref; Stack : MAT.Types.Target_Addr; Rusage : Rusage_Info; Cur_Depth : Natural; Frame : Frame_Table (1 .. Depth); end record; type Event_Data is record Kind : Attribute_Type; U8 : MAT.Types.Uint8; U16 : MAT.Types.Uint16; U32 : MAT.Types.Uint32; U64 : MAT.Types.Uint64; Probe : Frame_Info (Depth => 10); end record; type Event_Data_Table is array (Natural range <>) of Event_Data; procedure Dump (Table : in Event_Data_Table; Def : in Event_Description); end MAT.Events;
Use MAT.Types.Target_Addr for the frame address
Use MAT.Types.Target_Addr for the frame address
Ada
apache-2.0
stcarrez/mat,stcarrez/mat,stcarrez/mat
f8862ecd8c066c2cb56e86d9fda243b089759c95
mat/src/mat-consoles-text.adb
mat/src/mat-consoles-text.adb
----------------------------------------------------------------------- -- mat-consoles-text - Text 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. ----------------------------------------------------------------------- package body MAT.Consoles.Text is -- ------------------------------ -- Report an error message. -- ------------------------------ overriding procedure Error (Console : in out Console_Type; Message : in String) is pragma Unreferenced (Console); begin Ada.Text_IO.Put_Line (Message); end Error; -- ------------------------------ -- Report a notice message. -- ------------------------------ overriding procedure Notice (Console : in out Console_Type; Kind : in Notice_Type; Message : in String) is pragma Unreferenced (Console, Kind); begin Ada.Text_IO.Put_Line (Message); end Notice; -- ------------------------------ -- Print the field value for the given field. -- ------------------------------ overriding procedure Print_Field (Console : in out Console_Type; Field : in Field_Type; Value : in String) is use type Ada.Text_IO.Count; Pos : Ada.Text_IO.Count := Ada.Text_IO.Count (Console.Cols (Field)); begin if Pos > 1 then Pos := Pos + Ada.Text_IO.Count (Console.Sizes (Field)); if Pos > Value'Length then Ada.Text_IO.Set_Col (Pos - Value'Length); else Ada.Text_IO.Set_Col (Ada.Text_IO.Count (Console.Cols (Field))); Ada.Text_IO.Put (Value (Value'Last - Console.Sizes (Field) .. Value'Last)); return; end if; end if; Ada.Text_IO.Put (Value); end Print_Field; -- ------------------------------ -- Print the title for the given field. -- ------------------------------ overriding procedure Print_Title (Console : in out Console_Type; Field : in Field_Type; Title : in String) is use type Ada.Text_IO.Count; Pos : constant Ada.Text_IO.Count := Ada.Text_IO.Count (Console.Cols (Field)); begin if Pos > 1 then Ada.Text_IO.Set_Col (Pos + Ada.Text_IO.Count (Console.Sizes (Field)) - Title'Length); end if; Ada.Text_IO.Put (Title); end Print_Title; -- ------------------------------ -- Start a new title in a report. -- ------------------------------ overriding procedure Start_Title (Console : in out Console_Type) is begin Console.Field_Count := 0; Console.Sizes := (others => 0); Console.Cols := (others => 1); end Start_Title; -- ------------------------------ -- Finish a new title in a report. -- ------------------------------ procedure End_Title (Console : in out Console_Type) is pragma Unreferenced (Console); begin Ada.Text_IO.New_Line; end End_Title; -- ------------------------------ -- Start a new row in a report. -- ------------------------------ overriding procedure Start_Row (Console : in out Console_Type) is pragma Unreferenced (Console); begin null; end Start_Row; -- ------------------------------ -- Finish a new row in a report. -- ------------------------------ overriding procedure End_Row (Console : in out Console_Type) is pragma Unreferenced (Console); begin Ada.Text_IO.New_Line; end End_Row; end MAT.Consoles.Text;
----------------------------------------------------------------------- -- mat-consoles-text - Text 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. ----------------------------------------------------------------------- package body MAT.Consoles.Text is -- ------------------------------ -- Report an error message. -- ------------------------------ overriding procedure Error (Console : in out Console_Type; Message : in String) is pragma Unreferenced (Console); begin Ada.Text_IO.Put_Line (Message); end Error; -- ------------------------------ -- Report a notice message. -- ------------------------------ overriding procedure Notice (Console : in out Console_Type; Kind : in Notice_Type; Message : in String) is pragma Unreferenced (Console, Kind); begin Ada.Text_IO.Put_Line (Message); end Notice; -- ------------------------------ -- Print the field value for the given field. -- ------------------------------ overriding procedure Print_Field (Console : in out Console_Type; Field : in Field_Type; Value : in String; Justify : in Justify_Type := J_LEFT) is use type Ada.Text_IO.Count; Pos : Ada.Text_IO.Count := Ada.Text_IO.Count (Console.Cols (Field)); Size : constant Natural := Console.Sizes (Field); Start : Natural := Value'First; Last : Natural := Value'Last; Pad : Natural := 0; Fill : Natural := 0; begin case Justify is when J_LEFT => if Value'Length < Size then Pad := Size - Value'Length; else Start := Last - Size + 1; end if; when J_RIGHT => if Value'Length < Size then Fill := Size - Value'Length; else Start := Last - Size + 1; end if; when J_CENTER => if Value'Length < Size then Pad := (Size - Value'Length) / 2; Fill := Size - Value'Length - Pad; else Start := Last - Size + 1; end if; when J_RIGHT_NO_FILL => if Value'Length >= Size then Start := Last - Size + 1; end if; end case; if Pad > 0 then Ada.Text_IO.Set_Col (Pos + Ada.Text_IO.Count (Pad)); end if; Ada.Text_IO.Put (Value (Start .. Last)); if Fill > 0 then Ada.Text_IO.Set_Col (Pos + Ada.Text_IO.Count (Pad + Fill + Last - Start)); end if; end Print_Field; -- ------------------------------ -- Print the title for the given field. -- ------------------------------ overriding procedure Print_Title (Console : in out Console_Type; Field : in Field_Type; Title : in String) is use type Ada.Text_IO.Count; Pos : constant Ada.Text_IO.Count := Ada.Text_IO.Count (Console.Cols (Field)); begin if Pos > 1 then Ada.Text_IO.Set_Col (Pos + Ada.Text_IO.Count (Console.Sizes (Field)) - Title'Length); end if; Ada.Text_IO.Put (Title); end Print_Title; -- ------------------------------ -- Start a new title in a report. -- ------------------------------ overriding procedure Start_Title (Console : in out Console_Type) is begin Console.Field_Count := 0; Console.Sizes := (others => 0); Console.Cols := (others => 1); end Start_Title; -- ------------------------------ -- Finish a new title in a report. -- ------------------------------ procedure End_Title (Console : in out Console_Type) is pragma Unreferenced (Console); begin Ada.Text_IO.New_Line; end End_Title; -- ------------------------------ -- Start a new row in a report. -- ------------------------------ overriding procedure Start_Row (Console : in out Console_Type) is pragma Unreferenced (Console); begin null; end Start_Row; -- ------------------------------ -- Finish a new row in a report. -- ------------------------------ overriding procedure End_Row (Console : in out Console_Type) is pragma Unreferenced (Console); begin Ada.Text_IO.New_Line; end End_Row; end MAT.Consoles.Text;
Use the Justify parameter to format the column
Use the Justify parameter to format the column
Ada
apache-2.0
stcarrez/mat,stcarrez/mat,stcarrez/mat
5224bf832948cc03ab006ffd237ff57c88e23699
src/el-contexts.ads
src/el-contexts.ads
----------------------------------------------------------------------- -- EL.Contexts -- Contexts for evaluating an expression -- Copyright (C) 2009, 2010, 2011, 2012, 2018 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- -- The expression context provides information to resolve runtime -- information when evaluating an expression. The context provides -- a resolver whose role is to find variables given their name. with EL.Objects; with Util.Beans.Basic; with Ada.Strings.Unbounded; with Ada.Exceptions; with EL.Functions; limited with EL.Variables; package EL.Contexts is pragma Preelaborate; use Ada.Strings.Unbounded; type ELContext; -- ------------------------------ -- Expression Resolver -- ------------------------------ -- Enables customization of variable and property resolution -- behavior for EL expression evaluation. type ELResolver is limited interface; type ELResolver_Access is access all ELResolver'Class; -- Get the value associated with a base object and a given property. function Get_Value (Resolver : ELResolver; Context : ELContext'Class; Base : access Util.Beans.Basic.Readonly_Bean'Class; Name : Unbounded_String) return EL.Objects.Object is abstract; -- Set the value associated with a base object and a given property. procedure Set_Value (Resolver : in out ELResolver; Context : in ELContext'Class; Base : access Util.Beans.Basic.Bean'Class; Name : in Unbounded_String; Value : in EL.Objects.Object) is abstract; -- ------------------------------ -- Expression Context -- ------------------------------ -- Context information for expression evaluation. type ELContext is limited interface; type ELContext_Access is access all ELContext'Class; -- Retrieves the ELResolver associated with this ELcontext. function Get_Resolver (Context : ELContext) return ELResolver_Access is abstract; -- Retrieves the VariableMapper associated with this ELContext. function Get_Variable_Mapper (Context : ELContext) return access EL.Variables.Variable_Mapper'Class is abstract; -- Set the variable mapper associated with this ELContext. procedure Set_Variable_Mapper (Context : in out ELContext; Mapper : access EL.Variables.Variable_Mapper'Class) is abstract; -- Retrieves the FunctionMapper associated with this ELContext. -- The FunctionMapper is only used when parsing an expression. function Get_Function_Mapper (Context : ELContext) return EL.Functions.Function_Mapper_Access is abstract; -- Set the function mapper associated with this ELContext. procedure Set_Function_Mapper (Context : in out ELContext; Mapper : access EL.Functions.Function_Mapper'Class) is abstract; -- Handle the exception during expression evaluation. The handler can ignore the -- exception or raise it. procedure Handle_Exception (Context : in ELContext; Ex : in Ada.Exceptions.Exception_Occurrence) is abstract; end EL.Contexts;
----------------------------------------------------------------------- -- EL.Contexts -- Contexts for evaluating an expression -- Copyright (C) 2009, 2010, 2011, 2012, 2018, 2021 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- -- The expression context provides information to resolve runtime -- information when evaluating an expression. The context provides -- a resolver whose role is to find variables given their name. with EL.Objects; with Util.Beans.Basic; with Ada.Strings.Unbounded; with Ada.Exceptions; with EL.Functions; limited with EL.Variables; package EL.Contexts is pragma Preelaborate; use Ada.Strings.Unbounded; type ELContext is limited interface; -- ------------------------------ -- Expression Resolver -- ------------------------------ -- Enables customization of variable and property resolution -- behavior for EL expression evaluation. type ELResolver is limited interface; type ELResolver_Access is access all ELResolver'Class; -- Get the value associated with a base object and a given property. function Get_Value (Resolver : ELResolver; Context : ELContext'Class; Base : access Util.Beans.Basic.Readonly_Bean'Class; Name : Unbounded_String) return EL.Objects.Object is abstract; -- Set the value associated with a base object and a given property. procedure Set_Value (Resolver : in out ELResolver; Context : in ELContext'Class; Base : access Util.Beans.Basic.Bean'Class; Name : in Unbounded_String; Value : in EL.Objects.Object) is abstract; -- ------------------------------ -- Expression Context -- ------------------------------ -- Context information for expression evaluation. type ELContext_Access is access all ELContext'Class; -- Retrieves the ELResolver associated with this ELcontext. function Get_Resolver (Context : ELContext) return ELResolver_Access is abstract; -- Retrieves the VariableMapper associated with this ELContext. function Get_Variable_Mapper (Context : ELContext) return access EL.Variables.Variable_Mapper'Class is abstract; -- Set the variable mapper associated with this ELContext. procedure Set_Variable_Mapper (Context : in out ELContext; Mapper : access EL.Variables.Variable_Mapper'Class) is abstract; -- Retrieves the FunctionMapper associated with this ELContext. -- The FunctionMapper is only used when parsing an expression. function Get_Function_Mapper (Context : ELContext) return EL.Functions.Function_Mapper_Access is abstract; -- Set the function mapper associated with this ELContext. procedure Set_Function_Mapper (Context : in out ELContext; Mapper : access EL.Functions.Function_Mapper'Class) is abstract; -- Handle the exception during expression evaluation. The handler can ignore the -- exception or raise it. procedure Handle_Exception (Context : in ELContext; Ex : in Ada.Exceptions.Exception_Occurrence) is abstract; end EL.Contexts;
Fix compilation warning with GNAT 2021
Fix compilation warning with GNAT 2021
Ada
apache-2.0
stcarrez/ada-el
d47fb57071d39448b5072f9f2b97d8b83c2871c2
hal/src/hal-i2c.ads
hal/src/hal-i2c.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 the copyright holder nor the names of its -- -- contributors may be used to endorse or promote products derived -- -- from this software without specific prior written permission. -- -- -- -- THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -- -- "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -- -- LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -- -- A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -- -- HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -- -- SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -- -- LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -- -- DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -- -- THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -- -- (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -- -- OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -- -- -- ------------------------------------------------------------------------------ package HAL.I2C is type I2C_Status is (Ok, Err_Error, Err_Timeout, Busy); type I2C_Data is array (Natural range <>) of Byte; type I2C_Memory_Address_Size is (Memory_Size_8b, Memory_Size_16b); subtype I2C_Address is UInt10; type I2C_Port is limited interface; type Any_I2C_Port is access all I2C_Port'Class; procedure Master_Transmit (This : in out I2C_Port; Addr : I2C_Address; Data : I2C_Data; Status : out I2C_Status; Timeout : Natural := 1000) is abstract; procedure Master_Receive (This : in out I2C_Port; Addr : I2C_Address; Data : out I2C_Data; Status : out I2C_Status; Timeout : Natural := 1000) is abstract; procedure Mem_Write (This : in out I2C_Port; Addr : I2C_Address; Mem_Addr : UInt16; Mem_Addr_Size : I2C_Memory_Address_Size; Data : I2C_Data; Status : out I2C_Status; Timeout : Natural := 1000) is abstract; procedure Mem_Read (This : in out I2C_Port; Addr : I2C_Address; Mem_Addr : UInt16; Mem_Addr_Size : I2C_Memory_Address_Size; Data : out I2C_Data; Status : out I2C_Status; Timeout : Natural := 1000) is abstract; end HAL.I2C;
------------------------------------------------------------------------------ -- -- -- 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 the copyright holder nor the names of its -- -- contributors may be used to endorse or promote products derived -- -- from this software without specific prior written permission. -- -- -- -- THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -- -- "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -- -- LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -- -- A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -- -- HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -- -- SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -- -- LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -- -- DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -- -- THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -- -- (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -- -- OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -- -- -- ------------------------------------------------------------------------------ package HAL.I2C is type I2C_Status is (Ok, Err_Error, Err_Timeout, Busy); subtype I2C_Data is Byte_Array; type I2C_Memory_Address_Size is (Memory_Size_8b, Memory_Size_16b); subtype I2C_Address is UInt10; type I2C_Port is limited interface; type Any_I2C_Port is access all I2C_Port'Class; procedure Master_Transmit (This : in out I2C_Port; Addr : I2C_Address; Data : I2C_Data; Status : out I2C_Status; Timeout : Natural := 1000) is abstract; procedure Master_Receive (This : in out I2C_Port; Addr : I2C_Address; Data : out I2C_Data; Status : out I2C_Status; Timeout : Natural := 1000) is abstract; procedure Mem_Write (This : in out I2C_Port; Addr : I2C_Address; Mem_Addr : UInt16; Mem_Addr_Size : I2C_Memory_Address_Size; Data : I2C_Data; Status : out I2C_Status; Timeout : Natural := 1000) is abstract; procedure Mem_Read (This : in out I2C_Port; Addr : I2C_Address; Mem_Addr : UInt16; Mem_Addr_Size : I2C_Memory_Address_Size; Data : out I2C_Data; Status : out I2C_Status; Timeout : Natural := 1000) is abstract; end HAL.I2C;
Make the HAL.I2C.I2C_Data a subtype of Byte_Array.
Make the HAL.I2C.I2C_Data a subtype of Byte_Array. This makes the API more consistent with the rest of the HAL.
Ada
bsd-3-clause
Fabien-Chouteau/Ada_Drivers_Library,simonjwright/Ada_Drivers_Library,ellamosi/Ada_BMP_Library,simonjwright/Ada_Drivers_Library,AdaCore/Ada_Drivers_Library,AdaCore/Ada_Drivers_Library,Fabien-Chouteau/Ada_Drivers_Library
a9c1b6cc011802f0173659c0a473828b169ad87d
src/asf-views-nodes-facelets.ads
src/asf-views-nodes-facelets.ads
----------------------------------------------------------------------- -- nodes-facelets -- Facelets composition nodes -- 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. ----------------------------------------------------------------------- -- The <b>ASF.Views.Nodes.Facelets</b> package defines some pre-defined -- tags for composing a view. -- -- xmlns:ui="http://java.sun.com/jsf/facelets" -- -- The following Facelets core elements are defined: -- <ui:include src="..."/> -- <ui:decorate view="..."/> -- <ui:define name="..."/> -- <ui:insert name="..."/> -- <ui:param name="..." value="..."/> -- <ui:composition .../> -- with Ada.Strings.Hash; with ASF.Factory; with Ada.Containers.Indefinite_Hashed_Maps; package ASF.Views.Nodes.Facelets is -- Tag factory for nodes defined in this package. function Definition return ASF.Factory.Factory_Bindings_Access; -- ------------------------------ -- Include Tag -- ------------------------------ -- The <ui:include src="..."/> type Include_Tag_Node is new Tag_Node with private; type Include_Tag_Node_Access is access all Include_Tag_Node'Class; -- Create the Include Tag function Create_Include_Tag_Node (Binding : in Binding_Access; Line : in Line_Info; Parent : in Tag_Node_Access; Attributes : in Tag_Attribute_Array_Access) return Tag_Node_Access; -- Build the component tree from the tag node and attach it as -- the last child of the given parent. Calls recursively the -- method to create children. overriding procedure Build_Components (Node : access Include_Tag_Node; Parent : in UIComponent_Access; Context : in out Facelet_Context'Class); -- ------------------------------ -- Composition Tag -- ------------------------------ -- The <ui:composition template="..."/> type Composition_Tag_Node is new Tag_Node with private; type Composition_Tag_Node_Access is access all Composition_Tag_Node'Class; -- Create the Composition Tag function Create_Composition_Tag_Node (Binding : in Binding_Access; Line : in Line_Info; Parent : in Tag_Node_Access; Attributes : in Tag_Attribute_Array_Access) return Tag_Node_Access; -- Build the component tree from the tag node and attach it as -- the last child of the given parent. Calls recursively the -- method to create children. overriding procedure Build_Components (Node : access Composition_Tag_Node; Parent : in UIComponent_Access; Context : in out Facelet_Context'Class); -- Freeze the tag node tree and perform any initialization steps -- necessary to build the components efficiently. After this call -- the tag node tree should not be modified and it represents a read-only -- tree. overriding procedure Freeze (Node : access Composition_Tag_Node); -- Include in the component tree the definition identified by the name. -- Upon completion, return in <b>Found</b> whether the definition was found -- within this composition context. procedure Include_Definition (Node : access Composition_Tag_Node; Parent : in UIComponent_Access; Context : in out Facelet_Context'Class; Name : in Unbounded_String; Found : out Boolean); -- ------------------------------ -- Debug Tag -- ------------------------------ -- The <ui:debug/> type Debug_Tag_Node is new Tag_Node with private; type Debug_Tag_Node_Access is access all Debug_Tag_Node'Class; -- Create the Debug Tag function Create_Debug_Tag_Node (Binding : in Binding_Access; Line : in Line_Info; Parent : in Tag_Node_Access; Attributes : in Tag_Attribute_Array_Access) return Tag_Node_Access; -- Build the component tree from the tag node and attach it as -- the last child of the given parent. Calls recursively the -- method to create children. overriding procedure Build_Components (Node : access Debug_Tag_Node; Parent : in UIComponent_Access; Context : in out Facelet_Context'Class); -- ------------------------------ -- Decorate Tag -- ------------------------------ -- The <ui:decorate template="...">...</ui:decorate> type Decorate_Tag_Node is new Composition_Tag_Node with private; type Decorate_Tag_Node_Access is access all Decorate_Tag_Node'Class; -- Create the Decorate Tag function Create_Decorate_Tag_Node (Binding : in Binding_Access; Line : in Line_Info; Parent : in Tag_Node_Access; Attributes : in Tag_Attribute_Array_Access) return Tag_Node_Access; -- ------------------------------ -- Define Tag -- ------------------------------ -- The <ui:define name="...">...</ui:define> type Define_Tag_Node is new Tag_Node with private; type Define_Tag_Node_Access is access all Define_Tag_Node'Class; -- Create the Define Tag function Create_Define_Tag_Node (Binding : in Binding_Access; Line : in Line_Info; Parent : in Tag_Node_Access; Attributes : in Tag_Attribute_Array_Access) return Tag_Node_Access; -- Build the component tree from the tag node and attach it as -- the last child of the given parent. Calls recursively the -- method to create children. overriding procedure Build_Components (Node : access Define_Tag_Node; Parent : in UIComponent_Access; Context : in out Facelet_Context'Class); -- ------------------------------ -- Insert Tag -- ------------------------------ -- The <ui:insert name="...">...</ui:insert> type Insert_Tag_Node is new Tag_Node with private; type Insert_Tag_Node_Access is access all Insert_Tag_Node'Class; -- Create the Insert Tag function Create_Insert_Tag_Node (Binding : in Binding_Access; Line : in Line_Info; Parent : in Tag_Node_Access; Attributes : in Tag_Attribute_Array_Access) return Tag_Node_Access; -- Build the component tree from the tag node and attach it as -- the last child of the given parent. Calls recursively the -- method to create children. overriding procedure Build_Components (Node : access Insert_Tag_Node; Parent : in UIComponent_Access; Context : in out Facelet_Context'Class); -- ------------------------------ -- Param Tag -- ------------------------------ -- The <ui:param name="name" value="#{expr}"/> parameter creation. -- The parameter is created in the faces context. type Param_Tag_Node is new Tag_Node with private; type Param_Tag_Node_Access is access all Param_Tag_Node'Class; -- Create the Param Tag function Create_Param_Tag_Node (Binding : in Binding_Access; Line : in Line_Info; Parent : in Tag_Node_Access; Attributes : in Tag_Attribute_Array_Access) return Tag_Node_Access; -- Build the component tree from the tag node and attach it as -- the last child of the given parent. Calls recursively the -- method to create children. overriding procedure Build_Components (Node : access Param_Tag_Node; Parent : in UIComponent_Access; Context : in out Facelet_Context'Class); -- ------------------------------ -- Comment Tag -- ------------------------------ -- The <ui:comment condition="...">...</ui:comment> type Comment_Tag_Node is new Tag_Node with private; type Comment_Tag_Node_Access is access all Comment_Tag_Node'Class; -- Create the Comment Tag function Create_Comment_Tag_Node (Binding : in Binding_Access; Line : in Line_Info; Parent : in Tag_Node_Access; Attributes : in Tag_Attribute_Array_Access) return Tag_Node_Access; -- Build the component tree from the tag node and attach it as -- the last child of the given parent. Calls recursively the -- method to create children. overriding procedure Build_Components (Node : access Comment_Tag_Node; Parent : in UIComponent_Access; Context : in out Facelet_Context'Class); private -- Tag library map indexed on the library namespace. package Define_Maps is new Ada.Containers.Indefinite_Hashed_Maps (Key_Type => String, Element_Type => Define_Tag_Node_Access, Hash => Ada.Strings.Hash, Equivalent_Keys => "="); type Include_Tag_Node is new Tag_Node with record Source : Tag_Attribute_Access; end record; type Composition_Tag_Node is new Tag_Node with record Template : Tag_Attribute_Access; Defines : Define_Maps.Map; end record; type Debug_Tag_Node is new Tag_Node with record Source : Tag_Attribute_Access; end record; type Decorate_Tag_Node is new Composition_Tag_Node with null record; type Define_Tag_Node is new Tag_Node with record Define_Name : Unbounded_String; end record; type Insert_Tag_Node is new Tag_Node with record Insert_Name : Tag_Attribute_Access; end record; type Param_Tag_Node is new Tag_Node with record Var : Tag_Attribute_Access; Value : Tag_Attribute_Access; end record; type Comment_Tag_Node is new Tag_Node with record Condition : Tag_Attribute_Access; end record; end ASF.Views.Nodes.Facelets;
----------------------------------------------------------------------- -- nodes-facelets -- Facelets composition nodes -- Copyright (C) 2009, 2010, 2011, 2012, 2013, 2018 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- -- The <b>ASF.Views.Nodes.Facelets</b> package defines some pre-defined -- tags for composing a view. -- -- xmlns:ui="http://java.sun.com/jsf/facelets" -- -- The following Facelets core elements are defined: -- <ui:include src="..."/> -- <ui:decorate view="..."/> -- <ui:define name="..."/> -- <ui:insert name="..."/> -- <ui:param name="..." value="..."/> -- <ui:composition .../> -- with Ada.Strings.Hash; with ASF.Factory; with Ada.Containers.Indefinite_Hashed_Maps; package ASF.Views.Nodes.Facelets is -- Register the facelets component factory. procedure Register (Factory : in out ASF.Factory.Component_Factory); -- ------------------------------ -- Include Tag -- ------------------------------ -- The <ui:include src="..."/> type Include_Tag_Node is new Tag_Node with private; type Include_Tag_Node_Access is access all Include_Tag_Node'Class; -- Create the Include Tag function Create_Include_Tag_Node (Binding : in Binding_Type; Line : in Line_Info; Parent : in Tag_Node_Access; Attributes : in Tag_Attribute_Array_Access) return Tag_Node_Access; -- Build the component tree from the tag node and attach it as -- the last child of the given parent. Calls recursively the -- method to create children. overriding procedure Build_Components (Node : access Include_Tag_Node; Parent : in UIComponent_Access; Context : in out Facelet_Context'Class); -- ------------------------------ -- Composition Tag -- ------------------------------ -- The <ui:composition template="..."/> type Composition_Tag_Node is new Tag_Node with private; type Composition_Tag_Node_Access is access all Composition_Tag_Node'Class; -- Create the Composition Tag function Create_Composition_Tag_Node (Binding : in Binding_Type; Line : in Line_Info; Parent : in Tag_Node_Access; Attributes : in Tag_Attribute_Array_Access) return Tag_Node_Access; -- Build the component tree from the tag node and attach it as -- the last child of the given parent. Calls recursively the -- method to create children. overriding procedure Build_Components (Node : access Composition_Tag_Node; Parent : in UIComponent_Access; Context : in out Facelet_Context'Class); -- Freeze the tag node tree and perform any initialization steps -- necessary to build the components efficiently. After this call -- the tag node tree should not be modified and it represents a read-only -- tree. overriding procedure Freeze (Node : access Composition_Tag_Node); -- Include in the component tree the definition identified by the name. -- Upon completion, return in <b>Found</b> whether the definition was found -- within this composition context. procedure Include_Definition (Node : access Composition_Tag_Node; Parent : in UIComponent_Access; Context : in out Facelet_Context'Class; Name : in Unbounded_String; Found : out Boolean); -- ------------------------------ -- Debug Tag -- ------------------------------ -- The <ui:debug/> type Debug_Tag_Node is new Tag_Node with private; type Debug_Tag_Node_Access is access all Debug_Tag_Node'Class; -- Create the Debug Tag function Create_Debug_Tag_Node (Binding : in Binding_Type; Line : in Line_Info; Parent : in Tag_Node_Access; Attributes : in Tag_Attribute_Array_Access) return Tag_Node_Access; -- Build the component tree from the tag node and attach it as -- the last child of the given parent. Calls recursively the -- method to create children. overriding procedure Build_Components (Node : access Debug_Tag_Node; Parent : in UIComponent_Access; Context : in out Facelet_Context'Class); -- ------------------------------ -- Decorate Tag -- ------------------------------ -- The <ui:decorate template="...">...</ui:decorate> type Decorate_Tag_Node is new Composition_Tag_Node with private; type Decorate_Tag_Node_Access is access all Decorate_Tag_Node'Class; -- Create the Decorate Tag function Create_Decorate_Tag_Node (Binding : in Binding_Type; Line : in Line_Info; Parent : in Tag_Node_Access; Attributes : in Tag_Attribute_Array_Access) return Tag_Node_Access; -- ------------------------------ -- Define Tag -- ------------------------------ -- The <ui:define name="...">...</ui:define> type Define_Tag_Node is new Tag_Node with private; type Define_Tag_Node_Access is access all Define_Tag_Node'Class; -- Create the Define Tag function Create_Define_Tag_Node (Binding : in Binding_Type; Line : in Line_Info; Parent : in Tag_Node_Access; Attributes : in Tag_Attribute_Array_Access) return Tag_Node_Access; -- Build the component tree from the tag node and attach it as -- the last child of the given parent. Calls recursively the -- method to create children. overriding procedure Build_Components (Node : access Define_Tag_Node; Parent : in UIComponent_Access; Context : in out Facelet_Context'Class); -- ------------------------------ -- Insert Tag -- ------------------------------ -- The <ui:insert name="...">...</ui:insert> type Insert_Tag_Node is new Tag_Node with private; type Insert_Tag_Node_Access is access all Insert_Tag_Node'Class; -- Create the Insert Tag function Create_Insert_Tag_Node (Binding : in Binding_Type; Line : in Line_Info; Parent : in Tag_Node_Access; Attributes : in Tag_Attribute_Array_Access) return Tag_Node_Access; -- Build the component tree from the tag node and attach it as -- the last child of the given parent. Calls recursively the -- method to create children. overriding procedure Build_Components (Node : access Insert_Tag_Node; Parent : in UIComponent_Access; Context : in out Facelet_Context'Class); -- ------------------------------ -- Param Tag -- ------------------------------ -- The <ui:param name="name" value="#{expr}"/> parameter creation. -- The parameter is created in the faces context. type Param_Tag_Node is new Tag_Node with private; type Param_Tag_Node_Access is access all Param_Tag_Node'Class; -- Create the Param Tag function Create_Param_Tag_Node (Binding : in Binding_Type; Line : in Line_Info; Parent : in Tag_Node_Access; Attributes : in Tag_Attribute_Array_Access) return Tag_Node_Access; -- Build the component tree from the tag node and attach it as -- the last child of the given parent. Calls recursively the -- method to create children. overriding procedure Build_Components (Node : access Param_Tag_Node; Parent : in UIComponent_Access; Context : in out Facelet_Context'Class); -- ------------------------------ -- Comment Tag -- ------------------------------ -- The <ui:comment condition="...">...</ui:comment> type Comment_Tag_Node is new Tag_Node with private; type Comment_Tag_Node_Access is access all Comment_Tag_Node'Class; -- Create the Comment Tag function Create_Comment_Tag_Node (Binding : in Binding_Type; Line : in Line_Info; Parent : in Tag_Node_Access; Attributes : in Tag_Attribute_Array_Access) return Tag_Node_Access; -- Build the component tree from the tag node and attach it as -- the last child of the given parent. Calls recursively the -- method to create children. overriding procedure Build_Components (Node : access Comment_Tag_Node; Parent : in UIComponent_Access; Context : in out Facelet_Context'Class); private -- Tag library map indexed on the library namespace. package Define_Maps is new Ada.Containers.Indefinite_Hashed_Maps (Key_Type => String, Element_Type => Define_Tag_Node_Access, Hash => Ada.Strings.Hash, Equivalent_Keys => "="); type Include_Tag_Node is new Tag_Node with record Source : Tag_Attribute_Access; end record; type Composition_Tag_Node is new Tag_Node with record Template : Tag_Attribute_Access; Defines : Define_Maps.Map; end record; type Debug_Tag_Node is new Tag_Node with record Source : Tag_Attribute_Access; end record; type Decorate_Tag_Node is new Composition_Tag_Node with null record; type Define_Tag_Node is new Tag_Node with record Define_Name : Unbounded_String; end record; type Insert_Tag_Node is new Tag_Node with record Insert_Name : Tag_Attribute_Access; end record; type Param_Tag_Node is new Tag_Node with record Var : Tag_Attribute_Access; Value : Tag_Attribute_Access; end record; type Comment_Tag_Node is new Tag_Node with record Condition : Tag_Attribute_Access; end record; end ASF.Views.Nodes.Facelets;
Use Binding_Type instead of Binding_Access and replace Definition function by a Register procedure
Use Binding_Type instead of Binding_Access and replace Definition function by a Register procedure
Ada
apache-2.0
stcarrez/ada-asf,stcarrez/ada-asf,stcarrez/ada-asf
8512888bce678c94e31a1240e9182d5ad9ecda5b
src/os-win32/util-systems-os.ads
src/os-win32/util-systems-os.ads
----------------------------------------------------------------------- -- util-system-os -- Windows system operations -- 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 System; with Interfaces.C; with Interfaces.C.Strings; with Util.Systems.Types; -- The <b>Util.Systems.Os</b> package defines various types and operations which are specific -- to the OS (Windows). package Util.Systems.Os is -- The directory separator. Directory_Separator : constant Character := '\'; -- Defines several windows specific types. type BOOL is mod 8; type WORD is new Interfaces.C.short; type DWORD is new Interfaces.C.unsigned_long; type PDWORD is access all DWORD; for PDWORD'Size use Standard'Address_Size; function Get_Last_Error return Integer; pragma Import (Stdcall, Get_Last_Error, "GetLastError"); -- Some useful error codes (See Windows document "System Error Codes (0-499)"). ERROR_BROKEN_PIPE : constant Integer := 109; -- ------------------------------ -- Handle -- ------------------------------ -- The windows HANDLE is defined as a void* in the C API. subtype HANDLE is System.Address; type PHANDLE is access all HANDLE; for PHANDLE'Size use Standard'Address_Size; function Wait_For_Single_Object (H : in HANDLE; Time : in DWORD) return DWORD; pragma Import (Stdcall, Wait_For_Single_Object, "WaitForSingleObject"); type Security_Attributes is record Length : DWORD; Security_Descriptor : System.Address; Inherit : Boolean; end record; type LPSECURITY_ATTRIBUTES is access all Security_Attributes; for LPSECURITY_ATTRIBUTES'Size use Standard'Address_Size; -- ------------------------------ -- File operations -- ------------------------------ subtype File_Type is HANDLE; NO_FILE : constant File_Type := System.Null_Address; STD_INPUT_HANDLE : constant DWORD := -10; STD_OUTPUT_HANDLE : constant DWORD := -11; STD_ERROR_HANDLE : constant DWORD := -12; function Get_Std_Handle (Kind : in DWORD) return File_Type; pragma Import (Stdcall, Get_Std_Handle, "GetStdHandle"); function Close_Handle (Fd : in File_Type) return BOOL; pragma Import (Stdcall, Close_Handle, "CloseHandle"); function Duplicate_Handle (SourceProcessHandle : in HANDLE; SourceHandle : in HANDLE; TargetProcessHandle : in HANDLE; TargetHandle : in PHANDLE; DesiredAccess : in DWORD; InheritHandle : in BOOL; Options : in DWORD) return BOOL; pragma Import (Stdcall, Duplicate_Handle, "DuplicateHandle"); function Read_File (Fd : in File_Type; Buf : in System.Address; Size : in DWORD; Result : in PDWORD; Overlap : in System.Address) return BOOL; pragma Import (Stdcall, Read_File, "ReadFile"); function Write_File (Fd : in File_Type; Buf : in System.Address; Size : in DWORD; Result : in PDWORD; Overlap : in System.Address) return BOOL; pragma Import (Stdcall, Write_File, "WriteFile"); function Create_Pipe (Read_Handle : in PHANDLE; Write_Handle : in PHANDLE; Attributes : in LPSECURITY_ATTRIBUTES; Buf_Size : in DWORD) return BOOL; pragma Import (Stdcall, Create_Pipe, "CreatePipe"); -- type Size_T is mod 2 ** Standard'Address_Size; subtype LPWSTR is Interfaces.C.Strings.chars_ptr; subtype PBYTE is Interfaces.C.Strings.chars_ptr; subtype Ptr is Interfaces.C.Strings.chars_ptr; subtype LPCTSTR is System.Address; subtype LPTSTR is System.Address; type CommandPtr is access all Interfaces.C.wchar_array; NULL_STR : constant LPWSTR := Interfaces.C.Strings.Null_Ptr; type Startup_Info is record cb : DWORD := 0; lpReserved : LPWSTR := NULL_STR; lpDesktop : LPWSTR := NULL_STR; lpTitle : LPWSTR := NULL_STR; dwX : DWORD := 0; dwY : DWORD := 0; dwXsize : DWORD := 0; dwYsize : DWORD := 0; dwXCountChars : DWORD := 0; dwYCountChars : DWORD := 0; dwFillAttribute : DWORD := 0; dwFlags : DWORD := 0; wShowWindow : WORD := 0; cbReserved2 : WORD := 0; lpReserved2 : PBYTE := Interfaces.C.Strings.Null_Ptr; hStdInput : HANDLE := System.Null_Address; hStdOutput : HANDLE := System.Null_Address; hStdError : HANDLE := System.Null_Address; end record; pragma Pack (Startup_Info); type Startup_Info_Access is access all Startup_Info; type PROCESS_INFORMATION is record hProcess : HANDLE := NO_FILE; hThread : HANDLE := NO_FILE; dwProcessId : DWORD; dwThreadId : DWORD; end record; type Process_Information_Access is access all PROCESS_INFORMATION; function Get_Current_Process return HANDLE; pragma Import (Stdcall, Get_Current_Process, "GetCurrentProcess"); function Get_Exit_Code_Process (Proc : in HANDLE; Code : in PDWORD) return BOOL; pragma Import (Stdcall, Get_Exit_Code_Process, "GetExitCodeProcess"); function Create_Process (Name : in LPCTSTR; Command : in System.Address; Process_Attributes : in LPSECURITY_ATTRIBUTES; Thread_Attributes : in LPSECURITY_ATTRIBUTES; Inherit_Handlers : in Boolean; Creation_Flags : in DWORD; Environment : in LPTSTR; Directory : in LPCTSTR; Startup_Info : in Startup_Info_Access; Process_Info : in Process_Information_Access) return Integer; pragma Import (Stdcall, Create_Process, "CreateProcessW"); -- Terminate the windows process and all its threads. function Terminate_Process (Proc : in HANDLE; Code : in DWORD) return Integer; pragma Import (Stdcall, Terminate_Process, "TerminateProcess"); function Sys_Stat (Path : in LPWSTR; Stat : access Util.Systems.Types.Stat_Type) return Integer; pragma Import (C, Sys_Stat, "_stat64"); function Sys_Fstat (Fs : in File_Type; Stat : access Util.Systems.Types.Stat_Type) return Integer; pragma Import (C, Sys_Fstat, "_fstat64"); private -- kernel32 is used on Windows32 as well as Windows64. pragma Linker_Options ("-lkernel32"); end Util.Systems.Os;
----------------------------------------------------------------------- -- util-system-os -- Windows system operations -- Copyright (C) 2011, 2012, 2015 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES 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 Interfaces.C; with Interfaces.C.Strings; with Util.Systems.Types; -- The <b>Util.Systems.Os</b> package defines various types and operations which are specific -- to the OS (Windows). package Util.Systems.Os is -- The directory separator. Directory_Separator : constant Character := '\'; -- The path separator. Path_Separator : constant Character := ';'; -- Defines several windows specific types. type BOOL is mod 8; type WORD is new Interfaces.C.short; type DWORD is new Interfaces.C.unsigned_long; type PDWORD is access all DWORD; for PDWORD'Size use Standard'Address_Size; function Get_Last_Error return Integer; pragma Import (Stdcall, Get_Last_Error, "GetLastError"); -- Some useful error codes (See Windows document "System Error Codes (0-499)"). ERROR_BROKEN_PIPE : constant Integer := 109; -- ------------------------------ -- Handle -- ------------------------------ -- The windows HANDLE is defined as a void* in the C API. subtype HANDLE is System.Address; type PHANDLE is access all HANDLE; for PHANDLE'Size use Standard'Address_Size; function Wait_For_Single_Object (H : in HANDLE; Time : in DWORD) return DWORD; pragma Import (Stdcall, Wait_For_Single_Object, "WaitForSingleObject"); type Security_Attributes is record Length : DWORD; Security_Descriptor : System.Address; Inherit : Boolean; end record; type LPSECURITY_ATTRIBUTES is access all Security_Attributes; for LPSECURITY_ATTRIBUTES'Size use Standard'Address_Size; -- ------------------------------ -- File operations -- ------------------------------ subtype File_Type is HANDLE; NO_FILE : constant File_Type := System.Null_Address; STD_INPUT_HANDLE : constant DWORD := -10; STD_OUTPUT_HANDLE : constant DWORD := -11; STD_ERROR_HANDLE : constant DWORD := -12; function Get_Std_Handle (Kind : in DWORD) return File_Type; pragma Import (Stdcall, Get_Std_Handle, "GetStdHandle"); function Close_Handle (Fd : in File_Type) return BOOL; pragma Import (Stdcall, Close_Handle, "CloseHandle"); function Duplicate_Handle (SourceProcessHandle : in HANDLE; SourceHandle : in HANDLE; TargetProcessHandle : in HANDLE; TargetHandle : in PHANDLE; DesiredAccess : in DWORD; InheritHandle : in BOOL; Options : in DWORD) return BOOL; pragma Import (Stdcall, Duplicate_Handle, "DuplicateHandle"); function Read_File (Fd : in File_Type; Buf : in System.Address; Size : in DWORD; Result : in PDWORD; Overlap : in System.Address) return BOOL; pragma Import (Stdcall, Read_File, "ReadFile"); function Write_File (Fd : in File_Type; Buf : in System.Address; Size : in DWORD; Result : in PDWORD; Overlap : in System.Address) return BOOL; pragma Import (Stdcall, Write_File, "WriteFile"); function Create_Pipe (Read_Handle : in PHANDLE; Write_Handle : in PHANDLE; Attributes : in LPSECURITY_ATTRIBUTES; Buf_Size : in DWORD) return BOOL; pragma Import (Stdcall, Create_Pipe, "CreatePipe"); -- type Size_T is mod 2 ** Standard'Address_Size; subtype LPWSTR is Interfaces.C.Strings.chars_ptr; subtype PBYTE is Interfaces.C.Strings.chars_ptr; subtype Ptr is Interfaces.C.Strings.chars_ptr; subtype LPCTSTR is System.Address; subtype LPTSTR is System.Address; type CommandPtr is access all Interfaces.C.wchar_array; NULL_STR : constant LPWSTR := Interfaces.C.Strings.Null_Ptr; type Startup_Info is record cb : DWORD := 0; lpReserved : LPWSTR := NULL_STR; lpDesktop : LPWSTR := NULL_STR; lpTitle : LPWSTR := NULL_STR; dwX : DWORD := 0; dwY : DWORD := 0; dwXsize : DWORD := 0; dwYsize : DWORD := 0; dwXCountChars : DWORD := 0; dwYCountChars : DWORD := 0; dwFillAttribute : DWORD := 0; dwFlags : DWORD := 0; wShowWindow : WORD := 0; cbReserved2 : WORD := 0; lpReserved2 : PBYTE := Interfaces.C.Strings.Null_Ptr; hStdInput : HANDLE := System.Null_Address; hStdOutput : HANDLE := System.Null_Address; hStdError : HANDLE := System.Null_Address; end record; pragma Pack (Startup_Info); type Startup_Info_Access is access all Startup_Info; type PROCESS_INFORMATION is record hProcess : HANDLE := NO_FILE; hThread : HANDLE := NO_FILE; dwProcessId : DWORD; dwThreadId : DWORD; end record; type Process_Information_Access is access all PROCESS_INFORMATION; function Get_Current_Process return HANDLE; pragma Import (Stdcall, Get_Current_Process, "GetCurrentProcess"); function Get_Exit_Code_Process (Proc : in HANDLE; Code : in PDWORD) return BOOL; pragma Import (Stdcall, Get_Exit_Code_Process, "GetExitCodeProcess"); function Create_Process (Name : in LPCTSTR; Command : in System.Address; Process_Attributes : in LPSECURITY_ATTRIBUTES; Thread_Attributes : in LPSECURITY_ATTRIBUTES; Inherit_Handlers : in Boolean; Creation_Flags : in DWORD; Environment : in LPTSTR; Directory : in LPCTSTR; Startup_Info : in Startup_Info_Access; Process_Info : in Process_Information_Access) return Integer; pragma Import (Stdcall, Create_Process, "CreateProcessW"); -- Terminate the windows process and all its threads. function Terminate_Process (Proc : in HANDLE; Code : in DWORD) return Integer; pragma Import (Stdcall, Terminate_Process, "TerminateProcess"); function Sys_Stat (Path : in LPWSTR; Stat : access Util.Systems.Types.Stat_Type) return Integer; pragma Import (C, Sys_Stat, "_stat64"); function Sys_Fstat (Fs : in File_Type; Stat : access Util.Systems.Types.Stat_Type) return Integer; pragma Import (C, Sys_Fstat, "_fstat64"); private -- kernel32 is used on Windows32 as well as Windows64. pragma Linker_Options ("-lkernel32"); end Util.Systems.Os;
Declare Path_Separator constant
Declare Path_Separator constant
Ada
apache-2.0
stcarrez/ada-util,stcarrez/ada-util
2af482db32834e863da818046460b13793640a34
orka_numerics/src/x86/generic/sse4_1/orka-numerics-singles-tensors-cpu.ads
orka_numerics/src/x86/generic/sse4_1/orka-numerics-singles-tensors-cpu.ads
-- SPDX-License-Identifier: Apache-2.0 -- -- Copyright (c) 2021 onox <[email protected]> -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. with Orka.Numerics.Tensors.SIMD_CPU; with Orka.SIMD.SSE.Singles.Arithmetic; with Orka.SIMD.SSE.Singles.Compare; with Orka.SIMD.SSE.Singles.Logical; with Orka.SIMD.SSE.Singles.Math; with Orka.SIMD.SSE2.Integers.Arithmetic; with Orka.SIMD.SSE2.Integers.Logical; with Orka.SIMD.SSE2.Integers.Random; with Orka.SIMD.SSE2.Integers.Shift; with Orka.SIMD.SSE3.Singles.Arithmetic; with Orka.SIMD.SSE4_1.Integers.Logical; with Orka.SIMD.SSE4_1.Singles.Math; package Orka.Numerics.Singles.Tensors.CPU is new Orka.Numerics.Singles.Tensors.SIMD_CPU (Index_Homogeneous, Integer_32, SIMD.SSE2.Integers.m128i, SIMD.SSE2.Integers.Arithmetic."+", SIMD.SSE2.Integers.Logical."and", SIMD.SSE2.Integers.Shift.Shift_Elements_Left_Zeros, SIMD.SSE2.Integers.Shift.Shift_Elements_Right_Zeros, SIMD.SSE4_1.Integers.Logical.Test_All_Ones, SIMD.SSE4_1.Integers.Logical.Test_All_Zero, SIMD.SSE.Singles.m128, SIMD.SSE.Singles.Arithmetic."*", SIMD.SSE.Singles.Arithmetic."/", SIMD.SSE.Singles.Arithmetic."+", SIMD.SSE.Singles.Arithmetic."-", SIMD.SSE.Singles.Arithmetic."-", SIMD.SSE.Singles.Arithmetic."abs", SIMD.SSE3.Singles.Arithmetic.Sum, SIMD.SSE.Singles.Arithmetic.Divide_Or_Zero, SIMD.SSE.Singles.Math.Sqrt, SIMD.SSE.Singles.Math.Min, SIMD.SSE.Singles.Math.Max, SIMD.SSE4_1.Singles.Math.Ceil, SIMD.SSE4_1.Singles.Math.Floor, SIMD.SSE4_1.Singles.Math.Round_Nearest_Integer, SIMD.SSE4_1.Singles.Math.Round_Truncate, SIMD.SSE.Singles.Logical.And_Not, SIMD.SSE.Singles.Logical."and", SIMD.SSE.Singles.Logical."or", SIMD.SSE.Singles.Logical."xor", SIMD.SSE.Singles.Compare."=", SIMD.SSE.Singles.Compare."/=", SIMD.SSE.Singles.Compare.">", SIMD.SSE.Singles.Compare."<", SIMD.SSE.Singles.Compare.">=", SIMD.SSE.Singles.Compare."<=", SIMD.SSE2.Integers.Random.State, SIMD.SSE2.Integers.Random.Next, SIMD.SSE2.Integers.Random.Reset); pragma Preelaborate (Orka.Numerics.Singles.Tensors.CPU);
-- SPDX-License-Identifier: Apache-2.0 -- -- Copyright (c) 2021 onox <[email protected]> -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. with Orka.Numerics.Tensors.SIMD_CPU; with Orka.SIMD.SSE.Singles.Arithmetic; with Orka.SIMD.SSE.Singles.Compare; with Orka.SIMD.SSE.Singles.Logical; with Orka.SIMD.SSE.Singles.Math; with Orka.SIMD.SSE2.Integers.Arithmetic; with Orka.SIMD.SSE2.Integers.Logical; with Orka.SIMD.SSE2.Integers.Random; with Orka.SIMD.SSE2.Integers.Shift; with Orka.SIMD.SSE3.Singles.Arithmetic; with Orka.SIMD.SSE4_1.Integers.Logical; with Orka.SIMD.SSE4_1.Singles.Math; package Orka.Numerics.Singles.Tensors.CPU is new Orka.Numerics.Singles.Tensors.SIMD_CPU (Index_4D, Integer_32, SIMD.SSE2.Integers.m128i, SIMD.SSE2.Integers.Arithmetic."+", SIMD.SSE2.Integers.Logical."and", SIMD.SSE2.Integers.Shift.Shift_Elements_Left_Zeros, SIMD.SSE2.Integers.Shift.Shift_Elements_Right_Zeros, SIMD.SSE4_1.Integers.Logical.Test_All_Ones, SIMD.SSE4_1.Integers.Logical.Test_All_Zero, SIMD.SSE.Singles.m128, SIMD.SSE.Singles.Arithmetic."*", SIMD.SSE.Singles.Arithmetic."/", SIMD.SSE.Singles.Arithmetic."+", SIMD.SSE.Singles.Arithmetic."-", SIMD.SSE.Singles.Arithmetic."-", SIMD.SSE.Singles.Arithmetic."abs", SIMD.SSE3.Singles.Arithmetic.Sum, SIMD.SSE.Singles.Arithmetic.Divide_Or_Zero, SIMD.SSE.Singles.Math.Sqrt, SIMD.SSE.Singles.Math.Min, SIMD.SSE.Singles.Math.Max, SIMD.SSE4_1.Singles.Math.Ceil, SIMD.SSE4_1.Singles.Math.Floor, SIMD.SSE4_1.Singles.Math.Round_Nearest_Integer, SIMD.SSE4_1.Singles.Math.Round_Truncate, SIMD.SSE.Singles.Logical.And_Not, SIMD.SSE.Singles.Logical."and", SIMD.SSE.Singles.Logical."or", SIMD.SSE.Singles.Logical."xor", SIMD.SSE.Singles.Compare."=", SIMD.SSE.Singles.Compare."/=", SIMD.SSE.Singles.Compare.">", SIMD.SSE.Singles.Compare."<", SIMD.SSE.Singles.Compare.">=", SIMD.SSE.Singles.Compare."<=", SIMD.SSE2.Integers.Random.State, SIMD.SSE2.Integers.Random.Next, SIMD.SSE2.Integers.Random.Reset); pragma Preelaborate (Orka.Numerics.Singles.Tensors.CPU);
Rename occurrences of Index_Homogeneous to Index_4D
numerics: Rename occurrences of Index_Homogeneous to Index_4D Signed-off-by: onox <[email protected]>
Ada
apache-2.0
onox/orka
12f03d1a1ffe042e3a1420fd51605e82f89c22dc
awa/src/awa-applications-configs.adb
awa/src/awa-applications-configs.adb
----------------------------------------------------------------------- -- awa-applications-configs -- Read application configuration files -- Copyright (C) 2011, 2012 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Log.Loggers; with ASF.Contexts.Faces; with ASF.Applications.Main.Configs; with Security.Permissions; with Security.Controllers.Roles; with AWA.Permissions.Configs; with AWA.Events.Configs; with AWA.Services.Contexts; package body AWA.Applications.Configs is use Util.Log; Log : constant Loggers.Logger := Loggers.Create ("AWA.Applications.Configs"); -- ------------------------------ -- XML reader configuration. By instantiating this generic package, the XML parser -- gets initialized to read the configuration for servlets, filters, managed beans, -- permissions, events and other configuration elements. -- ------------------------------ package body Reader_Config is App_Access : constant ASF.Contexts.Faces.Application_Access := App.all'Unchecked_Access; Sec : constant Security.Permissions.Permission_Manager_Access := App.Get_Permission_Manager; package Bean_Config is new ASF.Applications.Main.Configs.Reader_Config (Reader, App_Access, Context.all'Access); package Policy_Config is new Security.Permissions.Reader_Config (Reader, Sec); package Role_Config is new Security.Controllers.Roles.Reader_Config (Reader, Sec); package Entity_Config is new AWA.Permissions.Configs.Reader_Config (Reader, Sec); package Event_Config is new AWA.Events.Configs.Reader_Config (Reader => Reader, Manager => App.Events'Unchecked_Access, Context => Context.all'Access); pragma Warnings (Off, Bean_Config); pragma Warnings (Off, Policy_Config); pragma Warnings (Off, Role_Config); pragma Warnings (Off, Entity_Config); pragma Warnings (Off, Event_Config); end Reader_Config; -- ------------------------------ -- Read the application configuration file and configure the application -- ------------------------------ procedure Read_Configuration (App : in out Application'Class; File : in String; Context : in EL.Contexts.Default.Default_Context_Access) is Reader : Util.Serialize.IO.XML.Parser; Ctx : AWA.Services.Contexts.Service_Context; begin Log.Info ("Reading application configuration file {0}", File); Ctx.Set_Context (App'Unchecked_Access, null); declare package Config is new Reader_Config (Reader, App'Unchecked_Access, Context); pragma Warnings (Off, Config); begin -- Initialize the parser with the module configuration mappers (if any). Initialize_Parser (App, Reader); if Log.Get_Level >= Util.Log.DEBUG_LEVEL then Util.Serialize.IO.Dump (Reader, Log); end if; -- Read the configuration file and record managed beans, navigation rules. Reader.Parse (File); end; exception when others => Log.Error ("Error while reading {0}", File); raise; end Read_Configuration; end AWA.Applications.Configs;
----------------------------------------------------------------------- -- awa-applications-configs -- Read application configuration files -- Copyright (C) 2011, 2012 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Log.Loggers; with ASF.Contexts.Faces; with ASF.Applications.Main.Configs; with Security.Policies; with AWA.Events.Configs; with AWA.Services.Contexts; package body AWA.Applications.Configs is use Util.Log; Log : constant Loggers.Logger := Loggers.Create ("AWA.Applications.Configs"); -- ------------------------------ -- XML reader configuration. By instantiating this generic package, the XML parser -- gets initialized to read the configuration for servlets, filters, managed beans, -- permissions, events and other configuration elements. -- ------------------------------ package body Reader_Config is App_Access : constant ASF.Contexts.Faces.Application_Access := App.all'Unchecked_Access; Sec : constant Security.Policies.Policy_Manager_Access := App.Get_Security_Manager; package Bean_Config is new ASF.Applications.Main.Configs.Reader_Config (Reader, App_Access, Context.all'Access); package Policy_Config is new Security.Policies.Reader_Config (Reader, Sec); package Event_Config is new AWA.Events.Configs.Reader_Config (Reader => Reader, Manager => App.Events'Unchecked_Access, Context => Context.all'Access); pragma Warnings (Off, Bean_Config); pragma Warnings (Off, Policy_Config); pragma Warnings (Off, Event_Config); end Reader_Config; -- ------------------------------ -- Read the application configuration file and configure the application -- ------------------------------ procedure Read_Configuration (App : in out Application'Class; File : in String; Context : in EL.Contexts.Default.Default_Context_Access) is Reader : Util.Serialize.IO.XML.Parser; Ctx : AWA.Services.Contexts.Service_Context; begin Log.Info ("Reading application configuration file {0}", File); Ctx.Set_Context (App'Unchecked_Access, null); declare package Config is new Reader_Config (Reader, App'Unchecked_Access, Context); pragma Warnings (Off, Config); begin -- Initialize the parser with the module configuration mappers (if any). Initialize_Parser (App, Reader); if Log.Get_Level >= Util.Log.DEBUG_LEVEL then Util.Serialize.IO.Dump (Reader, Log); end if; -- Read the configuration file and record managed beans, navigation rules. Reader.Parse (File); end; exception when others => Log.Error ("Error while reading {0}", File); raise; end Read_Configuration; end AWA.Applications.Configs;
Use the Security.Policies to configure the security permissions
Use the Security.Policies to configure the security permissions
Ada
apache-2.0
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
86298308a1337a2ae90153047c0c627f52df6bc9
matp/src/events/mat-events-targets.ads
matp/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 Ada.Finalization; 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 Event_Info_Type is record First_Event : Target_Event; Last_Event : Target_Event; Frame_Addr : MAT.Types.Target_Addr; Count : Natural; end record; package Size_Event_Info_Maps is new Ada.Containers.Ordered_Maps (Key_Type => MAT.Types.Target_Size, Element_Type => Event_Info_Type); subtype Size_Event_Info_Map is Size_Event_Info_Maps.Map; subtype Size_Event_Info_Cursor is Size_Event_Info_Maps.Cursor; package Frame_Event_Info_Maps is new Ada.Containers.Ordered_Maps (Key_Type => MAT.Types.Target_Addr, Element_Type => Event_Info_Type); subtype Frame_Event_Info_Map is Frame_Event_Info_Maps.Map; subtype Frame_Event_Info_Cursor is Frame_Event_Info_Maps.Cursor; package Event_Info_Vectors is new Ada.Containers.Vectors (Index_Type => Positive, Element_Type => Event_Info_Type); subtype Event_Info_Vector is Event_Info_Vectors.Vector; subtype Event_Info_Cursor is Event_Info_Vectors.Cursor; -- Extract from the frame info map, the list of event info sorted on the count. procedure Build_Event_Info (Map : in Frame_Event_Info_Map; List : in out Event_Info_Vector); 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)); -- Iterate over the events starting from first first event up to the last event collected. -- Execute the <tt>Process</tt> procedure with each event instance. procedure Iterate (Target : in out Target_Events; Process : access procedure (Event : in Target_Event)); 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)); -- Clear the events. procedure Clear; 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 new Ada.Finalization.Limited_Controlled with record Events : Event_Collector; Event_Count : Util.Concurrent.Counters.Counter; end record; -- Release the storage allocated for the events. overriding procedure Finalize (Target : in out Target_Events); 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 Ada.Finalization; 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; Old_Size : MAT.Types.Target_Size; 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 Event_Info_Type is record First_Event : Target_Event; Last_Event : Target_Event; Frame_Addr : MAT.Types.Target_Addr; Count : Natural; end record; package Size_Event_Info_Maps is new Ada.Containers.Ordered_Maps (Key_Type => MAT.Types.Target_Size, Element_Type => Event_Info_Type); subtype Size_Event_Info_Map is Size_Event_Info_Maps.Map; subtype Size_Event_Info_Cursor is Size_Event_Info_Maps.Cursor; package Frame_Event_Info_Maps is new Ada.Containers.Ordered_Maps (Key_Type => MAT.Types.Target_Addr, Element_Type => Event_Info_Type); subtype Frame_Event_Info_Map is Frame_Event_Info_Maps.Map; subtype Frame_Event_Info_Cursor is Frame_Event_Info_Maps.Cursor; package Event_Info_Vectors is new Ada.Containers.Vectors (Index_Type => Positive, Element_Type => Event_Info_Type); subtype Event_Info_Vector is Event_Info_Vectors.Vector; subtype Event_Info_Cursor is Event_Info_Vectors.Cursor; -- Extract from the frame info map, the list of event info sorted on the count. procedure Build_Event_Info (Map : in Frame_Event_Info_Map; List : in out Event_Info_Vector); 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)); -- Iterate over the events starting from first first event up to the last event collected. -- Execute the <tt>Process</tt> procedure with each event instance. procedure Iterate (Target : in out Target_Events; Process : access procedure (Event : in Target_Event)); 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)); -- Clear the events. procedure Clear; 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 new Ada.Finalization.Limited_Controlled with record Events : Event_Collector; Event_Count : Util.Concurrent.Counters.Counter; end record; -- Release the storage allocated for the events. overriding procedure Finalize (Target : in out Target_Events); end MAT.Events.Targets;
Add the Old_Size in the Probe_Event_Type to track realloc information
Add the Old_Size in the Probe_Event_Type to track realloc information
Ada
apache-2.0
stcarrez/mat,stcarrez/mat,stcarrez/mat
b8f84be9c9242e279e0a2c49c5f3ed98127a046c
src/ado-drivers.ads
src/ado-drivers.ads
----------------------------------------------------------------------- -- ADO Drivers -- Database Drivers -- Copyright (C) 2010, 2011, 2012 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Properties; -- The <b>ADO.Drivers</b> package represents the database driver that will create -- database connections and provide the database specific implementation. package ADO.Drivers is use Ada.Strings.Unbounded; -- Raised when the connection URI is invalid. Connection_Error : exception; -- Raised for all errors reported by the database DB_Error : exception; type Driver_Index is new Natural range 0 .. 4; -- Initialize the drivers and the library by reading the property file -- and configure the runtime with it. procedure Initialize (Config : in String); -- Initialize the drivers and the library and configure the runtime with the given properties. procedure Initialize (Config : in Util.Properties.Manager'Class); -- Initialize the drivers which are available. procedure 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; end ADO.Drivers;
----------------------------------------------------------------------- -- ADO Drivers -- Database Drivers -- 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.Properties; -- The <b>ADO.Drivers</b> package represents the database driver that will create -- database connections and provide the database specific implementation. package ADO.Drivers is use Ada.Strings.Unbounded; -- Raised when the connection URI is invalid. Connection_Error : exception; -- Raised for all errors reported by the database DB_Error : exception; type Driver_Index is new Natural range 0 .. 4; -- Initialize the drivers and the library by reading the property file -- and configure the runtime with it. procedure Initialize (Config : in String); -- Initialize the drivers and the library and configure the runtime with the given properties. procedure Initialize (Config : in Util.Properties.Manager'Class); -- Get the global configuration property identified by the name. -- If the configuration property does not exist, returns the default value. function Get_Config (Name : in String; Default : in String := "") return String; end ADO.Drivers;
Move the Initialize operation in a separate library
Move the Initialize operation in a separate library
Ada
apache-2.0
stcarrez/ada-ado
e41f43dbd83073dd28e27090675fefc97e0dfd16
src/babel-files.adb
src/babel-files.adb
-- bkp-files -- File and directories ----------------------------------------------------------------------- -- Copyright (C) 2014 Stephane.Carrez -- Written by Stephane.Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Log.Loggers; with Util.Files; with Util.Encoders.Base16; package body Babel.Files is Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("Bkp.Files"); Hex_Encoder : Util.Encoders.Base16.Encoder; -- ------------------------------ -- Allocate a File_Type entry with the given name for the directory. -- ------------------------------ function Allocate (Name : in String; Dir : in Directory_Type) return File_Type is Result : constant File_Type := new File '(Len => Name'Length, Id => NO_IDENTIFIER, Dir => Dir, Name => Name, others => <>); begin return Result; end Allocate; -- ------------------------------ -- Allocate a Directory_Type entry with the given name for the directory. -- ------------------------------ function Allocate (Name : in String; Dir : in Directory_Type) return Directory_Type is use Ada.Strings.Unbounded; Result : constant Directory_Type := new Directory '(Len => Name'Length, Id => NO_IDENTIFIER, Parent => Dir, Name => Name, others => <>); begin if Dir /= null then Result.Path := To_Unbounded_String (Util.Files.Compose (To_String (Dir.Path), Name)); end if; return Result; end Allocate; -- ------------------------------ -- Return true if the file was modified and need a backup. -- ------------------------------ function Is_Modified (Element : in File_Type) return Boolean is use type ADO.Identifier; begin if Element.Id = NO_IDENTIFIER then return True; elsif (Element.Status and FILE_MODIFIED) /= 0 then return True; else return False; end if; end Is_Modified; -- ------------------------------ -- Set the file as modified. -- ------------------------------ procedure Set_Modified (Element : in File_Type) is begin Element.Status := Element.Status or FILE_MODIFIED; end Set_Modified; -- ------------------------------ -- Set the SHA1 signature that was computed for this file. -- If the computed signature is different from the current signature, -- the FILE_MODIFIED flag is set on the file. The FILE_HAS_SHA1 flag -- is set on the file. -- ------------------------------ procedure Set_Signature (Element : in File_Type; Signature : in Util.Encoders.SHA1.Hash_Array) is use type Util.Encoders.SHA1.Hash_Array; begin if (Element.Status and FILE_HAS_SHA1) /= 0 and then Element.SHA1 /= Signature then Element.Status := Element.Status or FILE_MODIFIED; end if; Element.Status := Element.Status or FILE_HAS_SHA1; Element.SHA1 := Signature; end Set_Signature; -- ------------------------------ -- Set the file size. If the new size is different, the FILE_MODIFIED -- flag is set on the file. -- ------------------------------ procedure Set_Size (Element : in File_Type; Size : in File_Size) is begin if Element.Size /= Size then Element.Size := Size; Element.Status := Element.Status or FILE_MODIFIED; end if; end Set_Size; -- ------------------------------ -- Return the path for the file. -- ------------------------------ function Get_Path (Element : in File_Type) return String is begin if Element.Dir = null then return Element.Name; else return Util.Files.Compose (Get_Path (Element.Dir), Element.Name); end if; end Get_Path; -- ------------------------------ -- Return the path for the directory. -- ------------------------------ function Get_Path (Element : in Directory_Type) return String is begin return Ada.Strings.Unbounded.To_String (Element.Path); end Get_Path; -- ------------------------------ -- Return the SHA1 signature computed for the file. -- ------------------------------ function Get_SHA1 (Element : in File_Type) return String is begin return Hex_Encoder.Transform (Element.SHA1); end Get_SHA1; end Babel.Files;
-- bkp-files -- File and directories ----------------------------------------------------------------------- -- Copyright (C) 2014 Stephane.Carrez -- Written by Stephane.Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Log.Loggers; with Util.Files; with Util.Encoders.Base16; package body Babel.Files is Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("Bkp.Files"); Hex_Encoder : Util.Encoders.Base16.Encoder; -- ------------------------------ -- Allocate a File_Type entry with the given name for the directory. -- ------------------------------ function Allocate (Name : in String; Dir : in Directory_Type) return File_Type is Result : constant File_Type := new File '(Len => Name'Length, Id => NO_IDENTIFIER, Dir => Dir, Name => Name, others => <>); begin return Result; end Allocate; -- ------------------------------ -- Allocate a Directory_Type entry with the given name for the directory. -- ------------------------------ function Allocate (Name : in String; Dir : in Directory_Type) return Directory_Type is use Ada.Strings.Unbounded; Result : constant Directory_Type := new Directory '(Len => Name'Length, Id => NO_IDENTIFIER, Parent => Dir, Name => Name, others => <>); begin if Dir /= null then Result.Path := To_Unbounded_String (Util.Files.Compose (To_String (Dir.Path), Name)); end if; return Result; end Allocate; -- ------------------------------ -- Return true if the file was modified and need a backup. -- ------------------------------ function Is_Modified (Element : in File_Type) return Boolean is use type ADO.Identifier; begin if Element.Id = NO_IDENTIFIER then return True; elsif (Element.Status and FILE_MODIFIED) /= 0 then return True; else return False; end if; end Is_Modified; -- ------------------------------ -- Set the file as modified. -- ------------------------------ procedure Set_Modified (Element : in File_Type) is begin Element.Status := Element.Status or FILE_MODIFIED; end Set_Modified; -- ------------------------------ -- Set the SHA1 signature that was computed for this file. -- If the computed signature is different from the current signature, -- the FILE_MODIFIED flag is set on the file. The FILE_HAS_SHA1 flag -- is set on the file. -- ------------------------------ procedure Set_Signature (Element : in File_Type; Signature : in Util.Encoders.SHA1.Hash_Array) is use type Util.Encoders.SHA1.Hash_Array; begin if (Element.Status and FILE_HAS_SHA1) /= 0 and then Element.SHA1 /= Signature then Element.Status := Element.Status or FILE_MODIFIED; end if; Element.Status := Element.Status or FILE_HAS_SHA1; Element.SHA1 := Signature; end Set_Signature; -- ------------------------------ -- Set the file size. If the new size is different, the FILE_MODIFIED -- flag is set on the file. -- ------------------------------ procedure Set_Size (Element : in File_Type; Size : in File_Size) is begin if Element.Size /= Size then Element.Size := Size; Element.Status := Element.Status or FILE_MODIFIED; end if; end Set_Size; -- ------------------------------ -- Return the path for the file. -- ------------------------------ function Get_Path (Element : in File_Type) return String is begin if Element.Dir = null then return Element.Name; else return Util.Files.Compose (Get_Path (Element.Dir), Element.Name); end if; end Get_Path; -- ------------------------------ -- Return the path for the directory. -- ------------------------------ function Get_Path (Element : in Directory_Type) return String is begin return Ada.Strings.Unbounded.To_String (Element.Path); end Get_Path; -- ------------------------------ -- Return the SHA1 signature computed for the file. -- ------------------------------ function Get_SHA1 (Element : in File_Type) return String is begin return Hex_Encoder.Transform (Element.SHA1); end Get_SHA1; -- ------------------------------ -- Add the file with the given name in the container. -- ------------------------------ overriding procedure Add_File (Into : in out Default_Container; Element : in File_Type) is begin Into.Files.Append (Element); end Add_File; -- ------------------------------ -- Add the directory with the given name in the container. -- ------------------------------ overriding procedure Add_Directory (Into : in out Default_Container; Element : in Directory_Type) is begin Into.Dirs.Append (Element); end Add_Directory; -- ------------------------------ -- Create a new file instance with the given name in the container. -- ------------------------------ overriding function Create (Into : in Default_Container; Name : in String) return File_Type is begin return Allocate (Name => Name, Dir => Into.Current); end Create; -- ------------------------------ -- Create a new directory instance with the given name in the container. -- ------------------------------ overriding function Create (Into : in Default_Container; Name : in String) return Directory_Type is begin return Allocate (Name => Name, Dir => Into.Current); end Create; -- ------------------------------ -- Find the file with the given name in this file container. -- Returns NO_FILE if the file was not found. -- ------------------------------ overriding function Find (From : in Default_Container; Name : in String) return File_Type is begin return NO_FILE; end Find; -- ------------------------------ -- Find the directory with the given name in this file container. -- Returns NO_DIRECTORY if the directory was not found. -- ------------------------------ overriding function Find (From : in Default_Container; Name : in String) return Directory_Type is begin return NO_DIRECTORY; end Find; end Babel.Files;
Implement the Default_Container operations
Implement the Default_Container operations
Ada
apache-2.0
stcarrez/babel
01bd595df79fda14604042f575ee3a19696a09cd
src/babel-files.adb
src/babel-files.adb
-- bkp-files -- File and directories ----------------------------------------------------------------------- -- Copyright (C) 2014 Stephane.Carrez -- Written by Stephane.Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Strings.Unbounded; with Ada.Directories; with Ada.Containers.Vectors; with Ada.Text_IO; with Ada.Exceptions; with Ada.Streams.Stream_IO; with Util.Log.Loggers; with Util.Files; with Interfaces.C; package body Babel.Files is Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("Bkp.Files"); -- ------------------------------ -- Allocate a File_Type entry with the given name for the directory. -- ------------------------------ function Allocate (Name : in String; Dir : in Directory_Type) return File_Type is Result : constant File_Type := new File '(Len => Name'Length, Id => NO_IDENTIFIER, Dir => Dir, Name => Name, others => <>); begin return Result; end Allocate; -- ------------------------------ -- Return true if the file was modified and need a backup. -- ------------------------------ function Is_Modified (Element : in File_Type) return Boolean is use type ADO.Identifier; begin if Element.Id = NO_IDENTIFIER then return True; elsif (Element.Status and FILE_MODIFIED) /= 0 then return True; else return False; end if; end Is_Modified; -- ------------------------------ -- Set the file as modified. -- ------------------------------ procedure Set_Modified (Element : in File_Type) is begin Element.Status := Element.Status or FILE_MODIFIED; end Set_Modified; -- ------------------------------ -- Return the path for the file. -- ------------------------------ function Get_Path (Element : in File) return String is begin return Util.Files.Compose (Ada.Strings.Unbounded.To_String (Element.Path), Ada.Strings.Unbounded.To_String (Element.Name)); end Get_Path; end Babel.Files;
-- bkp-files -- File and directories ----------------------------------------------------------------------- -- Copyright (C) 2014 Stephane.Carrez -- Written by Stephane.Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Strings.Unbounded; with Ada.Directories; with Ada.Containers.Vectors; with Ada.Text_IO; with Ada.Exceptions; with Ada.Streams.Stream_IO; with Util.Log.Loggers; with Util.Files; with Interfaces.C; package body Babel.Files is Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("Bkp.Files"); -- ------------------------------ -- Allocate a File_Type entry with the given name for the directory. -- ------------------------------ function Allocate (Name : in String; Dir : in Directory_Type) return File_Type is Result : constant File_Type := new File '(Len => Name'Length, Id => NO_IDENTIFIER, Dir => Dir, Name => Name, others => <>); begin return Result; end Allocate; -- ------------------------------ -- Return true if the file was modified and need a backup. -- ------------------------------ function Is_Modified (Element : in File_Type) return Boolean is use type ADO.Identifier; begin if Element.Id = NO_IDENTIFIER then return True; elsif (Element.Status and FILE_MODIFIED) /= 0 then return True; else return False; end if; end Is_Modified; -- ------------------------------ -- Set the file as modified. -- ------------------------------ procedure Set_Modified (Element : in File_Type) is begin Element.Status := Element.Status or FILE_MODIFIED; end Set_Modified; -- ------------------------------ -- Return the path for the file. -- ------------------------------ function Get_Path (Element : in File_Type) return String is begin if Element.Dir = null then return Element.Name; else return Util.Files.Compose (Get_Path (Element.Dir), Element.Name); end if; end Get_Path; -- ------------------------------ -- Return the path for the directory. -- ------------------------------ function Get_Path (Element : in Directory_Type) return String is begin return Ada.Strings.Unbounded.To_String (Element.Path); end Get_Path; end Babel.Files;
Implement the Get_Path operations
Implement the Get_Path operations
Ada
apache-2.0
stcarrez/babel
737d7c7cd807a9bddb7bd943b7279dcfbe3fa893
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 := "33"; 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 := "34"; 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 to 1.34
Bump version to 1.34
Ada
isc
jrmarino/synth,jrmarino/synth,jrmarino/synth,jrmarino/synth
99a1e9673fc6e958a2ac26a9af6007564695d708
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 := "70"; copyright_years : constant String := "2015-2017"; host_localbase : constant String := "/usr/local"; host_make : constant String := "/usr/bin/make"; host_pkg8 : constant String := host_localbase & "/sbin/pkg"; host_bmake : constant String := host_localbase & "/bin/bmake"; host_make_program : constant String := host_make; chroot_make : constant String := "/usr/bin/make"; chroot_bmake : constant String := "/usr/pkg/bin/bmake -m /usr/pkg/share/mk"; chroot_make_program : constant String := chroot_make; jobs_per_cpu : constant := 2; type cpu_range is range 1 .. 32; type scanners is range cpu_range'First .. cpu_range'Last; type builders is range cpu_range'First .. cpu_range'Last * jobs_per_cpu; type package_system is (ports_collection, pkgsrc); software_framework : constant package_system := ports_collection; -- Notes for tailoring Synth. Use sed to: -- 1. Modify host_localbase to value of LOCALBASE -- 2. Change software_framework to "pkgsrc" for pkgsrc version -- 3. Change host_make_program to "host_bmake" for Non-NetBSD pkgsrc platforms -- 4. Change chroot_make_program to "chroot_bmake" for pkgsrc version -- 5. On replicant.ads, change "/usr/local" to "/usr/pkg" on pkgsrc end Definitions;
-- This file is covered by the Internet Software Consortium (ISC) License -- Reference: ../License.txt package Definitions is pragma Pure; synth_version_major : constant String := "1"; synth_version_minor : constant String := "71"; copyright_years : constant String := "2015-2017"; host_localbase : constant String := "/usr/local"; host_make : constant String := "/usr/bin/make"; host_pkg8 : constant String := host_localbase & "/sbin/pkg"; host_bmake : constant String := host_localbase & "/bin/bmake"; host_make_program : constant String := host_make; chroot_make : constant String := "/usr/bin/make"; chroot_bmake : constant String := "/usr/pkg/bin/bmake -m /usr/pkg/share/mk"; chroot_make_program : constant String := chroot_make; jobs_per_cpu : constant := 2; type cpu_range is range 1 .. 32; type scanners is range cpu_range'First .. cpu_range'Last; type builders is range cpu_range'First .. cpu_range'Last * jobs_per_cpu; type package_system is (ports_collection, pkgsrc); software_framework : constant package_system := ports_collection; -- Notes for tailoring Synth. Use sed to: -- 1. Modify host_localbase to value of LOCALBASE -- 2. Change software_framework to "pkgsrc" for pkgsrc version -- 3. Change host_make_program to "host_bmake" for Non-NetBSD pkgsrc platforms -- 4. Change chroot_make_program to "chroot_bmake" for pkgsrc version -- 5. On replicant.ads, change "/usr/local" to "/usr/pkg" on pkgsrc end Definitions;
Bump version to v1.71
Bump version to v1.71
Ada
isc
jrmarino/synth,jrmarino/synth,jrmarino/synth,jrmarino/synth
2095c5264596752bb25da097c1d2ddd0816e24ef
awa/plugins/awa-setup/src/awa-setup-applications.ads
awa/plugins/awa-setup/src/awa-setup-applications.ads
----------------------------------------------------------------------- -- awa-setup -- Setup and installation -- Copyright (C) 2016 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Strings.Unbounded; with ASF.Applications.Main; with ASF.Servlets.Faces; with ASF.Servlets.Files; with ASF.Requests; with ASF.Responses; with ASF.Server; with Util.Beans.Objects; with Util.Beans.Basic; with Util.Beans.Methods; with ADO.Drivers.Connections; package AWA.Setup.Applications is -- The <b>Servlet</b> represents the component that will handle -- an HTTP request received by the server. type Redirect_Servlet is new ASF.Servlets.Servlet with null record; overriding procedure Do_Get (Server : in Redirect_Servlet; Request : in out ASF.Requests.Request'Class; Response : in out ASF.Responses.Response'Class); -- The configuration state starts in the <tt>CONFIGURING</tt> state and moves to the -- <tt>STARTING</tt> state after the application is configured and it is started. -- Once the application is initialized and registered in the server container, the -- state is changed to <tt>READY</tt>. type Configure_State is (CONFIGURING, STARTING, READY); -- Maintains the state of the configuration between the main task and the http configuration -- requests. protected type State is -- Wait until the configuration is finished. entry Wait_Configuring; -- Wait until the server application is initialized and ready. entry Wait_Ready; -- Set the configuration state. procedure Set (V : in Configure_State); private Value : Configure_State := CONFIGURING; end State; type Application is new ASF.Applications.Main.Application and Util.Beans.Basic.Bean and Util.Beans.Methods.Method_Bean with record Faces : aliased ASF.Servlets.Faces.Faces_Servlet; Files : aliased ASF.Servlets.Files.File_Servlet; Redirect : aliased Redirect_Servlet; Config : ASF.Applications.Config; Changed : ASF.Applications.Config; Factory : ASF.Applications.Main.Application_Factory; Path : Ada.Strings.Unbounded.Unbounded_String; Database : ADO.Drivers.Connections.Configuration; Driver : Util.Beans.Objects.Object; Result : Util.Beans.Objects.Object; Root_User : Util.Beans.Objects.Object; Root_Passwd : Util.Beans.Objects.Object; Db_Host : Util.Beans.Objects.Object; Db_Port : Util.Beans.Objects.Object; Has_Error : Boolean := False; Status : State; end record; -- Get the value identified by the name. function Get_Value (From : in Application; Name : in String) return Util.Beans.Objects.Object; -- Set the value identified by the name. procedure Set_Value (From : in out Application; Name : in String; Value : in Util.Beans.Objects.Object); -- Get the database connection string to be used by the application. function Get_Database_URL (From : in Application) return String; -- Get the command to configure the database. function Get_Configure_Command (From : in Application) return String; -- Configure the database. procedure Configure_Database (From : in out Application; Outcome : in out Ada.Strings.Unbounded.Unbounded_String); -- Validate the database configuration parameters. procedure Validate (From : in out Application); -- Save the configuration. procedure Save (From : in out Application; Outcome : in out Ada.Strings.Unbounded.Unbounded_String); -- Finish the setup and exit the setup. procedure Finish (From : in out Application; Outcome : in out Ada.Strings.Unbounded.Unbounded_String); -- This bean provides some methods that can be used in a Method_Expression overriding function Get_Method_Bindings (From : in Application) return Util.Beans.Methods.Method_Binding_Array_Access; -- Enter in the application setup procedure Setup (App : in out Application; Config : in String; Server : in out ASF.Server.Container'Class); end AWA.Setup.Applications;
----------------------------------------------------------------------- -- awa-setup -- Setup and installation -- Copyright (C) 2016 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Strings.Unbounded; with ASF.Applications.Main; with ASF.Servlets.Faces; with ASF.Servlets.Files; with ASF.Requests; with ASF.Responses; with ASF.Server; with Util.Beans.Objects; with Util.Beans.Basic; with Util.Beans.Methods; with ADO.Drivers.Connections; package AWA.Setup.Applications is -- The <b>Servlet</b> represents the component that will handle -- an HTTP request received by the server. type Redirect_Servlet is new ASF.Servlets.Servlet with null record; overriding procedure Do_Get (Server : in Redirect_Servlet; Request : in out ASF.Requests.Request'Class; Response : in out ASF.Responses.Response'Class); -- The configuration state starts in the <tt>CONFIGURING</tt> state and moves to the -- <tt>STARTING</tt> state after the application is configured and it is started. -- Once the application is initialized and registered in the server container, the -- state is changed to <tt>READY</tt>. type Configure_State is (CONFIGURING, STARTING, READY); -- Maintains the state of the configuration between the main task and the http configuration -- requests. protected type State is -- Wait until the configuration is finished. entry Wait_Configuring; -- Wait until the server application is initialized and ready. entry Wait_Ready; -- Set the configuration state. procedure Set (V : in Configure_State); private Value : Configure_State := CONFIGURING; end State; type Application is new ASF.Applications.Main.Application and Util.Beans.Basic.Bean and Util.Beans.Methods.Method_Bean with record Faces : aliased ASF.Servlets.Faces.Faces_Servlet; Files : aliased ASF.Servlets.Files.File_Servlet; Redirect : aliased Redirect_Servlet; Config : ASF.Applications.Config; Changed : ASF.Applications.Config; Factory : ASF.Applications.Main.Application_Factory; Path : Ada.Strings.Unbounded.Unbounded_String; Database : ADO.Drivers.Connections.Configuration; Driver : Util.Beans.Objects.Object; Result : Util.Beans.Objects.Object; Root_User : Util.Beans.Objects.Object; Root_Passwd : Util.Beans.Objects.Object; Db_Host : Util.Beans.Objects.Object; Db_Port : Util.Beans.Objects.Object; Has_Error : Boolean := False; Status : State; end record; -- Get the value identified by the name. function Get_Value (From : in Application; Name : in String) return Util.Beans.Objects.Object; -- Set the value identified by the name. procedure Set_Value (From : in out Application; Name : in String; Value : in Util.Beans.Objects.Object); -- Get the database connection string to be used by the application. function Get_Database_URL (From : in Application) return String; -- Get the command to configure the database. function Get_Configure_Command (From : in Application) return String; -- Configure the database. procedure Configure_Database (From : in out Application; Outcome : in out Ada.Strings.Unbounded.Unbounded_String); -- Validate the database configuration parameters. procedure Validate (From : in out Application); -- Save the configuration. procedure Save (From : in out Application; Outcome : in out Ada.Strings.Unbounded.Unbounded_String); -- Finish the setup and exit the setup. procedure Finish (From : in out Application; Outcome : in out Ada.Strings.Unbounded.Unbounded_String); -- This bean provides some methods that can be used in a Method_Expression overriding function Get_Method_Bindings (From : in Application) return Util.Beans.Methods.Method_Binding_Array_Access; -- Enter in the application setup procedure Setup (App : in out Application; Config : in String; Server : in out ASF.Server.Container'Class); -- Configure the application by using the setup application, allowing the administrator to -- setup the application database, define the application admin parameters. After the -- configuration is done, register the application in the server container and start it. generic type Application_Type (<>) is new ASF.Servlets.Servlet_Registry with private; type Application_Access is access all Application_Type'Class; with procedure Initialize (App : in Application_Access; Config : in ASF.Applications.Config); procedure Configure (Server : in out ASF.Server.Container'Class; App : in Application_Access; Config : in String; URI : in String); end AWA.Setup.Applications;
Declare the Configure generic procedure to setup the configuration, wait for the configuration to be done and initialize and register the application
Declare the Configure generic procedure to setup the configuration, wait for the configuration to be done and initialize and register the application
Ada
apache-2.0
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
5c35566a4e6435e7f3be970bc2e49fa80f6787c3
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.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;
----------------------------------------------------------------------- -- 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.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;
Fix Query_Table to use the simple reference
Fix Query_Table to use the simple reference
Ada
apache-2.0
stcarrez/ada-ado
fbf59209e44faef45bfb4913e707a1ce3af79964
src/ado-configs.adb
src/ado-configs.adb
----------------------------------------------------------------------- -- ado-configs -- Database connection configuration -- Copyright (C) 2010, 2011, 2012, 2013, 2015, 2016, 2017, 2018 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Log.Loggers; with Ada.Strings.Fixed; package body ADO.Configs is use Ada.Strings.Fixed; Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("ADO.Configs"); -- ------------------------------ -- Set the connection URL to connect to the database. -- The driver connection is a string of the form: -- -- driver://[host][:port]/[database][?property1][=value1]... -- -- If the string is invalid or if the driver cannot be found, -- the Connection_Error exception is raised. -- ------------------------------ procedure Set_Connection (Config : in out Configuration; URI : in String) is Pos, Pos2, Slash_Pos, Next : Natural; Is_Hidden : Boolean; begin Config.URI := To_Unbounded_String (URI); Pos := Index (URI, "://"); if Pos <= URI'First then Log.Error ("Invalid connection URI: {0}", URI); raise Connection_Error with "Invalid URI: '" & URI & "'"; end if; Config.Driver := To_Unbounded_String (URI (URI'First .. Pos - 1)); 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 Config.Server := To_Unbounded_String (URI (Pos .. Pos2 - 1)); begin Config.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 Config.Port := 0; Config.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 Config.Database := To_Unbounded_String (URI (Slash_Pos + 1 .. Pos - 1)); elsif Pos = 0 and Slash_Pos + 1 < URI'Last then Config.Database := To_Unbounded_String (URI (Slash_Pos + 1 .. URI'Last)); else Config.Database := Null_Unbounded_String; end if; -- Parse the optional properties if Pos > Slash_Pos then Config.Log_URI := To_Unbounded_String (URI (URI'First .. Pos)); while Pos < URI'Last loop Pos2 := Index (URI, "=", Pos + 1); if Pos2 > Pos then Next := Index (URI, "&", Pos2 + 1); Append (Config.Log_URI, URI (Pos + 1 .. Pos2)); Is_Hidden := URI (Pos + 1 .. Pos2 - 1) = "password"; if Is_Hidden then Append (Config.Log_URI, "XXXXXXX"); end if; if Next > 0 then Config.Properties.Set (URI (Pos + 1 .. Pos2 - 1), URI (Pos2 + 1 .. Next - 1)); if not Is_Hidden then Append (Config.Log_URI, URI (Pos2 + 1 .. Next - 1)); end if; Append (Config.Log_URI, "&"); Pos := Next; else Config.Properties.Set (URI (Pos + 1 .. Pos2 - 1), URI (Pos2 + 1 .. URI'Last)); if not Is_Hidden then Append (Config.Log_URI, URI (Pos2 + 1 .. URI'Last)); end if; Pos := URI'Last; end if; else Config.Properties.Set (URI (Pos + 1 .. URI'Last), ""); Append (Config.Log_URI, URI (Pos + 1 .. URI'Last)); Pos := URI'Last; end if; end loop; else Config.Log_URI := Config.URI; end if; Log.Info ("Set connection URI: {0}", Config.Log_URI); end Set_Connection; -- ------------------------------ -- Get the connection URI that describes the database connection string. -- ------------------------------ function Get_URI (Config : in Configuration) return String is begin return To_String (Config.URI); end Get_URI; -- ------------------------------ -- Get the connection URI that describes the database connection string -- but the connection authentication is replaced by XXXX. -- ------------------------------ function Get_Log_URI (Config : in Configuration) return String is begin return To_String (Config.Log_URI); end Get_Log_URI; -- ------------------------------ -- Set a property on the datasource for the driver. -- The driver can retrieve the property to configure and open -- the database connection. -- ------------------------------ procedure Set_Property (Config : in out Configuration; Name : in String; Value : in String) is begin Config.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 (Config : in Configuration; Name : in String) return String is begin return Config.Properties.Get (Name, ""); end Get_Property; -- ------------------------------ -- Get the server hostname. -- ------------------------------ function Get_Server (Config : in Configuration) return String is begin return To_String (Config.Server); end Get_Server; -- ------------------------------ -- Set the server hostname. -- ------------------------------ procedure Set_Server (Config : in out Configuration; Server : in String) is begin Config.Server := To_Unbounded_String (Server); end Set_Server; -- ------------------------------ -- Set the server port. -- ------------------------------ procedure Set_Port (Config : in out Configuration; Port : in Natural) is begin Config.Port := Port; end Set_Port; -- ------------------------------ -- Get the server port. -- ------------------------------ function Get_Port (Config : in Configuration) return Natural is begin return Config.Port; end Get_Port; -- ------------------------------ -- Set the database name. -- ------------------------------ procedure Set_Database (Config : in out Configuration; Database : in String) is begin Config.Database := To_Unbounded_String (Database); end Set_Database; -- ------------------------------ -- Get the database name. -- ------------------------------ function Get_Database (Config : in Configuration) return String is begin return To_String (Config.Database); end Get_Database; -- ------------------------------ -- Get the database driver name. -- ------------------------------ function Get_Driver (Config : in Configuration) return String is begin return To_String (Config.Driver); end Get_Driver; -- Iterate over the configuration properties and execute the given procedure passing the -- property name and its value. procedure Iterate (Config : in Configuration; Process : access procedure (Name : in String; Item : in Util.Properties.Value)) is begin Config.Properties.Iterate (Process); end Iterate; end ADO.Configs;
----------------------------------------------------------------------- -- ado-configs -- Database connection configuration -- Copyright (C) 2010, 2011, 2012, 2013, 2015, 2016, 2017, 2018 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Log.Loggers; with Ada.Strings.Fixed; package body ADO.Configs is use Ada.Strings.Fixed; Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("ADO.Configs"); -- ------------------------------ -- Set the connection URL to connect to the database. -- The driver connection is a string of the form: -- -- driver://[host][:port]/[database][?property1][=value1]... -- -- If the string is invalid or if the driver cannot be found, -- the Connection_Error exception is raised. -- ------------------------------ procedure Set_Connection (Config : in out Configuration; URI : in String) is Pos, Pos2, Slash_Pos, Next : Natural; Is_Hidden : Boolean; begin Config.URI := To_Unbounded_String (URI); Pos := Index (URI, "://"); if Pos <= URI'First then Log.Error ("Invalid connection URI: {0}", URI); raise Connection_Error with "Invalid URI: '" & URI & "'"; end if; Config.Driver := To_Unbounded_String (URI (URI'First .. Pos - 1)); 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 Config.Server := To_Unbounded_String (URI (Pos .. Pos2 - 1)); begin Config.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 Config.Port := 0; Config.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 Config.Database := To_Unbounded_String (URI (Slash_Pos + 1 .. Pos - 1)); elsif Pos = 0 and Slash_Pos + 1 < URI'Last then Config.Database := To_Unbounded_String (URI (Slash_Pos + 1 .. URI'Last)); else Config.Database := Null_Unbounded_String; end if; -- Parse the optional properties if Pos > Slash_Pos then Config.Log_URI := To_Unbounded_String (URI (URI'First .. Pos)); while Pos < URI'Last loop Pos2 := Index (URI, "=", Pos + 1); if Pos2 > Pos then Next := Index (URI, "&", Pos2 + 1); Append (Config.Log_URI, URI (Pos + 1 .. Pos2)); Is_Hidden := URI (Pos + 1 .. Pos2 - 1) = "password"; if Is_Hidden then Append (Config.Log_URI, "XXXXXXX"); end if; if Next > 0 then Config.Properties.Set (URI (Pos + 1 .. Pos2 - 1), URI (Pos2 + 1 .. Next - 1)); if not Is_Hidden then Append (Config.Log_URI, URI (Pos2 + 1 .. Next - 1)); end if; Append (Config.Log_URI, "&"); Pos := Next; else Config.Properties.Set (URI (Pos + 1 .. Pos2 - 1), URI (Pos2 + 1 .. URI'Last)); if not Is_Hidden then Append (Config.Log_URI, URI (Pos2 + 1 .. URI'Last)); end if; Pos := URI'Last; end if; else Config.Properties.Set (URI (Pos + 1 .. URI'Last), ""); Append (Config.Log_URI, URI (Pos + 1 .. URI'Last)); Pos := URI'Last; end if; end loop; else Config.Log_URI := Config.URI; end if; Log.Info ("Set connection URI: {0}", Config.Log_URI); end Set_Connection; -- ------------------------------ -- Get the connection URI that describes the database connection string. -- ------------------------------ function Get_URI (Config : in Configuration) return String is begin return To_String (Config.URI); end Get_URI; -- ------------------------------ -- Get the connection URI that describes the database connection string -- but the connection authentication is replaced by XXXX. -- ------------------------------ function Get_Log_URI (Config : in Configuration) return String is begin return To_String (Config.Log_URI); end Get_Log_URI; -- ------------------------------ -- Set a property on the datasource for the driver. -- The driver can retrieve the property to configure and open -- the database connection. -- ------------------------------ procedure Set_Property (Config : in out Configuration; Name : in String; Value : in String) is begin Config.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 (Config : in Configuration; Name : in String) return String is begin return Config.Properties.Get (Name, ""); end Get_Property; -- ------------------------------ -- Returns true if the configuration property is set to true/on. -- ------------------------------ function Is_On (Config : in Configuration; Name : in String) return Boolean is Value : constant String := Config.Get_Property (Name); begin return Value = "on" or Value = "true" or Value = "1"; end Is_On; -- ------------------------------ -- Get the server hostname. -- ------------------------------ function Get_Server (Config : in Configuration) return String is begin return To_String (Config.Server); end Get_Server; -- ------------------------------ -- Set the server hostname. -- ------------------------------ procedure Set_Server (Config : in out Configuration; Server : in String) is begin Config.Server := To_Unbounded_String (Server); end Set_Server; -- ------------------------------ -- Set the server port. -- ------------------------------ procedure Set_Port (Config : in out Configuration; Port : in Natural) is begin Config.Port := Port; end Set_Port; -- ------------------------------ -- Get the server port. -- ------------------------------ function Get_Port (Config : in Configuration) return Natural is begin return Config.Port; end Get_Port; -- ------------------------------ -- Set the database name. -- ------------------------------ procedure Set_Database (Config : in out Configuration; Database : in String) is begin Config.Database := To_Unbounded_String (Database); end Set_Database; -- ------------------------------ -- Get the database name. -- ------------------------------ function Get_Database (Config : in Configuration) return String is begin return To_String (Config.Database); end Get_Database; -- ------------------------------ -- Get the database driver name. -- ------------------------------ function Get_Driver (Config : in Configuration) return String is begin return To_String (Config.Driver); end Get_Driver; -- Iterate over the configuration properties and execute the given procedure passing the -- property name and its value. procedure Iterate (Config : in Configuration; Process : access procedure (Name : in String; Item : in Util.Properties.Value)) is begin Config.Properties.Iterate (Process); end Iterate; end ADO.Configs;
Implement Is_On function
Implement Is_On function
Ada
apache-2.0
stcarrez/ada-ado
6980063419ebba2779e2fb001355c41bb360bbb9
src/babel-files.adb
src/babel-files.adb
-- bkp-files -- File and directories ----------------------------------------------------------------------- -- Copyright (C) 2014 Stephane.Carrez -- Written by Stephane.Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Log.Loggers; with Util.Files; with Util.Encoders.Base16; package body Babel.Files is Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("Bkp.Files"); Hex_Encoder : Util.Encoders.Base16.Encoder; -- ------------------------------ -- Allocate a File_Type entry with the given name for the directory. -- ------------------------------ function Allocate (Name : in String; Dir : in Directory_Type) return File_Type is use Ada.Strings.Unbounded; Result : constant File_Type := new File '(Len => Name'Length, Id => NO_IDENTIFIER, Dir => Dir, Name => Name, others => <>); begin return Result; end Allocate; -- ------------------------------ -- Allocate a Directory_Type entry with the given name for the directory. -- ------------------------------ function Allocate (Name : in String; Dir : in Directory_Type) return Directory_Type is use Ada.Strings.Unbounded; Result : constant Directory_Type := new Directory '(Len => Name'Length, Id => NO_IDENTIFIER, Parent => Dir, Name => Name, others => <>); begin if Dir /= null then Result.Path := To_Unbounded_String (Util.Files.Compose (To_String (Dir.Path), Name)); else Result.Path := To_Unbounded_String (Name); end if; return Result; end Allocate; -- ------------------------------ -- Return true if the file was modified and need a backup. -- ------------------------------ function Is_Modified (Element : in File_Type) return Boolean is use type ADO.Identifier; begin if Element.Id = NO_IDENTIFIER then return True; elsif (Element.Status and FILE_MODIFIED) /= 0 then return True; else return False; end if; end Is_Modified; -- ------------------------------ -- Set the file as modified. -- ------------------------------ procedure Set_Modified (Element : in File_Type) is begin Element.Status := Element.Status or FILE_MODIFIED; end Set_Modified; -- ------------------------------ -- Set the SHA1 signature that was computed for this file. -- If the computed signature is different from the current signature, -- the FILE_MODIFIED flag is set on the file. The FILE_HAS_SHA1 flag -- is set on the file. -- ------------------------------ procedure Set_Signature (Element : in File_Type; Signature : in Util.Encoders.SHA1.Hash_Array) is use type Util.Encoders.SHA1.Hash_Array; begin if (Element.Status and FILE_HAS_SHA1) /= 0 and then Element.SHA1 /= Signature then Element.Status := Element.Status or FILE_MODIFIED; end if; Element.Status := Element.Status or FILE_HAS_SHA1; Element.SHA1 := Signature; end Set_Signature; -- ------------------------------ -- Set the file size. If the new size is different, the FILE_MODIFIED -- flag is set on the file. -- ------------------------------ procedure Set_Size (Element : in File_Type; Size : in File_Size) is begin if Element.Size /= Size then Element.Size := Size; Element.Status := Element.Status or FILE_MODIFIED; end if; end Set_Size; -- ------------------------------ -- Return the path for the file. -- ------------------------------ function Get_Path (Element : in File_Type) return String is begin if Element.Dir = null then return Element.Name; else return Util.Files.Compose (Get_Path (Element.Dir), Element.Name); end if; end Get_Path; -- ------------------------------ -- Return the path for the directory. -- ------------------------------ function Get_Path (Element : in Directory_Type) return String is begin return Ada.Strings.Unbounded.To_String (Element.Path); end Get_Path; -- ------------------------------ -- Return the SHA1 signature computed for the file. -- ------------------------------ function Get_SHA1 (Element : in File_Type) return String is begin return Hex_Encoder.Transform (Element.SHA1); end Get_SHA1; -- ------------------------------ -- Add the file with the given name in the container. -- ------------------------------ overriding procedure Add_File (Into : in out Default_Container; Element : in File_Type) is begin Into.Files.Append (Element); end Add_File; -- ------------------------------ -- Add the directory with the given name in the container. -- ------------------------------ overriding procedure Add_Directory (Into : in out Default_Container; Element : in Directory_Type) is begin Into.Dirs.Append (Element); end Add_Directory; -- ------------------------------ -- Create a new file instance with the given name in the container. -- ------------------------------ overriding function Create (Into : in Default_Container; Name : in String) return File_Type is begin return Allocate (Name => Name, Dir => Into.Current); end Create; -- ------------------------------ -- Create a new directory instance with the given name in the container. -- ------------------------------ overriding function Create (Into : in Default_Container; Name : in String) return Directory_Type is begin return Allocate (Name => Name, Dir => Into.Current); end Create; -- ------------------------------ -- Find the file with the given name in this file container. -- Returns NO_FILE if the file was not found. -- ------------------------------ overriding function Find (From : in Default_Container; Name : in String) return File_Type is pragma Unreferenced (From, Name); begin return NO_FILE; end Find; -- ------------------------------ -- Find the directory with the given name in this file container. -- Returns NO_DIRECTORY if the directory was not found. -- ------------------------------ overriding function Find (From : in Default_Container; Name : in String) return Directory_Type is pragma Unreferenced (From, Name); begin return NO_DIRECTORY; end Find; -- ------------------------------ -- Set the directory object associated with the container. -- ------------------------------ procedure Set_Directory (Into : in out Default_Container; Directory : in Directory_Type) is begin Into.Current := Directory; Into.Files.Clear; Into.Dirs.Clear; end Set_Directory; -- ------------------------------ -- Execute the Process procedure on each directory found in the container. -- ------------------------------ overriding procedure Each_Directory (Container : in Default_Container; Process : not null access procedure (Dir : in Directory_Type)) is Iter : Directory_Vectors.Cursor := Container.Dirs.First; begin while Directory_Vectors.Has_Element (Iter) loop Process (Directory_Vectors.Element (Iter)); Directory_Vectors.Next (Iter); end loop; end Each_Directory; -- ------------------------------ -- Execute the Process procedure on each file found in the container. -- ------------------------------ overriding procedure Each_File (Container : in Default_Container; Process : not null access procedure (F : in File_Type)) is Iter : File_Vectors.Cursor := Container.Files.First; begin while File_Vectors.Has_Element (Iter) loop Process (File_Vectors.Element (Iter)); File_Vectors.Next (Iter); end loop; end Each_File; end Babel.Files;
-- bkp-files -- File and directories ----------------------------------------------------------------------- -- Copyright (C) 2014 Stephane.Carrez -- Written by Stephane.Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Log.Loggers; with Util.Files; with Util.Encoders.Base16; package body Babel.Files is Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("Bkp.Files"); Hex_Encoder : Util.Encoders.Base16.Encoder; -- ------------------------------ -- Compare two files on their name and directory. -- ------------------------------ function "<" (Left, Right : in File_Type) return Boolean is use type Ada.Strings.Unbounded.Unbounded_String; begin if Left = NO_FILE then return False; elsif Right = NO_FILE then return True; elsif Left.Dir = Right.Dir then return Left.Name < Right.Name; elsif Left.Dir = NO_DIRECTORY then return True; elsif Right.Dir = NO_DIRECTORY then return False; else return Left.Dir.Path < Right.Dir.Path; end if; end "<"; -- ------------------------------ -- Allocate a File_Type entry with the given name for the directory. -- ------------------------------ function Allocate (Name : in String; Dir : in Directory_Type) return File_Type is use Ada.Strings.Unbounded; Result : constant File_Type := new File '(Len => Name'Length, Id => NO_IDENTIFIER, Dir => Dir, Name => Name, others => <>); begin return Result; end Allocate; -- ------------------------------ -- Allocate a Directory_Type entry with the given name for the directory. -- ------------------------------ function Allocate (Name : in String; Dir : in Directory_Type) return Directory_Type is use Ada.Strings.Unbounded; Result : constant Directory_Type := new Directory '(Len => Name'Length, Id => NO_IDENTIFIER, Parent => Dir, Name => Name, others => <>); begin if Dir /= null then Result.Path := To_Unbounded_String (Util.Files.Compose (To_String (Dir.Path), Name)); else Result.Path := To_Unbounded_String (Name); end if; return Result; end Allocate; -- ------------------------------ -- Return true if the file was modified and need a backup. -- ------------------------------ function Is_Modified (Element : in File_Type) return Boolean is use type ADO.Identifier; begin if Element.Id = NO_IDENTIFIER then return True; elsif (Element.Status and FILE_MODIFIED) /= 0 then return True; else return False; end if; end Is_Modified; -- ------------------------------ -- Set the file as modified. -- ------------------------------ procedure Set_Modified (Element : in File_Type) is begin Element.Status := Element.Status or FILE_MODIFIED; end Set_Modified; -- ------------------------------ -- Set the SHA1 signature that was computed for this file. -- If the computed signature is different from the current signature, -- the FILE_MODIFIED flag is set on the file. The FILE_HAS_SHA1 flag -- is set on the file. -- ------------------------------ procedure Set_Signature (Element : in File_Type; Signature : in Util.Encoders.SHA1.Hash_Array) is use type Util.Encoders.SHA1.Hash_Array; begin if (Element.Status and FILE_HAS_SHA1) /= 0 and then Element.SHA1 /= Signature then Element.Status := Element.Status or FILE_MODIFIED; end if; Element.Status := Element.Status or FILE_HAS_SHA1; Element.SHA1 := Signature; end Set_Signature; -- ------------------------------ -- Set the file size. If the new size is different, the FILE_MODIFIED -- flag is set on the file. -- ------------------------------ procedure Set_Size (Element : in File_Type; Size : in File_Size) is begin if Element.Size /= Size then Element.Size := Size; Element.Status := Element.Status or FILE_MODIFIED; end if; end Set_Size; -- ------------------------------ -- Return the path for the file. -- ------------------------------ function Get_Path (Element : in File_Type) return String is begin if Element.Dir = null then return Element.Name; else return Util.Files.Compose (Get_Path (Element.Dir), Element.Name); end if; end Get_Path; -- ------------------------------ -- Return the path for the directory. -- ------------------------------ function Get_Path (Element : in Directory_Type) return String is begin return Ada.Strings.Unbounded.To_String (Element.Path); end Get_Path; -- ------------------------------ -- Return the SHA1 signature computed for the file. -- ------------------------------ function Get_SHA1 (Element : in File_Type) return String is begin return Hex_Encoder.Transform (Element.SHA1); end Get_SHA1; -- ------------------------------ -- Add the file with the given name in the container. -- ------------------------------ overriding procedure Add_File (Into : in out Default_Container; Element : in File_Type) is begin Into.Files.Append (Element); end Add_File; -- ------------------------------ -- Add the directory with the given name in the container. -- ------------------------------ overriding procedure Add_Directory (Into : in out Default_Container; Element : in Directory_Type) is begin Into.Dirs.Append (Element); end Add_Directory; -- ------------------------------ -- Create a new file instance with the given name in the container. -- ------------------------------ overriding function Create (Into : in Default_Container; Name : in String) return File_Type is begin return Allocate (Name => Name, Dir => Into.Current); end Create; -- ------------------------------ -- Create a new directory instance with the given name in the container. -- ------------------------------ overriding function Create (Into : in Default_Container; Name : in String) return Directory_Type is begin return Allocate (Name => Name, Dir => Into.Current); end Create; -- ------------------------------ -- Find the file with the given name in this file container. -- Returns NO_FILE if the file was not found. -- ------------------------------ overriding function Find (From : in Default_Container; Name : in String) return File_Type is pragma Unreferenced (From, Name); begin return NO_FILE; end Find; -- ------------------------------ -- Find the directory with the given name in this file container. -- Returns NO_DIRECTORY if the directory was not found. -- ------------------------------ overriding function Find (From : in Default_Container; Name : in String) return Directory_Type is pragma Unreferenced (From, Name); begin return NO_DIRECTORY; end Find; -- ------------------------------ -- Set the directory object associated with the container. -- ------------------------------ procedure Set_Directory (Into : in out Default_Container; Directory : in Directory_Type) is begin Into.Current := Directory; Into.Files.Clear; Into.Dirs.Clear; end Set_Directory; -- ------------------------------ -- Execute the Process procedure on each directory found in the container. -- ------------------------------ overriding procedure Each_Directory (Container : in Default_Container; Process : not null access procedure (Dir : in Directory_Type)) is Iter : Directory_Vectors.Cursor := Container.Dirs.First; begin while Directory_Vectors.Has_Element (Iter) loop Process (Directory_Vectors.Element (Iter)); Directory_Vectors.Next (Iter); end loop; end Each_Directory; -- ------------------------------ -- Execute the Process procedure on each file found in the container. -- ------------------------------ overriding procedure Each_File (Container : in Default_Container; Process : not null access procedure (F : in File_Type)) is Iter : File_Vectors.Cursor := Container.Files.First; begin while File_Vectors.Has_Element (Iter) loop Process (File_Vectors.Element (Iter)); File_Vectors.Next (Iter); end loop; end Each_File; end Babel.Files;
Implement the < operation to compare two File_Type
Implement the < operation to compare two File_Type
Ada
apache-2.0
stcarrez/babel
1a999614af4680bd7f6db1b7b5ba4bc669740872
mat/src/mat-targets.ads
mat/src/mat-targets.ads
----------------------------------------------------------------------- -- Targets - Representation of target information -- 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 MAT.Types; with Ada.Strings.Unbounded; with MAT.Memory.Targets; with MAT.Readers; package MAT.Targets is type Target_Type is tagged limited private; type Target_Type_Access is access all Target_Type'Class; -- Initialize the target object to manage the memory slots, the stack frames -- and setup the reader to analyze the memory and other events. procedure Initialize (Target : in out Target_Type; Reader : in out MAT.Readers.Manager_Base'Class); private type Target_Type is tagged limited record Memory : MAT.Memory.Targets.Target_Memory; end record; end MAT.Targets;
----------------------------------------------------------------------- -- Targets - Representation of target information -- 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 MAT.Types; with Ada.Strings.Unbounded; with MAT.Memory.Targets; with MAT.Symbols.Targets; with MAT.Readers; package MAT.Targets is -- type Target_Type is tagged limited private; type Target_Type is tagged limited record Memory : MAT.Memory.Targets.Target_Memory; Symbols : MAT.Symbols.Targets.Target_Symbols; end record; type Target_Type_Access is access all Target_Type'Class; -- Initialize the target object to manage the memory slots, the stack frames -- and setup the reader to analyze the memory and other events. procedure Initialize (Target : in out Target_Type; Reader : in out MAT.Readers.Manager_Base'Class); -- -- private -- -- type Target_Type is tagged limited record -- Memory : MAT.Memory.Targets.Target_Memory; -- end record; end MAT.Targets;
Add the symbols in the target object
Add the symbols in the target object
Ada
apache-2.0
stcarrez/mat,stcarrez/mat,stcarrez/mat
767d393a1c80c8b196be8a54dab596106f7aaf7a
samples/render.adb
samples/render.adb
----------------------------------------------------------------------- -- render -- Wiki rendering example -- Copyright (C) 2015, 2016, 2020, 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.IO_Exceptions; with Ada.Strings.Unbounded; with Ada.Directories; with Ada.Command_Line; with Wiki.Documents; with Wiki.Parsers; with Wiki.Filters.TOC; with Wiki.Filters.Html; with Wiki.Filters.Autolink; with Wiki.Plugins.Templates; with Wiki.Render.Html; with Wiki.Render.Text; with Wiki.Streams.Text_IO; with Wiki.Streams.Html.Text_IO; procedure Render is use Ada.Strings.Unbounded; procedure Usage; procedure Render_Html (Doc : in out Wiki.Documents.Document; Style : in Unbounded_String); procedure Render_Text (Doc : in out Wiki.Documents.Document); Arg_Count : constant Natural := Ada.Command_Line.Argument_Count; Count : Natural := 0; Html_Mode : Boolean := True; Html_Toc : Boolean := False; Syntax : Wiki.Wiki_Syntax := Wiki.SYNTAX_MARKDOWN; Style : Unbounded_String; Indent : Natural := 3; procedure Usage is begin Ada.Text_IO.Put_Line ("Render a wiki text file into HTML (default) or text"); Ada.Text_IO.Put_Line ("Usage: render [-t] [-m] [-M] [-H] [-d] [-c] [-s style] {wiki-file}"); Ada.Text_IO.Put_Line (" -t Render to text only"); Ada.Text_IO.Put_Line (" -m Render a Markdown wiki content"); Ada.Text_IO.Put_Line (" -M Render a Mediawiki wiki content"); Ada.Text_IO.Put_Line (" -T Render a Textile wiki content"); Ada.Text_IO.Put_Line (" -H Render a HTML wiki content"); Ada.Text_IO.Put_Line (" -d Render a Dotclear wiki content"); Ada.Text_IO.Put_Line (" -g Render a Google wiki content"); Ada.Text_IO.Put_Line (" -c Render a Creole wiki content"); Ada.Text_IO.Put_Line (" -s style Use the CSS style file"); Ada.Command_Line.Set_Exit_Status (Ada.Command_Line.Failure); end Usage; procedure Render_Html (Doc : in out Wiki.Documents.Document; Style : in Unbounded_String) is Output : aliased Wiki.Streams.Html.Text_IO.Html_Output_Stream; Renderer : aliased Wiki.Render.Html.Html_Renderer; begin Output.Set_Indent_Level (Indent); if Length (Style) > 0 then Output.Start_Element ("html"); Output.Start_Element ("head"); Output.Start_Element ("link"); Output.Write_Attribute ("type", "text/css"); Output.Write_Attribute ("rel", "stylesheet"); Output.Write_Attribute ("href", To_String (Style)); Output.End_Element ("link"); Output.End_Element ("head"); Output.Start_Element ("body"); end if; Renderer.Set_Output_Stream (Output'Unchecked_Access); Renderer.Set_Render_TOC (Html_Toc); Renderer.Render (Doc); if Length (Style) > 0 then Output.End_Element ("body"); Output.End_Element ("html"); end if; end Render_Html; procedure Render_Text (Doc : in out Wiki.Documents.Document) is Output : aliased Wiki.Streams.Text_IO.File_Output_Stream; Renderer : aliased Wiki.Render.Text.Text_Renderer; begin Renderer.Set_Output_Stream (Output'Unchecked_Access); Renderer.Render (Doc); end Render_Text; procedure Render_File (Name : in String) is Input : aliased Wiki.Streams.Text_IO.File_Input_Stream; Filter : aliased Wiki.Filters.Html.Html_Filter_Type; Autolink : aliased Wiki.Filters.Autolink.Autolink_Filter; Template : aliased Wiki.Plugins.Templates.File_Template_Plugin; TOC : aliased Wiki.Filters.TOC.TOC_Filter; Doc : Wiki.Documents.Document; Engine : Wiki.Parsers.Parser; begin Count := Count + 1; Template.Set_Template_Path (Ada.Directories.Containing_Directory (Name)); -- Open the file and parse it (assume UTF-8). if Name /= "--" then Input.Open (Name, "WCEM=8"); end if; Engine.Set_Plugin_Factory (Template'Unchecked_Access); Engine.Add_Filter (TOC'Unchecked_Access); Engine.Add_Filter (Autolink'Unchecked_Access); Engine.Add_Filter (Filter'Unchecked_Access); Engine.Set_Syntax (Syntax); Engine.Parse (Input'Unchecked_Access, Doc); -- Render the document in text or HTML. if Html_Mode then Render_Html (Doc, Style); else Render_Text (Doc); end if; exception when Ada.IO_Exceptions.Name_Error => Ada.Text_IO.Put_Line ("Cannot read file '" & Name & "'"); Ada.Command_Line.Set_Exit_Status (Ada.Command_Line.Failure); end Render_File; begin for I in 1 .. Arg_Count loop declare Param : constant String := Ada.Command_Line.Argument (I); begin if Param = "-m" then Syntax := Wiki.SYNTAX_MARKDOWN; elsif Param = "-M" then Syntax := Wiki.SYNTAX_MEDIA_WIKI; elsif Param = "-c" then Syntax := Wiki.SYNTAX_CREOLE; elsif Param = "-d" then Syntax := Wiki.SYNTAX_DOTCLEAR; elsif Param = "-H" then Syntax := Wiki.SYNTAX_HTML; elsif Param = "-T" then Syntax := Wiki.SYNTAX_TEXTILE; elsif Param = "-g" then Syntax := Wiki.SYNTAX_GOOGLE; elsif Param = "-t" then Html_Mode := False; elsif Param = "-z" then Html_Toc := True; elsif Param = "-s" then Style := To_Unbounded_String (Param); elsif Param = "--" then Render_File (Param); elsif Param = "-0" then Indent := 0; elsif Param = "-1" then Indent := 1; elsif Param = "-2" then Indent := 2; elsif Param (Param'First) = '-' then Usage; return; else Render_File (Param); end if; end; end loop; if Count = 0 then Usage; end if; end Render;
----------------------------------------------------------------------- -- render -- Wiki rendering example -- Copyright (C) 2015, 2016, 2020, 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.IO_Exceptions; with Ada.Strings.Unbounded; with Ada.Directories; with Ada.Command_Line; with Wiki.Documents; with Wiki.Parsers; with Wiki.Strings; with Wiki.Filters.TOC; with Wiki.Filters.Html; with Wiki.Filters.Autolink; with Wiki.Plugins.Templates; with Wiki.Render.Html; with Wiki.Render.Text; with Wiki.Streams.Text_IO; with Wiki.Streams.Html.Text_IO; with Wiki.Nodes.Dump; procedure Render is use Ada.Strings.Unbounded; procedure Usage; procedure Render_Html (Doc : in out Wiki.Documents.Document; Style : in Unbounded_String); procedure Render_Text (Doc : in out Wiki.Documents.Document); Arg_Count : constant Natural := Ada.Command_Line.Argument_Count; Count : Natural := 0; Html_Mode : Boolean := True; Html_Toc : Boolean := False; Syntax : Wiki.Wiki_Syntax := Wiki.SYNTAX_MARKDOWN; Style : Unbounded_String; Indent : Natural := 3; Dump_Tree : Boolean := False; procedure Usage is begin Ada.Text_IO.Put_Line ("Render a wiki text file into HTML (default) or text"); Ada.Text_IO.Put_Line ("Usage: render [-t] [-m] [-M] [-H] [-d] [-c] [-s style] {wiki-file}"); Ada.Text_IO.Put_Line (" -t Render to text only"); Ada.Text_IO.Put_Line (" -m Render a Markdown wiki content"); Ada.Text_IO.Put_Line (" -M Render a Mediawiki wiki content"); Ada.Text_IO.Put_Line (" -T Render a Textile wiki content"); Ada.Text_IO.Put_Line (" -H Render a HTML wiki content"); Ada.Text_IO.Put_Line (" -d Render a Dotclear wiki content"); Ada.Text_IO.Put_Line (" -g Render a Google wiki content"); Ada.Text_IO.Put_Line (" -c Render a Creole wiki content"); Ada.Text_IO.Put_Line (" -s style Use the CSS style file"); Ada.Command_Line.Set_Exit_Status (Ada.Command_Line.Failure); end Usage; procedure Render_Html (Doc : in out Wiki.Documents.Document; Style : in Unbounded_String) is Output : aliased Wiki.Streams.Html.Text_IO.Html_Output_Stream; Renderer : aliased Wiki.Render.Html.Html_Renderer; begin Output.Set_Indent_Level (Indent); if Length (Style) > 0 then Output.Start_Element ("html"); Output.Start_Element ("head"); Output.Start_Element ("link"); Output.Write_Attribute ("type", "text/css"); Output.Write_Attribute ("rel", "stylesheet"); Output.Write_Attribute ("href", To_String (Style)); Output.End_Element ("link"); Output.End_Element ("head"); Output.Start_Element ("body"); end if; Renderer.Set_Output_Stream (Output'Unchecked_Access); Renderer.Set_Render_TOC (Html_Toc); Renderer.Render (Doc); if Length (Style) > 0 then Output.End_Element ("body"); Output.End_Element ("html"); end if; end Render_Html; procedure Render_Text (Doc : in out Wiki.Documents.Document) is Output : aliased Wiki.Streams.Text_IO.File_Output_Stream; Renderer : aliased Wiki.Render.Text.Text_Renderer; begin Renderer.Set_Output_Stream (Output'Unchecked_Access); Renderer.Render (Doc); end Render_Text; procedure Dump (Doc : in Wiki.Documents.Document) is procedure Write (Indent : in Positive; Line : in Wiki.Strings.WString) is S : constant String := Wiki.Strings.To_String (Line); begin Ada.Text_IO.Set_Col (Ada.Text_Io.Count (Indent)); Ada.Text_IO.Put_Line (S); end Write; procedure Dump is new Wiki.Nodes.Dump (Write); begin Doc.Iterate (Dump'Access); end Dump; procedure Render_File (Name : in String) is Input : aliased Wiki.Streams.Text_IO.File_Input_Stream; Filter : aliased Wiki.Filters.Html.Html_Filter_Type; Autolink : aliased Wiki.Filters.Autolink.Autolink_Filter; Template : aliased Wiki.Plugins.Templates.File_Template_Plugin; TOC : aliased Wiki.Filters.TOC.TOC_Filter; Doc : Wiki.Documents.Document; Engine : Wiki.Parsers.Parser; begin Count := Count + 1; Template.Set_Template_Path (Ada.Directories.Containing_Directory (Name)); -- Open the file and parse it (assume UTF-8). if Name /= "--" then Input.Open (Name, "WCEM=8"); end if; Engine.Set_Plugin_Factory (Template'Unchecked_Access); Engine.Add_Filter (TOC'Unchecked_Access); Engine.Add_Filter (Autolink'Unchecked_Access); Engine.Add_Filter (Filter'Unchecked_Access); Engine.Set_Syntax (Syntax); Engine.Parse (Input'Unchecked_Access, Doc); -- Render the document in text or HTML. if Dump_Tree then Dump (Doc); elsif Html_Mode then Render_Html (Doc, Style); else Render_Text (Doc); end if; exception when Ada.IO_Exceptions.Name_Error => Ada.Text_IO.Put_Line ("Cannot read file '" & Name & "'"); Ada.Command_Line.Set_Exit_Status (Ada.Command_Line.Failure); end Render_File; begin for I in 1 .. Arg_Count loop declare Param : constant String := Ada.Command_Line.Argument (I); begin if Param = "-m" then Syntax := Wiki.SYNTAX_MARKDOWN; elsif Param = "-M" then Syntax := Wiki.SYNTAX_MEDIA_WIKI; elsif Param = "-c" then Syntax := Wiki.SYNTAX_CREOLE; elsif Param = "-d" then Syntax := Wiki.SYNTAX_DOTCLEAR; elsif Param = "-H" then Syntax := Wiki.SYNTAX_HTML; elsif Param = "-T" then Syntax := Wiki.SYNTAX_TEXTILE; elsif Param = "-g" then Syntax := Wiki.SYNTAX_GOOGLE; elsif Param = "-t" then Html_Mode := False; elsif Param = "-z" then Html_Toc := True; elsif Param = "-s" then Style := To_Unbounded_String (Param); elsif Param = "--" then Render_File (Param); elsif Param = "-0" then Indent := 0; elsif Param = "-1" then Indent := 1; elsif Param = "-2" then Indent := 2; elsif Param = "-dump" then Dump_Tree := True; elsif Param (Param'First) = '-' then Usage; return; else Render_File (Param); end if; end; end loop; if Count = 0 then Usage; end if; end Render;
Add a -dump option to dump the document tree
Add a -dump option to dump the document tree
Ada
apache-2.0
stcarrez/ada-wiki,stcarrez/ada-wiki
01d0967d9267f214d72e2e900a0c4cece1bebdfb
regtests/security-policies-tests.adb
regtests/security-policies-tests.adb
----------------------------------------------------------------------- -- Security-policies-tests - Unit tests for Security.Permissions -- Copyright (C) 2011, 2012 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Tests; with Util.Files; with Util.Test_Caller; with Util.Measures; with Security.Contexts; with Security.Policies.Roles; with Security.Permissions.Tests; package body Security.Policies.Tests is use Util.Tests; package Caller is new Util.Test_Caller (Test, "Security.Policies"); procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is begin Caller.Add_Test (Suite, "Test Security.Permissions.Create_Role", Test_Create_Role'Access); Caller.Add_Test (Suite, "Test Security.Permissions.Has_Permission", Test_Has_Permission'Access); Caller.Add_Test (Suite, "Test Security.Permissions.Read_Policy (empty)", Test_Read_Empty_Policy'Access); Caller.Add_Test (Suite, "Test Security.Policies.Add_Policy", Test_Get_Role_Policy'Access); Caller.Add_Test (Suite, "Test Security.Policies.Get_Policy", Test_Get_Role_Policy'Access); Caller.Add_Test (Suite, "Test Security.Policies.Roles.Get_Role_Policy", Test_Get_Role_Policy'Access); Caller.Add_Test (Suite, "Test Security.Policies.Read_Policy", Test_Read_Policy'Access); Caller.Add_Test (Suite, "Test Security.Policies.Roles.Set_Roles", Test_Set_Roles'Access); Caller.Add_Test (Suite, "Test Security.Policies.Roles.Set_Roles (invalid)", Test_Set_Invalid_Roles'Access); -- These tests are identical but registered under different names -- for the test documentation. Caller.Add_Test (Suite, "Test Security.Contexts.Has_Permission", Test_Role_Policy'Access); Caller.Add_Test (Suite, "Test Security.Controllers.Roles.Has_Permission", Test_Role_Policy'Access); Caller.Add_Test (Suite, "Test Security.Permissions.Role_Policy", Test_Role_Policy'Access); end Add_Tests; -- ------------------------------ -- Get the roles assigned to the user. -- ------------------------------ function Get_Roles (User : in Test_Principal) return Roles.Role_Map is begin return User.Roles; end Get_Roles; -- ------------------------------ -- Get the principal name. -- ------------------------------ function Get_Name (From : in Test_Principal) return String is begin return Util.Strings.To_String (From.Name); end Get_Name; -- ------------------------------ -- Test Create_Role and Get_Role_Name -- ------------------------------ procedure Test_Create_Role (T : in out Test) is use Security.Policies.Roles; M : Security.Policies.Roles.Role_Policy; Role : Role_Type; begin M.Create_Role (Name => "admin", Role => Role); Assert_Equals (T, "admin", M.Get_Role_Name (Role), "Invalid name"); for I in Role + 1 .. Role_Type'Last loop declare Name : constant String := "admin-" & Role_Type'Image (I); Role2 : Role_Type; begin Role2 := M.Find_Role ("admin"); T.Assert (Role2 = Role, "Find_Role returned an invalid role"); M.Create_Role (Name => Name, Role => Role2); Assert_Equals (T, Name, M.Get_Role_Name (Role2), "Invalid name"); end; end loop; end Test_Create_Role; -- ------------------------------ -- Test Set_Roles -- ------------------------------ procedure Test_Set_Roles (T : in out Test) is use Security.Policies.Roles; M : Security.Policies.Roles.Role_Policy; Admin : Role_Type; Manager : Role_Type; Map : Role_Map := (others => False); begin M.Create_Role (Name => "manager", Role => Manager); M.Create_Role (Name => "admin", Role => Admin); Assert_Equals (T, "admin", M.Get_Role_Name (Admin), "Invalid name"); T.Assert (not Map (Admin), "The admin role must not set in the map"); M.Set_Roles ("admin", Map); T.Assert (Map (Admin), "The admin role is not set in the map"); T.Assert (not Map (Manager), "The manager role must not be set in the map"); Map := (others => False); M.Set_Roles ("manager,admin", Map); T.Assert (Map (Admin), "The admin role is not set in the map"); T.Assert (Map (Manager), "The manager role is not set in the map"); end Test_Set_Roles; -- ------------------------------ -- Test Set_Roles on an invalid role name -- ------------------------------ procedure Test_Set_Invalid_Roles (T : in out Test) is use Security.Policies.Roles; M : Security.Policies.Roles.Role_Policy; Map : Role_Map := (others => False); begin M.Set_Roles ("manager,admin", Map); T.Assert (False, "No exception was raised"); exception when E : Security.Policies.Roles.Invalid_Name => null; end Test_Set_Invalid_Roles; -- ------------------------------ -- Test Has_Permission -- ------------------------------ procedure Test_Has_Permission (T : in out Test) is M : Security.Policies.Policy_Manager (1); -- Perm : Permissions.Permission_Type; User : Test_Principal; begin -- T.Assert (not M.Has_Permission (User, 1), "User has a non-existing permission"); null; end Test_Has_Permission; procedure Configure_Policy (Manager : in out Security.Policies.Policy_Manager; Name : in String) is Dir : constant String := "regtests/files/permissions/"; Path : constant String := Util.Tests.Get_Path (Dir); R : Security.Policies.Roles.Role_Policy_Access := new Roles.Role_Policy; U : Security.Policies.URLs.URL_Policy_Access := new URLs.URL_Policy; begin Manager.Add_Policy (R.all'Access); Manager.Add_Policy (U.all'Access); Manager.Read_Policy (Util.Files.Compose (Path, Name)); end Configure_Policy; -- ------------------------------ -- Test the Get_Policy, Get_Role_Policy and Add_Policy operations. -- ------------------------------ procedure Test_Get_Role_Policy (T : in out Test) is use type Roles.Role_Policy_Access; M : aliased Security.Policies.Policy_Manager (Max_Policies => 2); P : Security.Policies.Policy_Access; R : Security.Policies.Roles.Role_Policy_Access; begin P := M.Get_Policy (Security.Policies.Roles.NAME); T.Assert (P = null, "Get_Policy succeeded"); R := Security.Policies.Roles.Get_Role_Policy (M); T.Assert (R = null, "Get_Role_Policy succeeded"); R := new Roles.Role_Policy; M.Add_Policy (R.all'Access); P := M.Get_Policy (Security.Policies.Roles.NAME); T.Assert (P /= null, "Role policy not found"); T.Assert (P.all in Roles.Role_Policy'Class, "Invalid role policy"); R := Security.Policies.Roles.Get_Role_Policy (M); T.Assert (R /= null, "Get_Role_Policy should not return null"); end Test_Get_Role_Policy; -- ------------------------------ -- Test reading an empty policy file -- ------------------------------ procedure Test_Read_Empty_Policy (T : in out Test) is M : aliased Security.Policies.Policy_Manager (Max_Policies => 2); User : aliased Test_Principal; Context : aliased Security.Contexts.Security_Context; P : Security.Policies.Policy_Access; R : Security.Policies.Roles.Role_Policy_Access; begin Configure_Policy (M, "empty.xml"); Context.Set_Context (Manager => M'Unchecked_Access, Principal => User'Unchecked_Access); R := Security.Policies.Roles.Get_Role_Policy (M); declare Admin : Policies.Roles.Role_Type; begin Admin := R.Find_Role ("admin"); T.Fail ("'admin' role was returned"); exception when Security.Policies.Roles.Invalid_Name => null; end; T.Assert (not Contexts.Has_Permission (Permissions.Tests.P_Admin.Permission), "Has_Permission (admin) failed for empty policy"); T.Assert (not Contexts.Has_Permission (Permissions.Tests.P_Create.Permission), "Has_Permission (create) failed for empty policy"); T.Assert (not Contexts.Has_Permission (Permissions.Tests.P_Update.Permission), "Has_Permission (update) failed for empty policy"); T.Assert (not Contexts.Has_Permission (Permissions.Tests.P_Delete.Permission), "Has_Permission (delete) failed for empty policy"); end Test_Read_Empty_Policy; -- ------------------------------ -- Test reading policy files -- ------------------------------ procedure Test_Read_Policy (T : in out Test) is use Security.Permissions.Tests; M : aliased Security.Policies.Policy_Manager (Max_Policies => 2); User : aliased Test_Principal; Admin : Policies.Roles.Role_Type; Manager_Perm : Policies.Roles.Role_Type; Context : aliased Security.Contexts.Security_Context; R : Security.Policies.Roles.Role_Policy_Access := new Roles.Role_Policy; begin Configure_Policy (M, "simple-policy.xml"); Context.Set_Context (Manager => M'Unchecked_Access, Principal => User'Unchecked_Access); R := Security.Policies.Roles.Get_Role_Policy (M); Admin := R.Find_Role ("admin"); T.Assert (not Contexts.Has_Permission (Permission => P_Admin.Permission), "Permission was granted but user has no role"); User.Roles (Admin) := True; T.Assert (Contexts.Has_Permission (Permission => P_Admin.Permission), "Permission was not granted and user has admin role"); declare S : Util.Measures.Stamp; begin for I in 1 .. 1_000 loop declare URI : constant String := "/admin/home/" & Util.Strings.Image (I) & "/l.html"; P : constant URLs.URI_Permission (URI'Length) := URLs.URI_Permission '(Len => URI'Length, URI => URI); begin T.Assert (Contexts.Has_Permission (Permission => P_Admin.Permission), "Permission not granted"); end; end loop; Util.Measures.Report (S, "Has_Permission (1000 calls, cache miss)"); end; declare use Security.Permissions.Tests; S : Util.Measures.Stamp; begin for I in 1 .. 1_000 loop declare URI : constant String := "/admin/home/list.html"; P : constant URLs.URI_Permission (URI'Length) := URLs.URI_Permission '(Len => URI'Length, URI => URI); begin T.Assert (Contexts.Has_Permission (Permission => P_Admin.Permission), "Permission not granted"); end; end loop; Util.Measures.Report (S, "Has_Permission (1000 calls, cache hit)"); end; end Test_Read_Policy; -- ------------------------------ -- Read the policy file <b>File</b> and perform a test on the given URI -- with a user having the given role. -- ------------------------------ procedure Check_Policy (T : in out Test; File : in String; Role : in String; URI : in String) is M : aliased Security.Policies.Policy_Manager (2); User : aliased Test_Principal; Admin : Roles.Role_Type; Context : aliased Security.Contexts.Security_Context; P : Security.Policies.Policy_Access; R : Security.Policies.Roles.Role_Policy_Access; U : Security.Policies.URLs.URL_Policy_Access; begin Configure_Policy (M, File); Context.Set_Context (Manager => M'Unchecked_Access, Principal => User'Unchecked_Access); R := Security.Policies.Roles.Get_Role_Policy (M); U := Security.Policies.URLs.Get_URL_Policy (M); Admin := R.Find_Role (Role); declare P : constant URLs.URI_Permission (URI'Length) := URLs.URI_Permission '(Len => URI'Length, URI => URI); begin -- A user without the role should not have the permission. T.Assert (not U.Has_Permission (Context => Context'Unchecked_Access, Permission => P), "Permission was granted for user without role. URI=" & URI); -- Set the role. User.Roles (Admin) := True; T.Assert (U.Has_Permission (Context => Context'Unchecked_Access, Permission => P), "Permission was not granted for user with role. URI=" & URI); end; end Check_Policy; -- ------------------------------ -- Test reading policy files and using the <role-permission> controller -- ------------------------------ procedure Test_Role_Policy (T : in out Test) is begin T.Check_Policy (File => "policy-with-role.xml", Role => "developer", URI => "/developer/user-should-have-developer-role"); T.Check_Policy (File => "policy-with-role.xml", Role => "manager", URI => "/developer/user-should-have-manager-role"); T.Check_Policy (File => "policy-with-role.xml", Role => "manager", URI => "/manager/user-should-have-manager-role"); T.Check_Policy (File => "policy-with-role.xml", Role => "admin", URI => "/manager/user-should-have-admin-role"); T.Check_Policy (File => "policy-with-role.xml", Role => "admin", URI => "/admin/user-should-have-admin-role"); end Test_Role_Policy; end Security.Policies.Tests;
----------------------------------------------------------------------- -- Security-policies-tests - Unit tests for Security.Permissions -- Copyright (C) 2011, 2012 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Tests; with Util.Files; with Util.Test_Caller; with Util.Measures; with Security.Contexts; with Security.Policies.Roles; with Security.Permissions.Tests; package body Security.Policies.Tests is use Util.Tests; package Caller is new Util.Test_Caller (Test, "Security.Policies"); procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is begin Caller.Add_Test (Suite, "Test Security.Permissions.Create_Role", Test_Create_Role'Access); Caller.Add_Test (Suite, "Test Security.Permissions.Has_Permission", Test_Has_Permission'Access); Caller.Add_Test (Suite, "Test Security.Permissions.Read_Policy (empty)", Test_Read_Empty_Policy'Access); Caller.Add_Test (Suite, "Test Security.Policies.Add_Policy", Test_Get_Role_Policy'Access); Caller.Add_Test (Suite, "Test Security.Policies.Get_Policy", Test_Get_Role_Policy'Access); Caller.Add_Test (Suite, "Test Security.Policies.Roles.Get_Role_Policy", Test_Get_Role_Policy'Access); Caller.Add_Test (Suite, "Test Security.Policies.Read_Policy", Test_Read_Policy'Access); Caller.Add_Test (Suite, "Test Security.Policies.Roles.Set_Roles", Test_Set_Roles'Access); Caller.Add_Test (Suite, "Test Security.Policies.Roles.Set_Roles (invalid)", Test_Set_Invalid_Roles'Access); -- These tests are identical but registered under different names -- for the test documentation. Caller.Add_Test (Suite, "Test Security.Contexts.Has_Permission", Test_Role_Policy'Access); Caller.Add_Test (Suite, "Test Security.Controllers.Roles.Has_Permission", Test_Role_Policy'Access); Caller.Add_Test (Suite, "Test Security.Permissions.Role_Policy", Test_Role_Policy'Access); end Add_Tests; -- ------------------------------ -- Get the roles assigned to the user. -- ------------------------------ function Get_Roles (User : in Test_Principal) return Roles.Role_Map is begin return User.Roles; end Get_Roles; -- ------------------------------ -- Get the principal name. -- ------------------------------ function Get_Name (From : in Test_Principal) return String is begin return Util.Strings.To_String (From.Name); end Get_Name; -- ------------------------------ -- Test Create_Role and Get_Role_Name -- ------------------------------ procedure Test_Create_Role (T : in out Test) is use Security.Policies.Roles; M : Security.Policies.Roles.Role_Policy; Role : Role_Type; begin M.Create_Role (Name => "admin", Role => Role); Assert_Equals (T, "admin", M.Get_Role_Name (Role), "Invalid name"); for I in Role + 1 .. Role_Type'Last loop declare Name : constant String := "admin-" & Role_Type'Image (I); Role2 : Role_Type; begin Role2 := M.Find_Role ("admin"); T.Assert (Role2 = Role, "Find_Role returned an invalid role"); M.Create_Role (Name => Name, Role => Role2); Assert_Equals (T, Name, M.Get_Role_Name (Role2), "Invalid name"); end; end loop; end Test_Create_Role; -- ------------------------------ -- Test Set_Roles -- ------------------------------ procedure Test_Set_Roles (T : in out Test) is use Security.Policies.Roles; M : Security.Policies.Roles.Role_Policy; Admin : Role_Type; Manager : Role_Type; Map : Role_Map := (others => False); begin M.Create_Role (Name => "manager", Role => Manager); M.Create_Role (Name => "admin", Role => Admin); Assert_Equals (T, "admin", M.Get_Role_Name (Admin), "Invalid name"); T.Assert (not Map (Admin), "The admin role must not set in the map"); M.Set_Roles ("admin", Map); T.Assert (Map (Admin), "The admin role is not set in the map"); T.Assert (not Map (Manager), "The manager role must not be set in the map"); Map := (others => False); M.Set_Roles ("manager,admin", Map); T.Assert (Map (Admin), "The admin role is not set in the map"); T.Assert (Map (Manager), "The manager role is not set in the map"); end Test_Set_Roles; -- ------------------------------ -- Test Set_Roles on an invalid role name -- ------------------------------ procedure Test_Set_Invalid_Roles (T : in out Test) is use Security.Policies.Roles; M : Security.Policies.Roles.Role_Policy; Map : Role_Map := (others => False); begin M.Set_Roles ("manager,admin", Map); T.Assert (False, "No exception was raised"); exception when E : Security.Policies.Roles.Invalid_Name => null; end Test_Set_Invalid_Roles; -- ------------------------------ -- Test Has_Permission -- ------------------------------ procedure Test_Has_Permission (T : in out Test) is M : Security.Policies.Policy_Manager (1); -- Perm : Permissions.Permission_Type; User : Test_Principal; begin -- T.Assert (not M.Has_Permission (User, 1), "User has a non-existing permission"); null; end Test_Has_Permission; procedure Configure_Policy (Manager : in out Security.Policies.Policy_Manager; Name : in String) is Dir : constant String := "regtests/files/permissions/"; Path : constant String := Util.Tests.Get_Path (Dir); R : Security.Policies.Roles.Role_Policy_Access := new Roles.Role_Policy; U : Security.Policies.URLs.URL_Policy_Access := new URLs.URL_Policy; begin Manager.Add_Policy (R.all'Access); Manager.Add_Policy (U.all'Access); Manager.Read_Policy (Util.Files.Compose (Path, Name)); end Configure_Policy; -- ------------------------------ -- Test the Get_Policy, Get_Role_Policy and Add_Policy operations. -- ------------------------------ procedure Test_Get_Role_Policy (T : in out Test) is use type Roles.Role_Policy_Access; M : aliased Security.Policies.Policy_Manager (Max_Policies => 2); P : Security.Policies.Policy_Access; R : Security.Policies.Roles.Role_Policy_Access; begin P := M.Get_Policy (Security.Policies.Roles.NAME); T.Assert (P = null, "Get_Policy succeeded"); R := Security.Policies.Roles.Get_Role_Policy (M); T.Assert (R = null, "Get_Role_Policy succeeded"); R := new Roles.Role_Policy; M.Add_Policy (R.all'Access); P := M.Get_Policy (Security.Policies.Roles.NAME); T.Assert (P /= null, "Role policy not found"); T.Assert (P.all in Roles.Role_Policy'Class, "Invalid role policy"); R := Security.Policies.Roles.Get_Role_Policy (M); T.Assert (R /= null, "Get_Role_Policy should not return null"); end Test_Get_Role_Policy; -- ------------------------------ -- Test reading an empty policy file -- ------------------------------ procedure Test_Read_Empty_Policy (T : in out Test) is M : aliased Security.Policies.Policy_Manager (Max_Policies => 2); User : aliased Test_Principal; Context : aliased Security.Contexts.Security_Context; P : Security.Policies.Policy_Access; R : Security.Policies.Roles.Role_Policy_Access; begin Configure_Policy (M, "empty.xml"); Context.Set_Context (Manager => M'Unchecked_Access, Principal => User'Unchecked_Access); R := Security.Policies.Roles.Get_Role_Policy (M); declare Admin : Policies.Roles.Role_Type; begin Admin := R.Find_Role ("admin"); T.Fail ("'admin' role was returned"); exception when Security.Policies.Roles.Invalid_Name => null; end; T.Assert (not Contexts.Has_Permission (Permissions.Tests.P_Admin.Permission), "Has_Permission (admin) failed for empty policy"); T.Assert (not Contexts.Has_Permission (Permissions.Tests.P_Create.Permission), "Has_Permission (create) failed for empty policy"); T.Assert (not Contexts.Has_Permission (Permissions.Tests.P_Update.Permission), "Has_Permission (update) failed for empty policy"); T.Assert (not Contexts.Has_Permission (Permissions.Tests.P_Delete.Permission), "Has_Permission (delete) failed for empty policy"); end Test_Read_Empty_Policy; -- ------------------------------ -- Test reading policy files -- ------------------------------ procedure Test_Read_Policy (T : in out Test) is use Security.Permissions.Tests; M : aliased Security.Policies.Policy_Manager (Max_Policies => 2); User : aliased Test_Principal; Admin : Policies.Roles.Role_Type; Manager_Perm : Policies.Roles.Role_Type; Context : aliased Security.Contexts.Security_Context; R : Security.Policies.Roles.Role_Policy_Access := new Roles.Role_Policy; begin Configure_Policy (M, "simple-policy.xml"); Context.Set_Context (Manager => M'Unchecked_Access, Principal => User'Unchecked_Access); R := Security.Policies.Roles.Get_Role_Policy (M); Admin := R.Find_Role ("admin"); T.Assert (not Contexts.Has_Permission (Permission => P_Admin.Permission), "Permission was granted but user has no role"); User.Roles (Admin) := True; T.Assert (Contexts.Has_Permission (Permission => P_Admin.Permission), "Permission was not granted and user has admin role"); declare S : Util.Measures.Stamp; Result : Boolean; begin for I in 1 .. 1_000 loop Result := Contexts.Has_Permission (Permission => P_Admin.Permission); end loop; Util.Measures.Report (S, "Has_Permission role based (1000 calls)"); T.Assert (Result, "Permission not granted"); end; declare use Security.Permissions.Tests; S : Util.Measures.Stamp; begin for I in 1 .. 1_000 loop declare URI : constant String := "/admin/home/list.html"; P : constant URLs.URI_Permission (URI'Length) := URLs.URI_Permission '(Len => URI'Length, URI => URI); begin T.Assert (Contexts.Has_Permission (Permission => P_Admin.Permission), "Permission not granted"); end; end loop; Util.Measures.Report (S, "Has_Permission (1000 calls, cache hit)"); end; end Test_Read_Policy; -- ------------------------------ -- Read the policy file <b>File</b> and perform a test on the given URI -- with a user having the given role. -- ------------------------------ procedure Check_Policy (T : in out Test; File : in String; Role : in String; URI : in String) is M : aliased Security.Policies.Policy_Manager (2); User : aliased Test_Principal; Admin : Roles.Role_Type; Context : aliased Security.Contexts.Security_Context; P : Security.Policies.Policy_Access; R : Security.Policies.Roles.Role_Policy_Access; U : Security.Policies.URLs.URL_Policy_Access; begin Configure_Policy (M, File); Context.Set_Context (Manager => M'Unchecked_Access, Principal => User'Unchecked_Access); R := Security.Policies.Roles.Get_Role_Policy (M); U := Security.Policies.URLs.Get_URL_Policy (M); Admin := R.Find_Role (Role); declare P : constant URLs.URI_Permission (URI'Length) := URLs.URI_Permission '(Len => URI'Length, URI => URI); begin -- A user without the role should not have the permission. T.Assert (not U.Has_Permission (Context => Context'Unchecked_Access, Permission => P), "Permission was granted for user without role. URI=" & URI); -- Set the role. User.Roles (Admin) := True; T.Assert (U.Has_Permission (Context => Context'Unchecked_Access, Permission => P), "Permission was not granted for user with role. URI=" & URI); end; end Check_Policy; -- ------------------------------ -- Test reading policy files and using the <role-permission> controller -- ------------------------------ procedure Test_Role_Policy (T : in out Test) is begin T.Check_Policy (File => "policy-with-role.xml", Role => "developer", URI => "/developer/user-should-have-developer-role"); T.Check_Policy (File => "policy-with-role.xml", Role => "manager", URI => "/developer/user-should-have-manager-role"); T.Check_Policy (File => "policy-with-role.xml", Role => "manager", URI => "/manager/user-should-have-manager-role"); T.Check_Policy (File => "policy-with-role.xml", Role => "admin", URI => "/manager/user-should-have-admin-role"); T.Check_Policy (File => "policy-with-role.xml", Role => "admin", URI => "/admin/user-should-have-admin-role"); end Test_Role_Policy; end Security.Policies.Tests;
Fix benchmark test for Has_Permission
Fix benchmark test for Has_Permission
Ada
apache-2.0
Letractively/ada-security
3b69527509d682cb95749493adc8f7f6e4f84693
src/wiki-render.adb
src/wiki-render.adb
----------------------------------------------------------------------- -- wiki-render -- Wiki renderer -- Copyright (C) 2015, 2016 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- package body Wiki.Render is -- ------------------------------ -- Get the image link that must be rendered from the wiki image link. -- ------------------------------ overriding procedure Make_Image_Link (Renderer : in Default_Link_Renderer; Link : in Wide_Wide_String; URI : out Unbounded_Wide_Wide_String; Width : out Natural; Height : out Natural) is pragma Unreferenced (Renderer); begin URI := To_Unbounded_Wide_Wide_String (Link); Width := 0; Height := 0; end Make_Image_Link; -- ------------------------------ -- Get the page link that must be rendered from the wiki page link. -- ------------------------------ overriding procedure Make_Page_Link (Renderer : in Default_Link_Renderer; Link : in Wide_Wide_String; URI : out Unbounded_Wide_Wide_String; Exists : out Boolean) is pragma Unreferenced (Renderer); begin URI := To_Unbounded_Wide_Wide_String (Link); Exists := True; end Make_Page_Link; -- ------------------------------ -- Render the list of nodes from the document. -- ------------------------------ procedure Render (Engine : in out Renderer'Class; Doc : in Wiki.Documents.Document; List : in Wiki.Nodes.Node_List_Access) is use type Wiki.Nodes.Node_List_Access; procedure Process (Node : in Wiki.Nodes.Node_Type); procedure Process (Node : in Wiki.Nodes.Node_Type) is begin Engine.Render (Doc, Node); end Process; begin if List /= null then Wiki.Nodes.Iterate (List, Process'Access); end if; end Render; -- ------------------------------ -- Render the document. -- ------------------------------ procedure Render (Engine : in out Renderer'Class; Doc : in Wiki.Documents.Document) is procedure Process (Node : in Wiki.Nodes.Node_Type); procedure Process (Node : in Wiki.Nodes.Node_Type) is begin Engine.Render (Doc, Node); end Process; begin Doc.Iterate (Process'Access); Engine.Finish (Doc); end Render; end Wiki.Render;
----------------------------------------------------------------------- -- wiki-render -- Wiki renderer -- Copyright (C) 2015, 2016 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- package body Wiki.Render is -- ------------------------------ -- Get the image link that must be rendered from the wiki image link. -- ------------------------------ overriding procedure Make_Image_Link (Renderer : in Default_Link_Renderer; Link : in Wiki.Strings.WString; URI : out Wiki.Strings.UString; Width : out Natural; Height : out Natural) is pragma Unreferenced (Renderer); begin URI := Wiki.Strings.To_UString (Link); Width := 0; Height := 0; end Make_Image_Link; -- ------------------------------ -- Get the page link that must be rendered from the wiki page link. -- ------------------------------ overriding procedure Make_Page_Link (Renderer : in Default_Link_Renderer; Link : in Wiki.Strings.WString; URI : out Wiki.Strings.UString; Exists : out Boolean) is pragma Unreferenced (Renderer); begin URI := Wiki.Strings.To_UString (Link); Exists := True; end Make_Page_Link; -- ------------------------------ -- Render the list of nodes from the document. -- ------------------------------ procedure Render (Engine : in out Renderer'Class; Doc : in Wiki.Documents.Document; List : in Wiki.Nodes.Node_List_Access) is use type Wiki.Nodes.Node_List_Access; procedure Process (Node : in Wiki.Nodes.Node_Type); procedure Process (Node : in Wiki.Nodes.Node_Type) is begin Engine.Render (Doc, Node); end Process; begin if List /= null then Wiki.Nodes.Iterate (List, Process'Access); end if; end Render; -- ------------------------------ -- Render the document. -- ------------------------------ procedure Render (Engine : in out Renderer'Class; Doc : in Wiki.Documents.Document) is procedure Process (Node : in Wiki.Nodes.Node_Type); procedure Process (Node : in Wiki.Nodes.Node_Type) is begin Engine.Render (Doc, Node); end Process; begin Doc.Iterate (Process'Access); Engine.Finish (Doc); end Render; end Wiki.Render;
Use the Wiki.Strings.WString and UString types
Use the Wiki.Strings.WString and UString types
Ada
apache-2.0
stcarrez/ada-wiki,stcarrez/ada-wiki
393dc104d87890de0141d68787edce86482b4c12
src/el-methods-func_1.ads
src/el-methods-func_1.ads
----------------------------------------------------------------------- -- EL.Methods.Func_1 -- Function Bindings with 1 argument -- Copyright (C) 2010, 2011 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with EL.Expressions; with EL.Contexts; with Util.Beans.Methods; with Util.Beans.Basic; generic type Param1_Type (<>) is private; type Return_Type (<>) is private; package EL.Methods.Func_1 is use Util.Beans.Methods; -- Execute the method describe by the method expression -- and with the given context. The method signature is: -- -- function F (Obj : <Bean>; Param : Param1_Type) return Return_Type; -- -- where <Bean> inherits from <b>Readonly_Bean</b> -- (See <b>Bind</b> package) -- -- Raises <b>Invalid_Method</b> if the method referenced by -- the method expression does not exist or does not match -- the signature. function Execute (Method : in EL.Expressions.Method_Expression'Class; Param : in Param1_Type; Context : in EL.Contexts.ELContext'Class) return Return_Type; -- Function access to the proxy. type Proxy_Access is access function (O : in Util.Beans.Basic.Readonly_Bean'Class; P : in Param1_Type) return Return_Type; -- The binding record which links the method name -- to the proxy function. type Binding is new Method_Binding with record Method : Proxy_Access; end record; type Binding_Access is access constant Binding; -- Proxy for the binding. -- The proxy declares the binding definition that links -- the name to the function and it implements the necessary -- object conversion to translate the <b>Readonly_Bean</b> -- object to the target object type. generic -- Name of the method (as exposed in the EL expression) Name : String; -- The bean type type Bean is new Util.Beans.Basic.Readonly_Bean with private; -- The bean method to invoke with function Method (O : in Bean; P1 : in Param1_Type) return Return_Type; package Bind is -- Method that <b>Execute</b> will invoke. function Method_Access (O : in Util.Beans.Basic.Readonly_Bean'Class; P1 : in Param1_Type) return Return_Type; F_NAME : aliased constant String := Name; -- The proxy binding that can be exposed through -- the <b>Method_Bean</b> interface. Proxy : aliased constant Binding := Binding '(Name => F_NAME'Access, Method => Method_Access'Access); end Bind; end EL.Methods.Func_1;
----------------------------------------------------------------------- -- EL.Methods.Func_1 -- Function Bindings with 1 argument -- Copyright (C) 2010, 2011, 2012 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with EL.Expressions; with EL.Contexts; with Util.Beans.Methods; with Util.Beans.Basic; generic type Param1_Type (<>) is limited private; type Return_Type (<>) is private; package EL.Methods.Func_1 is use Util.Beans.Methods; -- Execute the method describe by the method expression -- and with the given context. The method signature is: -- -- function F (Obj : <Bean>; Param : Param1_Type) return Return_Type; -- -- where <Bean> inherits from <b>Readonly_Bean</b> -- (See <b>Bind</b> package) -- -- Raises <b>Invalid_Method</b> if the method referenced by -- the method expression does not exist or does not match -- the signature. function Execute (Method : in EL.Expressions.Method_Expression'Class; Param : in Param1_Type; Context : in EL.Contexts.ELContext'Class) return Return_Type; -- Function access to the proxy. type Proxy_Access is access function (O : in Util.Beans.Basic.Readonly_Bean'Class; P : in Param1_Type) return Return_Type; -- The binding record which links the method name -- to the proxy function. type Binding is new Method_Binding with record Method : Proxy_Access; end record; type Binding_Access is access constant Binding; -- Proxy for the binding. -- The proxy declares the binding definition that links -- the name to the function and it implements the necessary -- object conversion to translate the <b>Readonly_Bean</b> -- object to the target object type. generic -- Name of the method (as exposed in the EL expression) Name : String; -- The bean type type Bean is new Util.Beans.Basic.Readonly_Bean with private; -- The bean method to invoke with function Method (O : in Bean; P1 : in Param1_Type) return Return_Type; package Bind is -- Method that <b>Execute</b> will invoke. function Method_Access (O : in Util.Beans.Basic.Readonly_Bean'Class; P1 : in Param1_Type) return Return_Type; F_NAME : aliased constant String := Name; -- The proxy binding that can be exposed through -- the <b>Method_Bean</b> interface. Proxy : aliased constant Binding := Binding '(Name => F_NAME'Access, Method => Method_Access'Access); end Bind; end EL.Methods.Func_1;
Change the function parameter to a limited parameter allowing to pass limited types
Change the function parameter to a limited parameter allowing to pass limited types
Ada
apache-2.0
stcarrez/ada-el
6d9ad7cdf9348bbf3657d3681d7d9611c91236fd
awa/plugins/awa-changelogs/src/awa-changelogs-modules.adb
awa/plugins/awa-changelogs/src/awa-changelogs-modules.adb
----------------------------------------------------------------------- -- awa-changelogs-modules -- Module changelogs -- 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 AWA.Modules.Get; with Util.Log.Loggers; package body AWA.Changelogs.Modules is Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("Awa.Changelogs.Module"); -- ------------------------------ -- Initialize the changelogs module. -- ------------------------------ overriding procedure Initialize (Plugin : in out Changelog_Module; App : in AWA.Modules.Application_Access; Props : in ASF.Applications.Config) is begin Log.Info ("Initializing the changelogs module"); AWA.Modules.Module (Plugin).Initialize (App, Props); -- Add here the creation of manager instances. end Initialize; -- ------------------------------ -- Get the changelogs module. -- ------------------------------ function Get_Changelog_Module return Changelog_Module_Access is function Get is new AWA.Modules.Get (Changelog_Module, Changelog_Module_Access, NAME); begin return Get; end Get_Changelog_Module; end AWA.Changelogs.Modules;
----------------------------------------------------------------------- -- awa-changelogs-modules -- Module changelogs -- Copyright (C) 2014 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Calendar; with Util.Log.Loggers; with AWA.Modules.Get; with AWA.Users.Models; with AWA.Services.Contexts; with AWA.Changelogs.Models; with ADO.Sessions; with ADO.Sessions.Entities; package body AWA.Changelogs.Modules is package ASC renames AWA.Services.Contexts; Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("Awa.Changelogs.Module"); -- ------------------------------ -- Initialize the changelogs module. -- ------------------------------ overriding procedure Initialize (Plugin : in out Changelog_Module; App : in AWA.Modules.Application_Access; Props : in ASF.Applications.Config) is begin Log.Info ("Initializing the changelogs module"); AWA.Modules.Module (Plugin).Initialize (App, Props); -- Add here the creation of manager instances. end Initialize; -- ------------------------------ -- Get the changelogs module. -- ------------------------------ function Get_Changelog_Module return Changelog_Module_Access is function Get is new AWA.Modules.Get (Changelog_Module, Changelog_Module_Access, NAME); begin return Get; end Get_Changelog_Module; -- ------------------------------ -- Add the log message and associate it with the database entity identified by -- the given id and the entity type. The log message is associated with the current user. -- ------------------------------ procedure Add_Log (Model : in Changelog_Module; Id : in ADO.Identifier; Entity_Type : in String; Message : in String) is pragma Unreferenced (Model); Ctx : constant ASC.Service_Context_Access := ASC.Current; User : constant AWA.Users.Models.User_Ref := Ctx.Get_User; DB : ADO.Sessions.Master_Session := AWA.Services.Contexts.Get_Master_Session (Ctx); Kind : ADO.Entity_Type; History : AWA.Changelogs.Models.Changelog_Ref; begin Ctx.Start; Kind := ADO.Sessions.Entities.Find_Entity_Type (DB, Entity_Type); History.Set_For_Entity_Id (Id); History.Set_User (User); History.Set_Date (Ada.Calendar.Clock); History.Set_Entity_Type (Kind); History.Set_Text (Message); History.Save (DB); DB.Commit; end Add_Log; end AWA.Changelogs.Modules;
Implement the Add_Log operation
Implement the Add_Log operation
Ada
apache-2.0
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
c98a733a37425f9753b4b0261f7a57f6696ab0c0
src/http/curl/util-http-clients-curl.adb
src/http/curl/util-http-clients-curl.adb
----------------------------------------------------------------------- -- util-http-clients-curl -- HTTP Clients with CURL -- 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. ----------------------------------------------------------------------- with Util.Strings; with Util.Log.Loggers; with Util.Http.Clients.Curl.Constants; package body Util.Http.Clients.Curl is use System; pragma Linker_Options ("-lcurl"); Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("Util.Http.Clients.Curl"); function Get_Request (Http : in Client'Class) return Curl_Http_Request_Access; Manager : aliased Curl_Http_Manager; -- ------------------------------ -- Register the CURL Http manager. -- ------------------------------ procedure Register is begin Default_Http_Manager := Manager'Access; end Register; -- ------------------------------ -- Check the CURL result code and report and exception and a log message if -- the CURL code indicates an error. -- ------------------------------ procedure Check_Code (Code : in CURL_Code; Message : in String) is begin if Code /= CURLE_OK then declare Error : constant Chars_Ptr := Curl_Easy_Strerror (Code); Msg : constant String := Interfaces.C.Strings.Value (Error); begin Log.Error ("{0}: {1}", Message, Msg); raise Connection_Error with Msg; end; end if; end Check_Code; -- ------------------------------ -- Create a new HTTP request associated with the current request manager. -- ------------------------------ procedure Create (Manager : in Curl_Http_Manager; Http : in out Client'Class) is pragma Unreferenced (Manager); Request : Curl_Http_Request_Access; Data : CURL; begin Data := Curl_Easy_Init; if Data = System.Null_Address then raise Storage_Error with "curl_easy_init cannot create the CURL instance"; end if; Request := new Curl_Http_Request; Request.Data := Data; Http.Delegate := Request.all'Access; end Create; function Get_Request (Http : in Client'Class) return Curl_Http_Request_Access is begin return Curl_Http_Request'Class (Http.Delegate.all)'Access; end Get_Request; -- ------------------------------ -- This function is called by CURL when a response line was read. -- ------------------------------ function Read_Response (Data : in Chars_Ptr; Size : in Size_T; Nmemb : in Size_T; Response : in Curl_Http_Response_Access) return Size_T is Total : constant Size_T := Size * Nmemb; Line : constant String := Interfaces.C.Strings.Value (Data, Total); begin Log.Info ("RCV: {0}", Line); if Response.Parsing_Body then Ada.Strings.Unbounded.Append (Response.Content, Line); elsif Total = 2 and then Line (1) = ASCII.CR and then Line (2) = ASCII.LF then Response.Parsing_Body := True; else declare Pos : constant Natural := Util.Strings.Index (Line, ':'); Start : Natural; Last : Natural; begin if Pos > 0 then Start := Pos + 1; while Start <= Line'Last and Line (Start) = ' ' loop Start := Start + 1; end loop; Last := Line'Last; while Last >= Start and (Line (Last) = ASCII.CR or Line (Last) = ASCII.LF) loop Last := Last - 1; end loop; Response.Add_Header (Name => Line (Line'First .. Pos - 1), Value => Line (Start .. Last)); end if; end; end if; return Total; end Read_Response; -- ------------------------------ -- Prepare to setup the headers in the request. -- ------------------------------ procedure Set_Headers (Request : in out Curl_Http_Request) is procedure Process (Name, Value : in String) is S : Chars_Ptr := Strings.New_String (Name & ": " & Value); begin Request.Curl_Headers := Curl_Slist_Append (Request.Curl_Headers, S); Interfaces.C.Strings.Free (S); end Process; begin if Request.Curl_Headers /= null then Curl_Slist_Free_All (Request.Curl_Headers); Request.Curl_Headers := null; end if; Request.Iterate_Headers (Process'Access); end Set_Headers; procedure Do_Get (Manager : in Curl_Http_Manager; Http : in Client'Class; URI : in String; Reply : out Response'Class) is pragma Unreferenced (Manager); use Interfaces.C; Req : constant Curl_Http_Request_Access := Get_Request (Http); Result : CURL_Code; Response : Curl_Http_Response_Access; Status : aliased C.long; begin Log.Info ("GET {0}", URI); Result := Curl_Easy_Setopt_Write_Callback (Req.Data, Constants.CURLOPT_WRITEUNCTION, Read_Response'Access); Check_Code (Result, "set callback"); Req.Set_Headers; Interfaces.C.Strings.Free (Req.URL); Req.URL := Strings.New_String (URI); Result := Curl_Easy_Setopt_Long (Req.Data, Constants.CURLOPT_HTTPGET, 1); Check_Code (Result, "set http GET"); Result := Curl_Easy_Setopt_Long (Req.Data, Constants.CURLOPT_HEADER, 1); Check_Code (Result, "set header"); Result := Curl_Easy_Setopt_Slist (Req.Data, Constants.CURLOPT_HTTPHEADER, Req.Curl_Headers); Check_Code (Result, "set http GET headers"); Result := Curl_Easy_Setopt_String (Req.Data, Constants.CURLOPT_URL, Req.URL); Check_Code (Result, "set url"); Response := new Curl_Http_Response; Result := Curl_Easy_Setopt_Data (Req.Data, Constants.CURLOPT_WRITEDATA, Response); Check_Code (Result, "set write data"); Reply.Delegate := Response.all'Access; Result := Curl_Easy_Perform (Req.Data); Check_Code (Result, "get request"); Result := Curl_Easy_Getinfo_Long (Req.Data, Constants.CURLINFO_RESPONSE_CODE, Status'Access); Check_Code (Result, "get response code"); Response.Status := Natural (Status); end Do_Get; procedure Do_Post (Manager : in Curl_Http_Manager; Http : in Client'Class; URI : in String; Data : in String; Reply : out Response'Class) is pragma Unreferenced (Manager); use Interfaces.C; Req : constant Curl_Http_Request_Access := Get_Request (Http); Result : CURL_Code; Response : Curl_Http_Response_Access; Status : aliased C.long; begin Log.Info ("POST {0}", URI); Result := Curl_Easy_Setopt_Write_Callback (Req.Data, Constants.CURLOPT_WRITEUNCTION, Read_Response'Access); Check_Code (Result, "set callback"); Req.Set_Headers; Interfaces.C.Strings.Free (Req.URL); Req.URL := Strings.New_String (URI); Interfaces.C.Strings.Free (Req.Content); Req.Content := Strings.New_String (Data); Result := Curl_Easy_Setopt_Long (Req.Data, Constants.CURLOPT_POST, 1); Check_Code (Result, "set http POST"); Result := Curl_Easy_Setopt_Long (Req.Data, Constants.CURLOPT_HEADER, 1); Check_Code (Result, "set header"); Result := Curl_Easy_Setopt_Slist (Req.Data, Constants.CURLOPT_HTTPHEADER, Req.Curl_Headers); Check_Code (Result, "set http GET headers"); Result := Curl_Easy_Setopt_String (Req.Data, Constants.CURLOPT_URL, Req.URL); Check_Code (Result, "set url"); Result := Curl_Easy_Setopt_String (Req.Data, Constants.CURLOPT_POSTFIELDS, Req.Content); Check_Code (Result, "set post data"); Result := Curl_Easy_Setopt_Long (Req.Data, Constants.CURLOPT_POSTFIELDSIZE, Data'Length); Check_Code (Result, "set post data"); Response := new Curl_Http_Response; Result := Curl_Easy_Setopt_Data (Req.Data, Constants.CURLOPT_WRITEDATA, Response); Check_Code (Result, "set write data"); Reply.Delegate := Response.all'Access; Result := Curl_Easy_Perform (Req.Data); Check_Code (Result, "get request"); Result := Curl_Easy_Getinfo_Long (Req.Data, Constants.CURLINFO_RESPONSE_CODE, Status'Access); Check_Code (Result, "get response code"); Response.Status := Natural (Status); end Do_Post; overriding procedure Finalize (Request : in out Curl_Http_Request) is begin if Request.Data /= System.Null_Address then Curl_Easy_Cleanup (Request.Data); Request.Data := System.Null_Address; end if; if Request.Curl_Headers /= null then Curl_Slist_Free_All (Request.Curl_Headers); Request.Curl_Headers := null; end if; Interfaces.C.Strings.Free (Request.URL); Interfaces.C.Strings.Free (Request.Content); end Finalize; -- ------------------------------ -- Get the response body as a string. -- ------------------------------ overriding function Get_Body (Reply : in Curl_Http_Response) return String is begin return Ada.Strings.Unbounded.To_String (Reply.Content); end Get_Body; -- ------------------------------ -- Get the response status code. -- ------------------------------ overriding function Get_Status (Reply : in Curl_Http_Response) return Natural is begin return Reply.Status; end Get_Status; end Util.Http.Clients.Curl;
----------------------------------------------------------------------- -- util-http-clients-curl -- HTTP Clients with CURL -- 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. ----------------------------------------------------------------------- with Util.Strings; with Util.Log.Loggers; with Util.Http.Clients.Curl.Constants; package body Util.Http.Clients.Curl is use System; pragma Linker_Options ("-lcurl"); Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("Util.Http.Clients.Curl"); function Get_Request (Http : in Client'Class) return Curl_Http_Request_Access; PUT_TOKEN : Chars_Ptr := Strings.New_String ("PUT"); Manager : aliased Curl_Http_Manager; -- ------------------------------ -- Register the CURL Http manager. -- ------------------------------ procedure Register is begin Default_Http_Manager := Manager'Access; end Register; -- ------------------------------ -- Check the CURL result code and report and exception and a log message if -- the CURL code indicates an error. -- ------------------------------ procedure Check_Code (Code : in CURL_Code; Message : in String) is begin if Code /= CURLE_OK then declare Error : constant Chars_Ptr := Curl_Easy_Strerror (Code); Msg : constant String := Interfaces.C.Strings.Value (Error); begin Log.Error ("{0}: {1}", Message, Msg); raise Connection_Error with Msg; end; end if; end Check_Code; -- ------------------------------ -- Create a new HTTP request associated with the current request manager. -- ------------------------------ procedure Create (Manager : in Curl_Http_Manager; Http : in out Client'Class) is pragma Unreferenced (Manager); Request : Curl_Http_Request_Access; Data : CURL; begin Data := Curl_Easy_Init; if Data = System.Null_Address then raise Storage_Error with "curl_easy_init cannot create the CURL instance"; end if; Request := new Curl_Http_Request; Request.Data := Data; Http.Delegate := Request.all'Access; end Create; function Get_Request (Http : in Client'Class) return Curl_Http_Request_Access is begin return Curl_Http_Request'Class (Http.Delegate.all)'Access; end Get_Request; -- ------------------------------ -- This function is called by CURL when a response line was read. -- ------------------------------ function Read_Response (Data : in Chars_Ptr; Size : in Size_T; Nmemb : in Size_T; Response : in Curl_Http_Response_Access) return Size_T is Total : constant Size_T := Size * Nmemb; Line : constant String := Interfaces.C.Strings.Value (Data, Total); begin Log.Info ("RCV: {0}", Line); if Response.Parsing_Body then Ada.Strings.Unbounded.Append (Response.Content, Line); elsif Total = 2 and then Line (1) = ASCII.CR and then Line (2) = ASCII.LF then Response.Parsing_Body := True; else declare Pos : constant Natural := Util.Strings.Index (Line, ':'); Start : Natural; Last : Natural; begin if Pos > 0 then Start := Pos + 1; while Start <= Line'Last and Line (Start) = ' ' loop Start := Start + 1; end loop; Last := Line'Last; while Last >= Start and (Line (Last) = ASCII.CR or Line (Last) = ASCII.LF) loop Last := Last - 1; end loop; Response.Add_Header (Name => Line (Line'First .. Pos - 1), Value => Line (Start .. Last)); end if; end; end if; return Total; end Read_Response; -- ------------------------------ -- Prepare to setup the headers in the request. -- ------------------------------ procedure Set_Headers (Request : in out Curl_Http_Request) is procedure Process (Name, Value : in String) is S : Chars_Ptr := Strings.New_String (Name & ": " & Value); begin Request.Curl_Headers := Curl_Slist_Append (Request.Curl_Headers, S); Interfaces.C.Strings.Free (S); end Process; begin if Request.Curl_Headers /= null then Curl_Slist_Free_All (Request.Curl_Headers); Request.Curl_Headers := null; end if; Request.Iterate_Headers (Process'Access); end Set_Headers; procedure Do_Get (Manager : in Curl_Http_Manager; Http : in Client'Class; URI : in String; Reply : out Response'Class) is pragma Unreferenced (Manager); use Interfaces.C; Req : constant Curl_Http_Request_Access := Get_Request (Http); Result : CURL_Code; Response : Curl_Http_Response_Access; Status : aliased C.long; begin Log.Info ("GET {0}", URI); Result := Curl_Easy_Setopt_Write_Callback (Req.Data, Constants.CURLOPT_WRITEUNCTION, Read_Response'Access); Check_Code (Result, "set callback"); Req.Set_Headers; Interfaces.C.Strings.Free (Req.URL); Req.URL := Strings.New_String (URI); Result := Curl_Easy_Setopt_Long (Req.Data, Constants.CURLOPT_HTTPGET, 1); Check_Code (Result, "set http GET"); Result := Curl_Easy_Setopt_Long (Req.Data, Constants.CURLOPT_HEADER, 1); Check_Code (Result, "set header"); Result := Curl_Easy_Setopt_Slist (Req.Data, Constants.CURLOPT_HTTPHEADER, Req.Curl_Headers); Check_Code (Result, "set http GET headers"); Result := Curl_Easy_Setopt_String (Req.Data, Constants.CURLOPT_URL, Req.URL); Check_Code (Result, "set url"); Response := new Curl_Http_Response; Result := Curl_Easy_Setopt_Data (Req.Data, Constants.CURLOPT_WRITEDATA, Response); Check_Code (Result, "set write data"); Reply.Delegate := Response.all'Access; Result := Curl_Easy_Perform (Req.Data); Check_Code (Result, "get request"); Result := Curl_Easy_Getinfo_Long (Req.Data, Constants.CURLINFO_RESPONSE_CODE, Status'Access); Check_Code (Result, "get response code"); Response.Status := Natural (Status); end Do_Get; procedure Do_Post (Manager : in Curl_Http_Manager; Http : in Client'Class; URI : in String; Data : in String; Reply : out Response'Class) is pragma Unreferenced (Manager); use Interfaces.C; Req : constant Curl_Http_Request_Access := Get_Request (Http); Result : CURL_Code; Response : Curl_Http_Response_Access; Status : aliased C.long; begin Log.Info ("POST {0}", URI); Result := Curl_Easy_Setopt_Write_Callback (Req.Data, Constants.CURLOPT_WRITEUNCTION, Read_Response'Access); Check_Code (Result, "set callback"); Req.Set_Headers; Interfaces.C.Strings.Free (Req.URL); Req.URL := Strings.New_String (URI); Interfaces.C.Strings.Free (Req.Content); Req.Content := Strings.New_String (Data); Result := Curl_Easy_Setopt_Long (Req.Data, Constants.CURLOPT_POST, 1); Check_Code (Result, "set http POST"); Result := Curl_Easy_Setopt_Long (Req.Data, Constants.CURLOPT_HEADER, 1); Check_Code (Result, "set header"); Result := Curl_Easy_Setopt_Slist (Req.Data, Constants.CURLOPT_HTTPHEADER, Req.Curl_Headers); Check_Code (Result, "set http GET headers"); Result := Curl_Easy_Setopt_String (Req.Data, Constants.CURLOPT_URL, Req.URL); Check_Code (Result, "set url"); Result := Curl_Easy_Setopt_String (Req.Data, Constants.CURLOPT_POSTFIELDS, Req.Content); Check_Code (Result, "set post data"); Result := Curl_Easy_Setopt_Long (Req.Data, Constants.CURLOPT_POSTFIELDSIZE, Data'Length); Check_Code (Result, "set post data"); Response := new Curl_Http_Response; Result := Curl_Easy_Setopt_Data (Req.Data, Constants.CURLOPT_WRITEDATA, Response); Check_Code (Result, "set write data"); Reply.Delegate := Response.all'Access; Result := Curl_Easy_Perform (Req.Data); Check_Code (Result, "get request"); Result := Curl_Easy_Getinfo_Long (Req.Data, Constants.CURLINFO_RESPONSE_CODE, Status'Access); Check_Code (Result, "get response code"); Response.Status := Natural (Status); end Do_Post; overriding procedure Do_Put (Manager : in Curl_Http_Manager; Http : in Client'Class; URI : in String; Data : in String; Reply : out Response'Class) is pragma Unreferenced (Manager); use Interfaces.C; Req : constant Curl_Http_Request_Access := Get_Request (Http); Result : CURL_Code; Response : Curl_Http_Response_Access; Status : aliased C.long; begin Log.Info ("PUT {0}", URI); Result := Curl_Easy_Setopt_Write_Callback (Req.Data, Constants.CURLOPT_WRITEUNCTION, Read_Response'Access); Check_Code (Result, "set callback"); Req.Set_Headers; Interfaces.C.Strings.Free (Req.URL); Req.URL := Strings.New_String (URI); Interfaces.C.Strings.Free (Req.Content); Req.Content := Strings.New_String (Data); Result := Curl_Easy_Setopt_Long (Req.Data, Constants.CURLOPT_POST, 1); Check_Code (Result, "set http PUT"); Result := Curl_Easy_Setopt_Long (Req.Data, Constants.CURLOPT_HEADER, 1); Check_Code (Result, "set header"); Result := Curl_Easy_Setopt_String (Req.Data, Constants.CURLOPT_CUSTOMREQUEST, PUT_TOKEN); Check_Code (Result, "set http PUT"); Result := Curl_Easy_Setopt_Slist (Req.Data, Constants.CURLOPT_HTTPHEADER, Req.Curl_Headers); Check_Code (Result, "set http GET headers"); Result := Curl_Easy_Setopt_String (Req.Data, Constants.CURLOPT_URL, Req.URL); Check_Code (Result, "set url"); Result := Curl_Easy_Setopt_String (Req.Data, Constants.CURLOPT_POSTFIELDS, Req.Content); Check_Code (Result, "set post data"); Result := Curl_Easy_Setopt_Long (Req.Data, Constants.CURLOPT_POSTFIELDSIZE, Data'Length); Check_Code (Result, "set post data"); Response := new Curl_Http_Response; Result := Curl_Easy_Setopt_Data (Req.Data, Constants.CURLOPT_WRITEDATA, Response); Check_Code (Result, "set write data"); Reply.Delegate := Response.all'Access; Result := Curl_Easy_Perform (Req.Data); Check_Code (Result, "get request"); Result := Curl_Easy_Getinfo_Long (Req.Data, Constants.CURLINFO_RESPONSE_CODE, Status'Access); Check_Code (Result, "get response code"); Response.Status := Natural (Status); end Do_Put; overriding procedure Finalize (Request : in out Curl_Http_Request) is begin if Request.Data /= System.Null_Address then Curl_Easy_Cleanup (Request.Data); Request.Data := System.Null_Address; end if; if Request.Curl_Headers /= null then Curl_Slist_Free_All (Request.Curl_Headers); Request.Curl_Headers := null; end if; Interfaces.C.Strings.Free (Request.URL); Interfaces.C.Strings.Free (Request.Content); end Finalize; -- ------------------------------ -- Get the response body as a string. -- ------------------------------ overriding function Get_Body (Reply : in Curl_Http_Response) return String is begin return Ada.Strings.Unbounded.To_String (Reply.Content); end Get_Body; -- ------------------------------ -- Get the response status code. -- ------------------------------ overriding function Get_Status (Reply : in Curl_Http_Response) return Natural is begin return Reply.Status; end Get_Status; end Util.Http.Clients.Curl;
Implement the Do_Put procedure
Implement the Do_Put procedure
Ada
apache-2.0
stcarrez/ada-util,stcarrez/ada-util
2c460ad37c86b03b3c47998c1d59ec2a9e22071f
src/gl/implementation/gl-objects-framebuffers.adb
src/gl/implementation/gl-objects-framebuffers.adb
-- Copyright (c) 2013 Felix Krause <[email protected]> -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES 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_Holders; with Ada.Unchecked_Conversion; with GL.API; with GL.Enums.Getter; with GL.Pixels.Extensions; with GL.Pixels.Queries; package body GL.Objects.Framebuffers is function Valid_Attachment (Attachment : Attachment_Point; Texture : Textures.Texture) return Boolean is use all type GL.Pixels.Internal_Format; Format : GL.Pixels.Internal_Format renames Texture.Internal_Format; begin case Attachment is when Depth_Stencil_Attachment => return GL.Pixels.Extensions.Depth_Stencil_Format (Format); when Depth_Attachment => return GL.Pixels.Extensions.Depth_Format (Format); when Stencil_Attachment => return GL.Pixels.Extensions.Stencil_Format (Format); when others => return GL.Pixels.Queries.Color_Renderable (Format, Texture.Kind); end case; end Valid_Attachment; function Status (Object : Framebuffer; Target : Framebuffer_Target'Class) return Framebuffer_Status is begin return API.Check_Named_Framebuffer_Status (Object.Reference.GL_Id, Target.Kind); end Status; procedure Set_Draw_Buffer (Object : Framebuffer; Selector : Buffers.Color_Buffer_Selector) is subtype Index_Type is Buffers.Draw_Buffer_Index; begin Object.Set_Draw_Buffers ((Index_Type'First => Selector, Index_Type'First + 1 .. Index_Type'Last => Buffers.None)); end Set_Draw_Buffer; procedure Set_Draw_Buffers (Object : Framebuffer; List : Buffers.Color_Buffer_List) is begin API.Named_Framebuffer_Draw_Buffers (Object.Reference.GL_Id, List'Length, List); Raise_Exception_On_OpenGL_Error; end Set_Draw_Buffers; procedure Set_Read_Buffer (Object : Framebuffer; Selector : Buffers.Color_Buffer_Selector) is begin API.Named_Framebuffer_Read_Buffer (Object.Reference.GL_Id, Selector); Raise_Exception_On_OpenGL_Error; end Set_Read_Buffer; procedure Attach_Texture (Object : Framebuffer; Attachment : Attachment_Point; Texture : Textures.Texture; Level : Textures.Mipmap_Level) is begin API.Named_Framebuffer_Texture (Object.Reference.GL_Id, Attachment, Texture.Raw_Id, Level); Raise_Exception_On_OpenGL_Error; end Attach_Texture; procedure Attach_Texture_Layer (Object : Framebuffer; Attachment : Attachment_Point; Texture : Textures.Texture; Level : Textures.Mipmap_Level; Layer : Natural) is begin API.Named_Framebuffer_Texture_Layer (Object.Reference.GL_Id, Attachment, Texture.Raw_Id, Level, Int (Layer)); Raise_Exception_On_OpenGL_Error; end Attach_Texture_Layer; procedure Detach (Object : Framebuffer; Attachment : Attachment_Point) is begin API.Named_Framebuffer_Texture (Object.Reference.GL_Id, Attachment, 0, 0); Raise_Exception_On_OpenGL_Error; end Detach; procedure Invalidate_Data (Object : Framebuffer; Attachments : Attachment_List) is begin API.Invalidate_Named_Framebuffer_Data (Object.Reference.GL_Id, Attachments'Length, Attachments); Raise_Exception_On_OpenGL_Error; end Invalidate_Data; procedure Invalidate_Sub_Data (Object : Framebuffer; Attachments : Attachment_List; X, Y : Int; Width, Height : Size) is begin API.Invalidate_Named_Framebuffer_Sub_Data (Object.Reference.GL_Id, Attachments'Length, Attachments, X, Y, Width, Height); Raise_Exception_On_OpenGL_Error; end Invalidate_Sub_Data; procedure Invalidate_Data (Object : Framebuffer; Attachments : Default_Attachment_List) is begin API.Invalidate_Named_Framebuffer_Data (Object.Reference.GL_Id, Attachments'Length, Attachments); Raise_Exception_On_OpenGL_Error; end Invalidate_Data; procedure Invalidate_Sub_Data (Object : Framebuffer; Attachments : Default_Attachment_List; X, Y : Int; Width, Height : Size) is begin API.Invalidate_Named_Framebuffer_Sub_Data (Object.Reference.GL_Id, Attachments'Length, Attachments, X, Y, Width, Height); Raise_Exception_On_OpenGL_Error; end Invalidate_Sub_Data; procedure Blit (Read_Object, Draw_Object : Framebuffer; Src_X0, Src_Y0, Src_X1, Src_Y1, Dst_X0, Dst_Y0, Dst_X1, Dst_Y1 : Int; Mask : Buffers.Buffer_Bits; Filter : Textures.Magnifying_Function) is use type Low_Level.Bitfield; function Convert is new Ada.Unchecked_Conversion (Buffers.Buffer_Bits, Low_Level.Bitfield); Raw_Bits : constant Low_Level.Bitfield := Convert (Mask) and 2#0100010100000000#; begin API.Blit_Named_Framebuffer (Read_Object.Reference.GL_Id, Draw_Object.Reference.GL_Id, Src_X0, Src_Y0, Src_X1, Src_Y1, Dst_X0, Dst_Y0, Dst_X1, Dst_Y1, Raw_Bits, Filter); Raise_Exception_On_OpenGL_Error; end Blit; procedure Set_Default_Width (Object : Framebuffer; Value : Size) is begin API.Named_Framebuffer_Parameter_Size (Object.Reference.GL_Id, Enums.Default_Width, Value); Raise_Exception_On_OpenGL_Error; end Set_Default_Width; function Default_Width (Object : Framebuffer) return Size is Ret : aliased Size; begin API.Get_Named_Framebuffer_Parameter_Size (Object.Reference.GL_Id, Enums.Default_Width, Ret'Unchecked_Access); Raise_Exception_On_OpenGL_Error; return Ret; end Default_Width; function Max_Framebuffer_Width return Size is Ret : Size := 16_384; begin API.Get_Size (Enums.Getter.Max_Framebuffer_Width, Ret); Raise_Exception_On_OpenGL_Error; return Ret; end Max_Framebuffer_Width; procedure Set_Default_Height (Object : Framebuffer; Value : Size) is begin API.Named_Framebuffer_Parameter_Size (Object.Reference.GL_Id, Enums.Default_Height, Value); Raise_Exception_On_OpenGL_Error; end Set_Default_Height; function Default_Height (Object : Framebuffer) return Size is Ret : aliased Size; begin API.Get_Named_Framebuffer_Parameter_Size (Object.Reference.GL_Id, Enums.Default_Height, Ret'Unchecked_Access); Raise_Exception_On_OpenGL_Error; return Ret; end Default_Height; function Max_Framebuffer_Height return Size is Ret : Size := 16_384; begin API.Get_Size (Enums.Getter.Max_Framebuffer_Height, Ret); Raise_Exception_On_OpenGL_Error; return Ret; end Max_Framebuffer_Height; procedure Set_Default_Layers (Object : Framebuffer; Value : Size) is begin API.Named_Framebuffer_Parameter_Size (Object.Reference.GL_Id, Enums.Default_Layers, Value); Raise_Exception_On_OpenGL_Error; end Set_Default_Layers; function Default_Layers (Object : Framebuffer) return Size is Ret : aliased Size; begin API.Get_Named_Framebuffer_Parameter_Size (Object.Reference.GL_Id, Enums.Default_Layers, Ret'Unchecked_Access); Raise_Exception_On_OpenGL_Error; return Ret; end Default_Layers; function Max_Framebuffer_Layers return Size is Ret : Size := 2_048; begin API.Get_Size (Enums.Getter.Max_Framebuffer_Layers, Ret); Raise_Exception_On_OpenGL_Error; return Ret; end Max_Framebuffer_Layers; procedure Set_Default_Samples (Object : Framebuffer; Value : Size) is begin API.Named_Framebuffer_Parameter_Size (Object.Reference.GL_Id, Enums.Default_Samples, Value); Raise_Exception_On_OpenGL_Error; end Set_Default_Samples; function Default_Samples (Object : Framebuffer) return Size is Ret : aliased Size; begin API.Get_Named_Framebuffer_Parameter_Size (Object.Reference.GL_Id, Enums.Default_Samples, Ret'Unchecked_Access); Raise_Exception_On_OpenGL_Error; return Ret; end Default_Samples; function Max_Framebuffer_Samples return Size is Ret : Size := 4; begin API.Get_Size (Enums.Getter.Max_Framebuffer_Samples, Ret); Raise_Exception_On_OpenGL_Error; return Ret; end Max_Framebuffer_Samples; procedure Set_Default_Fixed_Sample_Locations (Object : Framebuffer; Value : Boolean) is begin API.Named_Framebuffer_Parameter_Bool (Object.Reference.GL_Id, Enums.Default_Fixed_Sample_Locations, Low_Level.Bool (Value)); Raise_Exception_On_OpenGL_Error; end Set_Default_Fixed_Sample_Locations; function Default_Fixed_Sample_Locations (Object : Framebuffer) return Boolean is Ret : aliased Low_Level.Bool; begin API.Get_Named_Framebuffer_Parameter_Bool (Object.Reference.GL_Id, Enums.Default_Fixed_Sample_Locations, Ret'Unchecked_Access); Raise_Exception_On_OpenGL_Error; return Boolean (Ret); end Default_Fixed_Sample_Locations; overriding procedure Initialize_Id (Object : in out Framebuffer) is New_Id : UInt := 0; begin API.Create_Framebuffers (1, New_Id); Raise_Exception_On_OpenGL_Error; Object.Reference.GL_Id := New_Id; Object.Reference.Initialized := True; end Initialize_Id; overriding procedure Delete_Id (Object : in out Framebuffer) is Arr : constant Low_Level.UInt_Array := (1 => Object.Reference.GL_Id); begin API.Delete_Framebuffers (1, Arr); Raise_Exception_On_OpenGL_Error; Object.Reference.GL_Id := 0; Object.Reference.Initialized := False; end Delete_Id; package Framebuffer_Holder is new Ada.Containers.Indefinite_Holders (Element_Type => Framebuffer'Class); type Framebuffer_Target_Array is array (Enums.Framebuffer_Kind) of Framebuffer_Holder.Holder; Current_Framebuffers : Framebuffer_Target_Array; procedure Bind (Target : Framebuffer_Target; Object : Framebuffer'Class) is Holder : Framebuffer_Holder.Holder := Current_Framebuffers (Target.Kind); begin if Holder.Is_Empty or else Object /= Holder.Element then API.Bind_Framebuffer (Target.Kind, Object.Reference.GL_Id); Raise_Exception_On_OpenGL_Error; Holder.Replace_Element (Object); end if; end Bind; function Current (Target : Framebuffer_Target) return Framebuffer'Class is Holder : constant Framebuffer_Holder.Holder := Current_Framebuffers (Target.Kind); begin if Holder.Is_Empty then raise No_Object_Bound_Exception with Target.Kind'Image; else return Holder.Element; end if; end Current; procedure Clear_Color_Buffer (Object : Framebuffer; Index : Buffers.Draw_Buffer_Index; Data_Type : Pixels.Channel_Data_Type; Value : Colors.Color) is use all type GL.Pixels.Channel_Data_Type; begin case Data_Type is when Float_Type | Signed_Normalized | Unsigned_Normalized => API.Clear_Named_Framebuffer_Color_Real (Object.Reference.GL_Id, Enums.Color_Buffer, Index, Value); when Int_Type => API.Clear_Named_Framebuffer_Color_Signed_Int (Object.Reference.GL_Id, Enums.Color_Buffer, Index, Value); when Unsigned_Int_Type => API.Clear_Named_Framebuffer_Color_Unsigned_Int (Object.Reference.GL_Id, Enums.Color_Buffer, Index, Value); when None => raise Constraint_Error; end case; Raise_Exception_On_OpenGL_Error; end Clear_Color_Buffer; procedure Clear_Depth_Buffer (Object : Framebuffer; Value : Buffers.Depth) is Aliased_Value : aliased Buffers.Depth := Value; begin API.Clear_Named_Framebuffer_Depth (Object.Reference.GL_Id, Enums.Depth_Buffer, 0, Aliased_Value); Raise_Exception_On_OpenGL_Error; end Clear_Depth_Buffer; procedure Clear_Stencil_Buffer (Object : Framebuffer; Value : Buffers.Stencil_Index) is Aliased_Value : aliased Buffers.Stencil_Index := Value; begin API.Clear_Named_Framebuffer_Stencil (Object.Reference.GL_Id, Enums.Stencil_Buffer, 0, Aliased_Value); Raise_Exception_On_OpenGL_Error; end Clear_Stencil_Buffer; procedure Clear_Depth_And_Stencil_Buffer (Object : Framebuffer; Depth_Value : Buffers.Depth; Stencil_Value : Buffers.Stencil_Index) is begin API.Clear_Named_Framebuffer_Depth_Stencil (Object.Reference.GL_Id, Enums.Depth_Stencil_Buffer, 0, Depth_Value, Stencil_Value); Raise_Exception_On_OpenGL_Error; end Clear_Depth_And_Stencil_Buffer; ----------------------------------------------------------------------------- type Default_Framebuffer_Type is new Framebuffer with null record; overriding procedure Initialize_Id (Object : in out Default_Framebuffer_Type) is null; overriding procedure Delete_Id (Object : in out Default_Framebuffer_Type) is null; Default_FB : constant Default_Framebuffer_Type := Default_Framebuffer_Type'(GL_Object with null record); function Default_Framebuffer return Framebuffer is (Framebuffer (Default_FB)); end GL.Objects.Framebuffers;
-- Copyright (c) 2013 Felix Krause <[email protected]> -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES 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_Holders; with Ada.Unchecked_Conversion; with GL.API; with GL.Enums.Getter; with GL.Pixels.Extensions; with GL.Pixels.Queries; package body GL.Objects.Framebuffers is function Valid_Attachment (Attachment : Attachment_Point; Texture : Textures.Texture) return Boolean is Format : GL.Pixels.Internal_Format renames Texture.Internal_Format; begin case Attachment is when Depth_Stencil_Attachment => return GL.Pixels.Extensions.Depth_Stencil_Format (Format); when Depth_Attachment => return GL.Pixels.Extensions.Depth_Format (Format); when Stencil_Attachment => return GL.Pixels.Extensions.Stencil_Format (Format); when others => return GL.Pixels.Queries.Color_Renderable (Format, Texture.Kind); end case; end Valid_Attachment; function Status (Object : Framebuffer; Target : Framebuffer_Target'Class) return Framebuffer_Status is begin return API.Check_Named_Framebuffer_Status (Object.Reference.GL_Id, Target.Kind); end Status; procedure Set_Draw_Buffer (Object : Framebuffer; Selector : Buffers.Color_Buffer_Selector) is subtype Index_Type is Buffers.Draw_Buffer_Index; begin Object.Set_Draw_Buffers ((Index_Type'First => Selector, Index_Type'First + 1 .. Index_Type'Last => Buffers.None)); end Set_Draw_Buffer; procedure Set_Draw_Buffers (Object : Framebuffer; List : Buffers.Color_Buffer_List) is begin API.Named_Framebuffer_Draw_Buffers (Object.Reference.GL_Id, List'Length, List); Raise_Exception_On_OpenGL_Error; end Set_Draw_Buffers; procedure Set_Read_Buffer (Object : Framebuffer; Selector : Buffers.Color_Buffer_Selector) is begin API.Named_Framebuffer_Read_Buffer (Object.Reference.GL_Id, Selector); Raise_Exception_On_OpenGL_Error; end Set_Read_Buffer; procedure Attach_Texture (Object : Framebuffer; Attachment : Attachment_Point; Texture : Textures.Texture; Level : Textures.Mipmap_Level) is begin API.Named_Framebuffer_Texture (Object.Reference.GL_Id, Attachment, Texture.Raw_Id, Level); Raise_Exception_On_OpenGL_Error; end Attach_Texture; procedure Attach_Texture_Layer (Object : Framebuffer; Attachment : Attachment_Point; Texture : Textures.Texture; Level : Textures.Mipmap_Level; Layer : Natural) is begin API.Named_Framebuffer_Texture_Layer (Object.Reference.GL_Id, Attachment, Texture.Raw_Id, Level, Int (Layer)); Raise_Exception_On_OpenGL_Error; end Attach_Texture_Layer; procedure Detach (Object : Framebuffer; Attachment : Attachment_Point) is begin API.Named_Framebuffer_Texture (Object.Reference.GL_Id, Attachment, 0, 0); Raise_Exception_On_OpenGL_Error; end Detach; procedure Invalidate_Data (Object : Framebuffer; Attachments : Attachment_List) is begin API.Invalidate_Named_Framebuffer_Data (Object.Reference.GL_Id, Attachments'Length, Attachments); Raise_Exception_On_OpenGL_Error; end Invalidate_Data; procedure Invalidate_Sub_Data (Object : Framebuffer; Attachments : Attachment_List; X, Y : Int; Width, Height : Size) is begin API.Invalidate_Named_Framebuffer_Sub_Data (Object.Reference.GL_Id, Attachments'Length, Attachments, X, Y, Width, Height); Raise_Exception_On_OpenGL_Error; end Invalidate_Sub_Data; procedure Invalidate_Data (Object : Framebuffer; Attachments : Default_Attachment_List) is begin API.Invalidate_Named_Framebuffer_Data (Object.Reference.GL_Id, Attachments'Length, Attachments); Raise_Exception_On_OpenGL_Error; end Invalidate_Data; procedure Invalidate_Sub_Data (Object : Framebuffer; Attachments : Default_Attachment_List; X, Y : Int; Width, Height : Size) is begin API.Invalidate_Named_Framebuffer_Sub_Data (Object.Reference.GL_Id, Attachments'Length, Attachments, X, Y, Width, Height); Raise_Exception_On_OpenGL_Error; end Invalidate_Sub_Data; procedure Blit (Read_Object, Draw_Object : Framebuffer; Src_X0, Src_Y0, Src_X1, Src_Y1, Dst_X0, Dst_Y0, Dst_X1, Dst_Y1 : Int; Mask : Buffers.Buffer_Bits; Filter : Textures.Magnifying_Function) is use type Low_Level.Bitfield; function Convert is new Ada.Unchecked_Conversion (Buffers.Buffer_Bits, Low_Level.Bitfield); Raw_Bits : constant Low_Level.Bitfield := Convert (Mask) and 2#0100010100000000#; begin API.Blit_Named_Framebuffer (Read_Object.Reference.GL_Id, Draw_Object.Reference.GL_Id, Src_X0, Src_Y0, Src_X1, Src_Y1, Dst_X0, Dst_Y0, Dst_X1, Dst_Y1, Raw_Bits, Filter); Raise_Exception_On_OpenGL_Error; end Blit; procedure Set_Default_Width (Object : Framebuffer; Value : Size) is begin API.Named_Framebuffer_Parameter_Size (Object.Reference.GL_Id, Enums.Default_Width, Value); Raise_Exception_On_OpenGL_Error; end Set_Default_Width; function Default_Width (Object : Framebuffer) return Size is Ret : aliased Size; begin API.Get_Named_Framebuffer_Parameter_Size (Object.Reference.GL_Id, Enums.Default_Width, Ret'Unchecked_Access); Raise_Exception_On_OpenGL_Error; return Ret; end Default_Width; function Max_Framebuffer_Width return Size is Ret : Size := 16_384; begin API.Get_Size (Enums.Getter.Max_Framebuffer_Width, Ret); Raise_Exception_On_OpenGL_Error; return Ret; end Max_Framebuffer_Width; procedure Set_Default_Height (Object : Framebuffer; Value : Size) is begin API.Named_Framebuffer_Parameter_Size (Object.Reference.GL_Id, Enums.Default_Height, Value); Raise_Exception_On_OpenGL_Error; end Set_Default_Height; function Default_Height (Object : Framebuffer) return Size is Ret : aliased Size; begin API.Get_Named_Framebuffer_Parameter_Size (Object.Reference.GL_Id, Enums.Default_Height, Ret'Unchecked_Access); Raise_Exception_On_OpenGL_Error; return Ret; end Default_Height; function Max_Framebuffer_Height return Size is Ret : Size := 16_384; begin API.Get_Size (Enums.Getter.Max_Framebuffer_Height, Ret); Raise_Exception_On_OpenGL_Error; return Ret; end Max_Framebuffer_Height; procedure Set_Default_Layers (Object : Framebuffer; Value : Size) is begin API.Named_Framebuffer_Parameter_Size (Object.Reference.GL_Id, Enums.Default_Layers, Value); Raise_Exception_On_OpenGL_Error; end Set_Default_Layers; function Default_Layers (Object : Framebuffer) return Size is Ret : aliased Size; begin API.Get_Named_Framebuffer_Parameter_Size (Object.Reference.GL_Id, Enums.Default_Layers, Ret'Unchecked_Access); Raise_Exception_On_OpenGL_Error; return Ret; end Default_Layers; function Max_Framebuffer_Layers return Size is Ret : Size := 2_048; begin API.Get_Size (Enums.Getter.Max_Framebuffer_Layers, Ret); Raise_Exception_On_OpenGL_Error; return Ret; end Max_Framebuffer_Layers; procedure Set_Default_Samples (Object : Framebuffer; Value : Size) is begin API.Named_Framebuffer_Parameter_Size (Object.Reference.GL_Id, Enums.Default_Samples, Value); Raise_Exception_On_OpenGL_Error; end Set_Default_Samples; function Default_Samples (Object : Framebuffer) return Size is Ret : aliased Size; begin API.Get_Named_Framebuffer_Parameter_Size (Object.Reference.GL_Id, Enums.Default_Samples, Ret'Unchecked_Access); Raise_Exception_On_OpenGL_Error; return Ret; end Default_Samples; function Max_Framebuffer_Samples return Size is Ret : Size := 4; begin API.Get_Size (Enums.Getter.Max_Framebuffer_Samples, Ret); Raise_Exception_On_OpenGL_Error; return Ret; end Max_Framebuffer_Samples; procedure Set_Default_Fixed_Sample_Locations (Object : Framebuffer; Value : Boolean) is begin API.Named_Framebuffer_Parameter_Bool (Object.Reference.GL_Id, Enums.Default_Fixed_Sample_Locations, Low_Level.Bool (Value)); Raise_Exception_On_OpenGL_Error; end Set_Default_Fixed_Sample_Locations; function Default_Fixed_Sample_Locations (Object : Framebuffer) return Boolean is Ret : aliased Low_Level.Bool; begin API.Get_Named_Framebuffer_Parameter_Bool (Object.Reference.GL_Id, Enums.Default_Fixed_Sample_Locations, Ret'Unchecked_Access); Raise_Exception_On_OpenGL_Error; return Boolean (Ret); end Default_Fixed_Sample_Locations; overriding procedure Initialize_Id (Object : in out Framebuffer) is New_Id : UInt := 0; begin API.Create_Framebuffers (1, New_Id); Raise_Exception_On_OpenGL_Error; Object.Reference.GL_Id := New_Id; Object.Reference.Initialized := True; end Initialize_Id; overriding procedure Delete_Id (Object : in out Framebuffer) is Arr : constant Low_Level.UInt_Array := (1 => Object.Reference.GL_Id); begin API.Delete_Framebuffers (1, Arr); Raise_Exception_On_OpenGL_Error; Object.Reference.GL_Id := 0; Object.Reference.Initialized := False; end Delete_Id; package Framebuffer_Holder is new Ada.Containers.Indefinite_Holders (Element_Type => Framebuffer'Class); type Framebuffer_Target_Array is array (Enums.Framebuffer_Kind) of Framebuffer_Holder.Holder; Current_Framebuffers : Framebuffer_Target_Array; procedure Bind (Target : Framebuffer_Target; Object : Framebuffer'Class) is Holder : Framebuffer_Holder.Holder := Current_Framebuffers (Target.Kind); begin if Holder.Is_Empty or else Object /= Holder.Element then API.Bind_Framebuffer (Target.Kind, Object.Reference.GL_Id); Raise_Exception_On_OpenGL_Error; Holder.Replace_Element (Object); end if; end Bind; function Current (Target : Framebuffer_Target) return Framebuffer'Class is Holder : constant Framebuffer_Holder.Holder := Current_Framebuffers (Target.Kind); begin if Holder.Is_Empty then raise No_Object_Bound_Exception with Target.Kind'Image; else return Holder.Element; end if; end Current; procedure Clear_Color_Buffer (Object : Framebuffer; Index : Buffers.Draw_Buffer_Index; Data_Type : Pixels.Channel_Data_Type; Value : Colors.Color) is use all type GL.Pixels.Channel_Data_Type; begin case Data_Type is when Float_Type | Signed_Normalized | Unsigned_Normalized => API.Clear_Named_Framebuffer_Color_Real (Object.Reference.GL_Id, Enums.Color_Buffer, Index, Value); when Int_Type => API.Clear_Named_Framebuffer_Color_Signed_Int (Object.Reference.GL_Id, Enums.Color_Buffer, Index, Value); when Unsigned_Int_Type => API.Clear_Named_Framebuffer_Color_Unsigned_Int (Object.Reference.GL_Id, Enums.Color_Buffer, Index, Value); when None => raise Constraint_Error; end case; Raise_Exception_On_OpenGL_Error; end Clear_Color_Buffer; procedure Clear_Depth_Buffer (Object : Framebuffer; Value : Buffers.Depth) is Aliased_Value : aliased Buffers.Depth := Value; begin API.Clear_Named_Framebuffer_Depth (Object.Reference.GL_Id, Enums.Depth_Buffer, 0, Aliased_Value); Raise_Exception_On_OpenGL_Error; end Clear_Depth_Buffer; procedure Clear_Stencil_Buffer (Object : Framebuffer; Value : Buffers.Stencil_Index) is Aliased_Value : aliased Buffers.Stencil_Index := Value; begin API.Clear_Named_Framebuffer_Stencil (Object.Reference.GL_Id, Enums.Stencil_Buffer, 0, Aliased_Value); Raise_Exception_On_OpenGL_Error; end Clear_Stencil_Buffer; procedure Clear_Depth_And_Stencil_Buffer (Object : Framebuffer; Depth_Value : Buffers.Depth; Stencil_Value : Buffers.Stencil_Index) is begin API.Clear_Named_Framebuffer_Depth_Stencil (Object.Reference.GL_Id, Enums.Depth_Stencil_Buffer, 0, Depth_Value, Stencil_Value); Raise_Exception_On_OpenGL_Error; end Clear_Depth_And_Stencil_Buffer; ----------------------------------------------------------------------------- type Default_Framebuffer_Type is new Framebuffer with null record; overriding procedure Initialize_Id (Object : in out Default_Framebuffer_Type) is null; overriding procedure Delete_Id (Object : in out Default_Framebuffer_Type) is null; Default_FB : constant Default_Framebuffer_Type := Default_Framebuffer_Type'(GL_Object with null record); function Default_Framebuffer return Framebuffer is (Framebuffer (Default_FB)); end GL.Objects.Framebuffers;
Remove useless "use all type" clause
gl: Remove useless "use all type" clause Signed-off-by: onox <[email protected]>
Ada
apache-2.0
onox/orka
1592bbfb48172ee9beed77646de106a6bb0a5d8d
src/wiki-render.ads
src/wiki-render.ads
----------------------------------------------------------------------- -- wiki-render -- Wiki renderer -- Copyright (C) 2015, 2016 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Strings.Wide_Wide_Unbounded; with Wiki.Nodes; with Wiki.Documents; package Wiki.Render is pragma Preelaborate; use Ada.Strings.Wide_Wide_Unbounded; type Link_Renderer is limited interface; type Link_Renderer_Access is access all Link_Renderer'Class; -- Get the image link that must be rendered from the wiki image link. procedure Make_Image_Link (Renderer : in Link_Renderer; Link : in Wide_Wide_String; URI : out Unbounded_Wide_Wide_String; Width : out Natural; Height : out Natural) is abstract; -- Get the page link that must be rendered from the wiki page link. procedure Make_Page_Link (Renderer : in Link_Renderer; Link : in Wide_Wide_String; URI : out Unbounded_Wide_Wide_String; Exists : out Boolean) is abstract; type Default_Link_Renderer is new Link_Renderer with null record; -- Get the image link that must be rendered from the wiki image link. overriding procedure Make_Image_Link (Renderer : in Default_Link_Renderer; Link : in Wide_Wide_String; URI : out Unbounded_Wide_Wide_String; Width : out Natural; Height : out Natural); -- Get the page link that must be rendered from the wiki page link. overriding procedure Make_Page_Link (Renderer : in Default_Link_Renderer; Link : in Wide_Wide_String; URI : out Unbounded_Wide_Wide_String; Exists : out Boolean); -- ------------------------------ -- Document renderer -- ------------------------------ type Renderer is limited interface; type Renderer_Access is access all Renderer'Class; -- Render the node instance from the document. procedure Render (Engine : in out Renderer; Doc : in Wiki.Documents.Document; Node : in Wiki.Nodes.Node_Type) is abstract; -- Finish the rendering after complete wiki document nodes are rendered. procedure Finish (Document : in out Renderer) is abstract; -- Render the list of nodes from the document. procedure Render (Engine : in out Renderer'Class; Doc : in Wiki.Documents.Document; List : in Wiki.Nodes.Node_List_Access); -- Render the document. procedure Render (Engine : in out Renderer'Class; Doc : in Wiki.Documents.Document); end Wiki.Render;
----------------------------------------------------------------------- -- wiki-render -- Wiki renderer -- Copyright (C) 2015, 2016 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Strings.Wide_Wide_Unbounded; with Wiki.Nodes; with Wiki.Documents; -- == Wiki Renderer == -- The <tt>Wiki.Render</tt> package represents the renderer that takes a wiki document -- and render the result either in text, HTML or another format. package Wiki.Render is pragma Preelaborate; use Ada.Strings.Wide_Wide_Unbounded; type Link_Renderer is limited interface; type Link_Renderer_Access is access all Link_Renderer'Class; -- Get the image link that must be rendered from the wiki image link. procedure Make_Image_Link (Renderer : in Link_Renderer; Link : in Wide_Wide_String; URI : out Unbounded_Wide_Wide_String; Width : out Natural; Height : out Natural) is abstract; -- Get the page link that must be rendered from the wiki page link. procedure Make_Page_Link (Renderer : in Link_Renderer; Link : in Wide_Wide_String; URI : out Unbounded_Wide_Wide_String; Exists : out Boolean) is abstract; type Default_Link_Renderer is new Link_Renderer with null record; -- Get the image link that must be rendered from the wiki image link. overriding procedure Make_Image_Link (Renderer : in Default_Link_Renderer; Link : in Wide_Wide_String; URI : out Unbounded_Wide_Wide_String; Width : out Natural; Height : out Natural); -- Get the page link that must be rendered from the wiki page link. overriding procedure Make_Page_Link (Renderer : in Default_Link_Renderer; Link : in Wide_Wide_String; URI : out Unbounded_Wide_Wide_String; Exists : out Boolean); -- ------------------------------ -- Document renderer -- ------------------------------ type Renderer is limited interface; type Renderer_Access is access all Renderer'Class; -- Render the node instance from the document. procedure Render (Engine : in out Renderer; Doc : in Wiki.Documents.Document; Node : in Wiki.Nodes.Node_Type) is abstract; -- Finish the rendering pass after all the wiki document nodes are rendered. procedure Finish (Engine : in out Renderer) is abstract; -- Render the list of nodes from the document. procedure Render (Engine : in out Renderer'Class; Doc : in Wiki.Documents.Document; List : in Wiki.Nodes.Node_List_Access); -- Render the document. procedure Render (Engine : in out Renderer'Class; Doc : in Wiki.Documents.Document); end Wiki.Render;
Add some documentation
Add some documentation
Ada
apache-2.0
stcarrez/ada-wiki,stcarrez/ada-wiki
26214e9b6524bfc060c9254a4b23b49c1b147677
src/wiki-render-wiki.ads
src/wiki-render-wiki.ads
----------------------------------------------------------------------- -- 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; Title : 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; Optional : in Boolean := False); procedure Need_Separator_Line (Engine : in out Wiki_Renderer); procedure Close_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; Need_Newline : Boolean := False; Need_Space : Boolean := False; Empty_Line : Boolean := True; Empty_Previous_Line : Boolean := True; Keep_Content : Boolean := False; In_List : Boolean := False; Invert_Header_Level : Boolean := False; Allow_Link_Language : Boolean := False; Link_First : Boolean := False; Html_Blockquote : Boolean := False; Line_Count : Natural := 0; 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; Title : 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; Optional : in Boolean := False); procedure Need_Separator_Line (Engine : in out Wiki_Renderer); procedure Close_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; Need_Newline : Boolean := False; Need_Space : Boolean := False; Empty_Line : Boolean := True; Empty_Previous_Line : Boolean := True; Keep_Content : Natural := 0; In_List : Boolean := False; Invert_Header_Level : Boolean := False; Allow_Link_Language : Boolean := False; Link_First : Boolean := False; Html_Blockquote : Boolean := False; Line_Count : Natural := 0; 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;
Change Keep_Content to an integer to handle nested elements
Change Keep_Content to an integer to handle nested elements
Ada
apache-2.0
stcarrez/ada-wiki,stcarrez/ada-wiki
77c10091e6881bc6e91db6da554134804e5a6643
regtests/asf-applications-tests.ads
regtests/asf-applications-tests.ads
----------------------------------------------------------------------- -- asf-applications-tests - ASF Application tests using ASFUnit -- Copyright (C) 2011 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Tests; with Util.Beans.Basic; with Util.Beans.Objects; with Util.Beans.Methods; with Util.Beans.Basic.Lists; with Ada.Strings.Unbounded; package ASF.Applications.Tests is use Ada.Strings.Unbounded; procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite); type Test is new Util.Tests.Test with null record; -- Initialize the test application overriding procedure Set_Up (T : in out Test); -- Test a GET request on a static file served by the File_Servlet. procedure Test_Get_File (T : in out Test); -- Test a GET 404 error on missing static file served by the File_Servlet. procedure Test_Get_404 (T : in out Test); -- Test a GET request on the measure servlet procedure Test_Get_Measures (T : in out Test); -- Test an invalid HTTP request. procedure Test_Invalid_Request (T : in out Test); -- Test a GET+POST request with submitted values and an action method called on the bean. procedure Test_Form_Post (T : in out Test); -- Test a POST request with an invalid submitted value procedure Test_Form_Post_Validation_Error (T : in out Test); -- Test a GET+POST request with form having <h:selectOneMenu> element. procedure Test_Form_Post_Select (T : in out Test); -- Test a POST request to invoke a bean method. procedure Test_Ajax_Action (T : in out Test); -- Test a POST request to invoke a bean method. -- Verify that invalid requests raise an error. procedure Test_Ajax_Action_Error (T : in out Test); -- Test a POST/REDIRECT/GET request with a flash information passed in between. procedure Test_Flash_Object (T : in out Test); -- Test a GET+POST request with the default navigation rule based on the outcome. procedure Test_Default_Navigation_Rule (T : in out Test); -- Test a GET request with meta data and view parameters. procedure Test_View_Params (T : in out Test); -- Test a GET request with meta data and view action. procedure Test_View_Action (T : in out Test); type Form_Bean is new Util.Beans.Basic.Bean and Util.Beans.Methods.Method_Bean with record Name : Unbounded_String; Password : Unbounded_String; Email : Unbounded_String; Called : Natural := 0; Gender : Unbounded_String; Use_Flash : Boolean := False; Def_Nav : Boolean := False; end record; type Form_Bean_Access is access all Form_Bean'Class; -- Get the value identified by the name. overriding function Get_Value (From : in Form_Bean; Name : in String) return Util.Beans.Objects.Object; -- Set the value identified by the name. overriding procedure Set_Value (From : in out Form_Bean; Name : in String; Value : in Util.Beans.Objects.Object); -- This bean provides some methods that can be used in a Method_Expression overriding function Get_Method_Bindings (From : in Form_Bean) return Util.Beans.Methods.Method_Binding_Array_Access; -- Action to save the form procedure Save (Data : in out Form_Bean; Outcome : in out Unbounded_String); -- Create a list of forms. package Form_Lists is new Util.Beans.Basic.Lists (Form_Bean); -- Create a list of forms. function Create_Form_List return Util.Beans.Basic.Readonly_Bean_Access; -- Initialize the ASF application for the unit test. procedure Initialize_Test_Application; end ASF.Applications.Tests;
----------------------------------------------------------------------- -- asf-applications-tests - ASF Application tests using ASFUnit -- Copyright (C) 2011 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Tests; with Util.Beans.Basic; with Util.Beans.Objects; with Util.Beans.Methods; with Util.Beans.Basic.Lists; with Ada.Strings.Unbounded; package ASF.Applications.Tests is use Ada.Strings.Unbounded; Test_Exception : exception; procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite); type Test is new Util.Tests.Test with null record; -- Initialize the test application overriding procedure Set_Up (T : in out Test); -- Test a GET request on a static file served by the File_Servlet. procedure Test_Get_File (T : in out Test); -- Test a GET 404 error on missing static file served by the File_Servlet. procedure Test_Get_404 (T : in out Test); -- Test a GET request on the measure servlet procedure Test_Get_Measures (T : in out Test); -- Test an invalid HTTP request. procedure Test_Invalid_Request (T : in out Test); -- Test a GET+POST request with submitted values and an action method called on the bean. procedure Test_Form_Post (T : in out Test); -- Test a POST request with an invalid submitted value procedure Test_Form_Post_Validation_Error (T : in out Test); -- Test a GET+POST request with form having <h:selectOneMenu> element. procedure Test_Form_Post_Select (T : in out Test); -- Test a POST request to invoke a bean method. procedure Test_Ajax_Action (T : in out Test); -- Test a POST request to invoke a bean method. -- Verify that invalid requests raise an error. procedure Test_Ajax_Action_Error (T : in out Test); -- Test a POST/REDIRECT/GET request with a flash information passed in between. procedure Test_Flash_Object (T : in out Test); -- Test a GET+POST request with the default navigation rule based on the outcome. procedure Test_Default_Navigation_Rule (T : in out Test); -- Test a GET request with meta data and view parameters. procedure Test_View_Params (T : in out Test); -- Test a GET request with meta data and view action. procedure Test_View_Action (T : in out Test); type Form_Bean is new Util.Beans.Basic.Bean and Util.Beans.Methods.Method_Bean with record Name : Unbounded_String; Password : Unbounded_String; Email : Unbounded_String; Called : Natural := 0; Gender : Unbounded_String; Use_Flash : Boolean := False; Def_Nav : Boolean := False; Perm_Error : Boolean := False; end record; type Form_Bean_Access is access all Form_Bean'Class; -- Get the value identified by the name. overriding function Get_Value (From : in Form_Bean; Name : in String) return Util.Beans.Objects.Object; -- Set the value identified by the name. overriding procedure Set_Value (From : in out Form_Bean; Name : in String; Value : in Util.Beans.Objects.Object); -- This bean provides some methods that can be used in a Method_Expression overriding function Get_Method_Bindings (From : in Form_Bean) return Util.Beans.Methods.Method_Binding_Array_Access; -- Action to save the form procedure Save (Data : in out Form_Bean; Outcome : in out Unbounded_String); -- Create a list of forms. package Form_Lists is new Util.Beans.Basic.Lists (Form_Bean); -- Create a list of forms. function Create_Form_List return Util.Beans.Basic.Readonly_Bean_Access; -- Initialize the ASF application for the unit test. procedure Initialize_Test_Application; end ASF.Applications.Tests;
Add flag on form bean to raise an exception in the action bean
Add flag on form bean to raise an exception in the action bean
Ada
apache-2.0
Letractively/ada-asf,Letractively/ada-asf,Letractively/ada-asf
928e64e9103a675321b0d45a354361c1a89db86b
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; 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); 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. 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); 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 the Is_Hidden member to hide/show text dynamically
Add the Is_Hidden member to hide/show text dynamically
Ada
apache-2.0
stcarrez/ada-wiki,stcarrez/ada-wiki
96428c4a728a1e2537ea44594a47e76b08a1e37c
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, 2018, 2019, 2020 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with 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); Caller.Add_Test (Suite, "Test AWA.Blogs.Beans.Update_Post (Publish_Date)", Test_Update_Publish_Date'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_Matches (T, "The post you are looking for does not exist", Reply, "Blog post missing page is invalid", ASF.Responses.SC_NOT_FOUND); if Post = "" then return; end if; ASF.Tests.Do_Get (Request, Reply, "/blogs/post.html?post=" & Post, "blog-post.html"); ASF.Tests.Assert_Matches (T, ".*The blog post.*content.*", 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); ASF.Tests.Do_Get (Request, Reply, "/blogs/admin/create-blog.html", "create-blog-get.html"); T.Assert (Reply.Get_Status = ASF.Responses.SC_OK, "Invalid response after getting blog creation page"); ASF.Tests.Assert_Matches (T, "<dl id=.title.*<dt><label for=.title.*" & "<dd><input type=.text.*", Reply, "Blog post admin page is missing input field"); 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"); Request.Set_Parameter ("post-format", "dotclear"); 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", "POST_PUBLISHED"); Request.Set_Parameter ("post-format", "dotclear"); 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 updating the publication date by simulating web requests. -- ------------------------------ procedure Test_Update_Publish_Date (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_id", To_String (T.Post_Ident)); Request.Set_Parameter ("blog_id", Ident); ASF.Tests.Do_Get (Request, Reply, "/blogs/admin/edit.html", "edit-post-form.html"); 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", "POST_PUBLISHED"); Request.Set_Parameter ("post-format", "dotclear"); Request.Set_Parameter ("post-status", "1"); Request.Set_Parameter ("allow-comment", "0"); Request.Set_Parameter ("publish-date", ""); 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_Publish_Date; -- ------------------------------ -- 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, 2018, 2019, 2020 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with 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); Caller.Add_Test (Suite, "Test AWA.Blogs.Beans.Update_Post (Publish_Date)", Test_Update_Publish_Date'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_Matches (T, "The post you are looking for does not exist", Reply, "Blog post missing page is invalid", ASF.Responses.SC_NOT_FOUND); if Post = "" then return; end if; ASF.Tests.Do_Get (Request, Reply, "/blogs/post.html?post=" & Post, "blog-post.html"); ASF.Tests.Assert_Matches (T, ".*The blog post.*content.*", 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); ASF.Tests.Do_Get (Request, Reply, "/blogs/admin/create-blog.html", "create-blog-get.html"); T.Assert (Reply.Get_Status = ASF.Responses.SC_OK, "Invalid response after getting blog creation page"); ASF.Tests.Assert_Matches (T, "<dl id=.title.*<dt><label for=.title.*" & "<dd><input type=.text.*", Reply, "Blog post admin page is missing input field"); 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", "POST_PUBLISHED"); Request.Set_Parameter ("allow-comment", "0"); Request.Set_Parameter ("post-format", "FORMAT_DOTCLEAR"); 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", "POST_PUBLISHED"); Request.Set_Parameter ("post-format", "FORMAT_DOTCLEAR"); 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 updating the publication date by simulating web requests. -- ------------------------------ procedure Test_Update_Publish_Date (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_id", To_String (T.Post_Ident)); Request.Set_Parameter ("blog_id", Ident); ASF.Tests.Do_Get (Request, Reply, "/blogs/admin/edit.html", "edit-post-form.html"); 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-format", "FORMAT_DOTCLEAR"); Request.Set_Parameter ("post-status", "POST_PUBLISHED"); Request.Set_Parameter ("allow-comment", "0"); Request.Set_Parameter ("publish-date", ""); 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_Publish_Date; -- ------------------------------ -- 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 unit tests
Fix unit tests
Ada
apache-2.0
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
77676e8f28c44c9ae3b7fe303710a945841b9185
regtests/ado-drivers-tests.adb
regtests/ado-drivers-tests.adb
----------------------------------------------------------------------- -- ado-drivers-tests -- Unit tests for database drivers -- Copyright (C) 2014, 2015, 2016 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Exceptions; with Util.Test_Caller; with ADO.Statements; with ADO.Sessions; with ADO.Drivers.Connections; package body ADO.Drivers.Tests is use ADO.Drivers.Connections; package Caller is new Util.Test_Caller (Test, "ADO.Drivers"); procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is begin Caller.Add_Test (Suite, "Test ADO.Drivers.Initialize", Test_Initialize'Access); Caller.Add_Test (Suite, "Test ADO.Drivers.Get_Config", Test_Get_Config'Access); Caller.Add_Test (Suite, "Test ADO.Drivers.Get_Driver", Test_Get_Driver'Access); Caller.Add_Test (Suite, "Test ADO.Drivers.Get_Driver_Index", Test_Get_Driver_Index'Access); Caller.Add_Test (Suite, "Test ADO.Drivers.Get_Driver", Test_Load_Invalid_Driver'Access); Caller.Add_Test (Suite, "Test ADO.Drivers.Connections.Set_Connection", Test_Set_Connection'Access); Caller.Add_Test (Suite, "Test ADO.Drivers.Connections.Set_Connection (Errors)", Test_Set_Connection_Error'Access); Caller.Add_Test (Suite, "Test ADO.Drivers.Connections.Set_Server", Test_Set_Connection_Server'Access); Caller.Add_Test (Suite, "Test ADO.Drivers.Connections.Set_Port", Test_Set_Connection_Port'Access); Caller.Add_Test (Suite, "Test ADO.Drivers.Connections.Set_Database", Test_Set_Connection_Database'Access); Caller.Add_Test (Suite, "Test ADO.Databases (Errors)", Test_Empty_Connection'Access); end Add_Tests; -- ------------------------------ -- Test the Initialize operation. -- ------------------------------ procedure Test_Initialize (T : in out Test) is pragma Unreferenced (T); begin ADO.Drivers.Initialize ("test-missing-config.properties"); end Test_Initialize; -- ------------------------------ -- Test the Get_Config operation. -- ------------------------------ procedure Test_Get_Config (T : in out Test) is begin T.Assert (ADO.Drivers.Get_Config ("test.database")'Length > 0, "The Get_Config operation returned no value for the test database"); end Test_Get_Config; -- ------------------------------ -- Test the Get_Driver operation. -- ------------------------------ procedure Test_Get_Driver (T : in out Test) is Mysql_Driver : constant Driver_Access := ADO.Drivers.Connections.Get_Driver ("mysql"); Sqlite_Driver : constant Driver_Access := ADO.Drivers.Connections.Get_Driver ("sqlite"); begin T.Assert (Mysql_Driver /= null or Sqlite_Driver /= null, "No database driver was found!"); end Test_Get_Driver; -- ------------------------------ -- Test loading some invalid database driver. -- ------------------------------ procedure Test_Load_Invalid_Driver (T : in out Test) is Invalid_Driver : constant Driver_Access := ADO.Drivers.Connections.Get_Driver ("invalid"); begin T.Assert (Invalid_Driver = null, "The Get_Driver operation must return null for invalid drivers"); end Test_Load_Invalid_Driver; -- ------------------------------ -- Test the Get_Driver_Index operation. -- ------------------------------ procedure Test_Get_Driver_Index (T : in out Test) is Mysql_Driver : constant Driver_Access := ADO.Drivers.Connections.Get_Driver ("mysql"); Sqlite_Driver : constant Driver_Access := ADO.Drivers.Connections.Get_Driver ("sqlite"); begin if Mysql_Driver /= null then T.Assert (Mysql_Driver.Get_Driver_Index > 0, "The driver index must be positive"); end if; if Sqlite_Driver /= null then T.Assert (Sqlite_Driver.Get_Driver_Index > 0, "The driver index must be positive"); end if; if Mysql_Driver /= null and Sqlite_Driver /= null then T.Assert (Mysql_Driver.Get_Driver_Index /= Sqlite_Driver.Get_Driver_Index, "Two drivers must have different driver indexes"); end if; end Test_Get_Driver_Index; -- ------------------------------ -- Test the Set_Connection procedure. -- ------------------------------ procedure Test_Set_Connection (T : in out Test) is procedure Check (URI : in String; Server : in String; Port : in Integer; Database : in String); procedure Check (URI : in String; Server : in String; Port : in Integer; Database : in String) is Controller : ADO.Drivers.Connections.Configuration; begin Controller.Set_Connection (URI); Util.Tests.Assert_Equals (T, Server, Controller.Get_Server, "Invalid server for " & URI); Util.Tests.Assert_Equals (T, Port, Controller.Get_Port, "Invalid port for " & URI); Util.Tests.Assert_Equals (T, Database, Controller.Get_Database, "Invalid db for " & URI); Controller.Set_Property ("password", "test"); Util.Tests.Assert_Equals (T, "test", Controller.Get_Property ("password"), "Invalid 'password' property for " & URI); exception when E : Connection_Error => Util.Tests.Assert_Matches (T, "Driver.*not found.*", Ada.Exceptions.Exception_Message (E), "Invalid exception raised for " & URI); end Check; begin Check ("mysql://test:3306/db", "test", 3306, "db"); Check ("mysql://test2:3307/db2?user=admin&password=admin", "test2", 3307, "db2"); Check ("sqlite:///test.db", "", 0, "test.db"); Check ("sqlite:///test2.db?user=root&encoding=UTF-8", "", 0, "test2.db"); end Test_Set_Connection; -- ------------------------------ -- Test the Set_Connection procedure with several error cases. -- ------------------------------ procedure Test_Set_Connection_Error (T : in out Test) is procedure Check_Invalid_Connection (URI : in String); Controller : ADO.Drivers.Connections.Configuration; procedure Check_Invalid_Connection (URI : in String) is begin Controller.Set_Connection (URI); T.Fail ("No Connection_Error exception raised for " & URI); exception when Connection_Error => null; end Check_Invalid_Connection; begin Check_Invalid_Connection (""); Check_Invalid_Connection ("http://"); Check_Invalid_Connection ("mysql://"); Check_Invalid_Connection ("sqlite://"); Check_Invalid_Connection ("mysql://:toto/"); Check_Invalid_Connection ("sqlite://:toto/"); end Test_Set_Connection_Error; -- ------------------------------ -- Test the Set_Server operation. -- ------------------------------ procedure Test_Set_Connection_Server (T : in out Test) is Controller : ADO.Drivers.Connections.Configuration; begin Controller.Set_Connection ("mysql://localhost:3306/db"); Controller.Set_Server ("server-name"); Util.Tests.Assert_Equals (T, "server-name", Controller.Get_Server, "Configuration Set_Server returned invalid value"); end Test_Set_Connection_Server; -- ------------------------------ -- Test the Set_Port operation. -- ------------------------------ procedure Test_Set_Connection_Port (T : in out Test) is Controller : ADO.Drivers.Connections.Configuration; begin Controller.Set_Connection ("mysql://localhost:3306/db"); Controller.Set_Port (1234); Util.Tests.Assert_Equals (T, 1234, Controller.Get_Port, "Configuration Set_Port returned invalid value"); end Test_Set_Connection_Port; -- ------------------------------ -- Test the Set_Database operation. -- ------------------------------ procedure Test_Set_Connection_Database (T : in out Test) is Controller : ADO.Drivers.Connections.Configuration; begin Controller.Set_Connection ("mysql://localhost:3306/db"); Controller.Set_Database ("test-database"); Util.Tests.Assert_Equals (T, "test-database", Controller.Get_Database, "Configuration Set_Database returned invalid value"); end Test_Set_Connection_Database; -- ------------------------------ -- Test the connection operations on an empty connection. -- ------------------------------ procedure Test_Empty_Connection (T : in out Test) is use type ADO.Sessions.Connection_Status; C : ADO.Sessions.Session; Stmt : ADO.Statements.Query_Statement; pragma Unreferenced (Stmt); begin T.Assert (C.Get_Status = ADO.Sessions.CLOSED, "The database connection must be closed for an empty connection"); -- Util.Tests.Assert_Equals (T, "null", ADO.Databases.Get_Ident (C), -- "Get_Ident must return null"); -- Create_Statement must raise NOT_OPEN. begin Stmt := C.Create_Statement (""); T.Fail ("No exception raised for Create_Statement"); exception when ADO.Sessions.NOT_OPEN => null; end; -- Create_Statement must raise NOT_OPEN. begin Stmt := C.Create_Statement ("select"); T.Fail ("No exception raised for Create_Statement"); exception when ADO.Sessions.NOT_OPEN => null; end; -- Get_Driver must raise NOT_OPEN. -- begin -- T.Assert (ADO.Databases.Get_Driver (C) /= null, "Get_Driver must raise an exception"); -- exception -- when ADO.Sessions.NOT_OPEN => -- null; -- end; end Test_Empty_Connection; end ADO.Drivers.Tests;
----------------------------------------------------------------------- -- ado-drivers-tests -- Unit tests for database drivers -- Copyright (C) 2014, 2015, 2016, 2018 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Exceptions; with Util.Test_Caller; with ADO.Statements; with ADO.Sessions; with ADO.Drivers.Connections; package body ADO.Drivers.Tests is use ADO.Drivers.Connections; package Caller is new Util.Test_Caller (Test, "ADO.Drivers"); procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is begin Caller.Add_Test (Suite, "Test ADO.Drivers.Initialize", Test_Initialize'Access); Caller.Add_Test (Suite, "Test ADO.Drivers.Get_Config", Test_Get_Config'Access); Caller.Add_Test (Suite, "Test ADO.Drivers.Get_Driver", Test_Get_Driver'Access); Caller.Add_Test (Suite, "Test ADO.Drivers.Get_Driver_Index", Test_Get_Driver_Index'Access); Caller.Add_Test (Suite, "Test ADO.Drivers.Get_Driver", Test_Load_Invalid_Driver'Access); Caller.Add_Test (Suite, "Test ADO.Drivers.Connections.Set_Connection", Test_Set_Connection'Access); Caller.Add_Test (Suite, "Test ADO.Drivers.Connections.Set_Connection (Errors)", Test_Set_Connection_Error'Access); Caller.Add_Test (Suite, "Test ADO.Drivers.Connections.Set_Server", Test_Set_Connection_Server'Access); Caller.Add_Test (Suite, "Test ADO.Drivers.Connections.Set_Port", Test_Set_Connection_Port'Access); Caller.Add_Test (Suite, "Test ADO.Drivers.Connections.Set_Database", Test_Set_Connection_Database'Access); Caller.Add_Test (Suite, "Test ADO.Databases (Errors)", Test_Empty_Connection'Access); end Add_Tests; -- ------------------------------ -- Test the Initialize operation. -- ------------------------------ procedure Test_Initialize (T : in out Test) is pragma Unreferenced (T); begin ADO.Drivers.Initialize ("test-missing-config.properties"); end Test_Initialize; -- ------------------------------ -- Test the Get_Config operation. -- ------------------------------ procedure Test_Get_Config (T : in out Test) is begin T.Assert (ADO.Drivers.Get_Config ("test.database")'Length > 0, "The Get_Config operation returned no value for the test database"); end Test_Get_Config; -- ------------------------------ -- Test the Get_Driver operation. -- ------------------------------ procedure Test_Get_Driver (T : in out Test) is Mysql_Driver : constant Driver_Access := Drivers.Connections.Get_Driver ("mysql"); Sqlite_Driver : constant Driver_Access := Drivers.Connections.Get_Driver ("sqlite"); Postgres_Driver : constant Driver_Access := Drivers.Connections.Get_Driver ("postgresql"); begin T.Assert (Mysql_Driver /= null or Sqlite_Driver /= null or Postgres_Driver /= null, "No database driver was found!"); end Test_Get_Driver; -- ------------------------------ -- Test loading some invalid database driver. -- ------------------------------ procedure Test_Load_Invalid_Driver (T : in out Test) is Invalid_Driver : constant Driver_Access := ADO.Drivers.Connections.Get_Driver ("invalid"); begin T.Assert (Invalid_Driver = null, "The Get_Driver operation must return null for invalid drivers"); end Test_Load_Invalid_Driver; -- ------------------------------ -- Test the Get_Driver_Index operation. -- ------------------------------ procedure Test_Get_Driver_Index (T : in out Test) is Mysql_Driver : constant Driver_Access := Drivers.Connections.Get_Driver ("mysql"); Sqlite_Driver : constant Driver_Access := Drivers.Connections.Get_Driver ("sqlite"); Postgres_Driver : constant Driver_Access := Drivers.Connections.Get_Driver ("postgresql"); begin if Mysql_Driver /= null then T.Assert (Mysql_Driver.Get_Driver_Index > 0, "The driver index must be positive"); end if; if Sqlite_Driver /= null then T.Assert (Sqlite_Driver.Get_Driver_Index > 0, "The driver index must be positive"); end if; if Postgres_Driver /= null then T.Assert (Postgres_Driver.Get_Driver_Index > 0, "The driver index must be positive"); end if; if Mysql_Driver /= null and Sqlite_Driver /= null then T.Assert (Mysql_Driver.Get_Driver_Index /= Sqlite_Driver.Get_Driver_Index, "Two drivers must have different driver indexes"); end if; if Mysql_Driver /= null and Postgres_Driver /= null then T.Assert (Mysql_Driver.Get_Driver_Index /= Postgres_Driver.Get_Driver_Index, "Two drivers must have different driver indexes"); end if; if Sqlite_Driver /= null and Postgres_Driver /= null then T.Assert (Sqlite_Driver.Get_Driver_Index /= Postgres_Driver.Get_Driver_Index, "Two drivers must have different driver indexes"); end if; end Test_Get_Driver_Index; -- ------------------------------ -- Test the Set_Connection procedure. -- ------------------------------ procedure Test_Set_Connection (T : in out Test) is procedure Check (URI : in String; Server : in String; Port : in Integer; Database : in String); procedure Check (URI : in String; Server : in String; Port : in Integer; Database : in String) is Controller : ADO.Drivers.Connections.Configuration; begin Controller.Set_Connection (URI); Util.Tests.Assert_Equals (T, Server, Controller.Get_Server, "Invalid server for " & URI); Util.Tests.Assert_Equals (T, Port, Controller.Get_Port, "Invalid port for " & URI); Util.Tests.Assert_Equals (T, Database, Controller.Get_Database, "Invalid db for " & URI); Controller.Set_Property ("password", "test"); Util.Tests.Assert_Equals (T, "test", Controller.Get_Property ("password"), "Invalid 'password' property for " & URI); exception when E : Connection_Error => Util.Tests.Assert_Matches (T, "Driver.*not found.*", Ada.Exceptions.Exception_Message (E), "Invalid exception raised for " & URI); end Check; begin Check ("mysql://test:3306/db", "test", 3306, "db"); Check ("mysql://test2:3307/db2?user=admin&password=admin", "test2", 3307, "db2"); Check ("sqlite:///test.db", "", 0, "test.db"); Check ("sqlite:///test2.db?user=root&encoding=UTF-8", "", 0, "test2.db"); end Test_Set_Connection; -- ------------------------------ -- Test the Set_Connection procedure with several error cases. -- ------------------------------ procedure Test_Set_Connection_Error (T : in out Test) is procedure Check_Invalid_Connection (URI : in String); Controller : ADO.Drivers.Connections.Configuration; procedure Check_Invalid_Connection (URI : in String) is begin Controller.Set_Connection (URI); T.Fail ("No Connection_Error exception raised for " & URI); exception when Connection_Error => null; end Check_Invalid_Connection; begin Check_Invalid_Connection (""); Check_Invalid_Connection ("http://"); Check_Invalid_Connection ("mysql://"); Check_Invalid_Connection ("sqlite://"); Check_Invalid_Connection ("mysql://:toto/"); Check_Invalid_Connection ("sqlite://:toto/"); end Test_Set_Connection_Error; -- ------------------------------ -- Test the Set_Server operation. -- ------------------------------ procedure Test_Set_Connection_Server (T : in out Test) is Controller : ADO.Drivers.Connections.Configuration; begin Controller.Set_Connection ("mysql://localhost:3306/db"); Controller.Set_Server ("server-name"); Util.Tests.Assert_Equals (T, "server-name", Controller.Get_Server, "Configuration Set_Server returned invalid value"); exception when E : ADO.Drivers.Connection_Error => Util.Tests.Assert_Equals (T, "Driver 'mysql' not found", Ada.Exceptions.Exception_Message (E), "Invalid exception message"); end Test_Set_Connection_Server; -- ------------------------------ -- Test the Set_Port operation. -- ------------------------------ procedure Test_Set_Connection_Port (T : in out Test) is Controller : ADO.Drivers.Connections.Configuration; begin Controller.Set_Connection ("mysql://localhost:3306/db"); Controller.Set_Port (1234); Util.Tests.Assert_Equals (T, 1234, Controller.Get_Port, "Configuration Set_Port returned invalid value"); exception when E : ADO.Drivers.Connection_Error => Util.Tests.Assert_Equals (T, "Driver 'mysql' not found", Ada.Exceptions.Exception_Message (E), "Invalid exception message"); end Test_Set_Connection_Port; -- ------------------------------ -- Test the Set_Database operation. -- ------------------------------ procedure Test_Set_Connection_Database (T : in out Test) is Controller : ADO.Drivers.Connections.Configuration; begin Controller.Set_Connection ("mysql://localhost:3306/db"); Controller.Set_Database ("test-database"); Util.Tests.Assert_Equals (T, "test-database", Controller.Get_Database, "Configuration Set_Database returned invalid value"); exception when E : ADO.Drivers.Connection_Error => Util.Tests.Assert_Equals (T, "Driver 'mysql' not found", Ada.Exceptions.Exception_Message (E), "Invalid exception message"); end Test_Set_Connection_Database; -- ------------------------------ -- Test the connection operations on an empty connection. -- ------------------------------ procedure Test_Empty_Connection (T : in out Test) is use type ADO.Sessions.Connection_Status; C : ADO.Sessions.Session; Stmt : ADO.Statements.Query_Statement; pragma Unreferenced (Stmt); begin T.Assert (C.Get_Status = ADO.Sessions.CLOSED, "The database connection must be closed for an empty connection"); -- Util.Tests.Assert_Equals (T, "null", ADO.Databases.Get_Ident (C), -- "Get_Ident must return null"); -- Create_Statement must raise NOT_OPEN. begin Stmt := C.Create_Statement (""); T.Fail ("No exception raised for Create_Statement"); exception when ADO.Sessions.NOT_OPEN => null; end; -- Create_Statement must raise NOT_OPEN. begin Stmt := C.Create_Statement ("select"); T.Fail ("No exception raised for Create_Statement"); exception when ADO.Sessions.NOT_OPEN => null; end; -- Get_Driver must raise NOT_OPEN. -- begin -- T.Assert (ADO.Databases.Get_Driver (C) /= null, "Get_Driver must raise an exception"); -- exception -- when ADO.Sessions.NOT_OPEN => -- null; -- end; end Test_Empty_Connection; end ADO.Drivers.Tests;
Fix the driver tests when a database driver is not compiled/supported
Fix the driver tests when a database driver is not compiled/supported
Ada
apache-2.0
stcarrez/ada-ado
be13f028d741e430648071a4dc0894d704610941
regtests/el-contexts-tests.adb
regtests/el-contexts-tests.adb
----------------------------------------------------------------------- -- el-contexts-tests - Tests the EL contexts -- 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.Test_Caller; with Util.Properties; with Util.Beans.Objects; with EL.Expressions; with EL.Contexts.Properties; with EL.Contexts.Default; package body EL.Contexts.Tests is use Util.Tests; package Caller is new Util.Test_Caller (Test); procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is begin Caller.Add_Test (Suite, "Test EL.Contexts.Properties.Get_Value", Test_Context_Properties'Access); end Add_Tests; -- ------------------------------ -- Test Add_Parameter -- ------------------------------ procedure Test_Context_Properties (T : in out Test) is function Eval (Item : in String) return String; Context : EL.Contexts.Default.Default_Context; Prop_Resolver : aliased EL.Contexts.Properties.Property_Resolver; Props : Util.Properties.Manager; function Eval (Item : in String) return String is Expr : constant Expressions.Expression := EL.Expressions.Create_Expression (Item, Context); Result : constant Util.Beans.Objects.Object := Expr.Get_Value (Context); begin return Util.Beans.Objects.To_String (Result); end Eval; begin Props.Set ("user", "joe"); Props.Set ("home", "/home/joe"); Prop_Resolver.Set_Properties (Props); Context.Set_Resolver (Prop_Resolver'Unchecked_Access); Assert_Equals (T, "joe", Eval ("#{user}"), "Invalid evaluation of #{user}"); Assert_Equals (T, "/home/joe", Eval ("#{home}"), "Invalid evaluation of #{home}"); end Test_Context_Properties; end EL.Contexts.Tests;
----------------------------------------------------------------------- -- el-contexts-tests - Tests the EL contexts -- 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.Test_Caller; with Util.Properties; with Util.Beans.Objects; with EL.Expressions; with EL.Contexts.Properties; with EL.Contexts.Default; package body EL.Contexts.Tests is use Util.Tests; package Caller is new Util.Test_Caller (Test, "EL.Contexts"); procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is begin Caller.Add_Test (Suite, "Test EL.Contexts.Properties.Get_Value", Test_Context_Properties'Access); end Add_Tests; -- ------------------------------ -- Test Add_Parameter -- ------------------------------ procedure Test_Context_Properties (T : in out Test) is function Eval (Item : in String) return String; Context : EL.Contexts.Default.Default_Context; Prop_Resolver : aliased EL.Contexts.Properties.Property_Resolver; Props : Util.Properties.Manager; function Eval (Item : in String) return String is Expr : constant Expressions.Expression := EL.Expressions.Create_Expression (Item, Context); Result : constant Util.Beans.Objects.Object := Expr.Get_Value (Context); begin return Util.Beans.Objects.To_String (Result); end Eval; begin Props.Set ("user", "joe"); Props.Set ("home", "/home/joe"); Prop_Resolver.Set_Properties (Props); Context.Set_Resolver (Prop_Resolver'Unchecked_Access); Assert_Equals (T, "joe", Eval ("#{user}"), "Invalid evaluation of #{user}"); Assert_Equals (T, "/home/joe", Eval ("#{home}"), "Invalid evaluation of #{home}"); end Test_Context_Properties; end EL.Contexts.Tests;
Use the test name EL.Contexts
Use the test name EL.Contexts
Ada
apache-2.0
Letractively/ada-el
60f053bc5dc17ca3930b6d60ece2773f18ce0f47
awa/regtests/awa-blogs-services-tests.adb
awa/regtests/awa-blogs-services-tests.adb
----------------------------------------------------------------------- -- awa-blogs-tests -- Unit tests for blogs module -- 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.Test_Caller; with ADO; with Security.Contexts; with AWA.Services.Contexts; with AWA.Blogs.Modules; with AWA.Tests.Helpers.Users; package body AWA.Blogs.Services.Tests is use Util.Tests; use ADO; package Caller is new Util.Test_Caller (Test, "Blogs.Services"); procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is begin Caller.Add_Test (Suite, "Test AWA.Blogs.Services.Create_Blog", Test_Create_Blog'Access); Caller.Add_Test (Suite, "Test AWA.Blogs.Services.Create_Post", Test_Create_Post'Access); end Add_Tests; -- ------------------------------ -- Test creation of a blog -- ------------------------------ procedure Test_Create_Blog (T : in out Test) is Manager : AWA.Blogs.Services.Blog_Service_Access; Blog_Id : ADO.Identifier; Sec_Ctx : Security.Contexts.Security_Context; Context : AWA.Services.Contexts.Service_Context; begin AWA.Tests.Helpers.Users.Login (Context, Sec_Ctx, "[email protected]"); Manager := AWA.Blogs.Modules.Get_Blog_Manager; Manager.Create_Blog (Workspace_Id => 0, Title => "My blog", Result => Blog_Id); T.Assert (Blog_Id > 0, "Invalid blog identifier"); end Test_Create_Blog; -- ------------------------------ -- Test creating and updating of a blog post -- ------------------------------ procedure Test_Create_Post (T : in out Test) is Manager : AWA.Blogs.Services.Blog_Service_Access; Blog_Id : ADO.Identifier; Post_Id : ADO.Identifier; Sec_Ctx : Security.Contexts.Security_Context; Context : AWA.Services.Contexts.Service_Context; begin AWA.Tests.Helpers.Users.Login (Context, Sec_Ctx, "[email protected]"); Manager := AWA.Blogs.Modules.Get_Blog_Manager; Manager.Create_Blog (Workspace_Id => 0, Title => "My blog post", Result => Blog_Id); T.Assert (Blog_Id > 0, "Invalid blog identifier"); for I in 1 .. 5 loop Manager.Create_Post (Blog_Id => Blog_Id, Title => "Testing blog title", URI => "testing-blog-title", Text => "The blog content", Result => Post_Id); T.Assert (Post_Id > 0, "Invalid post identifier"); Manager.Update_Post (Post_Id => Post_Id, Title => "New blog post title", Text => "The new post content"); -- Keep the last post in the database. exit when I = 5; Manager.Delete_Post (Post_Id => Post_Id); -- Verify that a Not_Found exception is raised if the post was deleted. begin Manager.Update_Post (Post_Id => Post_Id, Title => "Something", Text => "Content"); T.Assert (False, "Exception Not_Found was not raised"); exception when Not_Found => null; end; -- Verify that a Not_Found exception is raised if the post was deleted. begin Manager.Delete_Post (Post_Id => Post_Id); T.Assert (False, "Exception Not_Found was not raised"); exception when Not_Found => null; end; end loop; end Test_Create_Post; end AWA.Blogs.Services.Tests;
----------------------------------------------------------------------- -- awa-blogs-tests -- Unit tests for blogs module -- 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.Test_Caller; with ADO; with Security.Contexts; with AWA.Services.Contexts; with AWA.Blogs.Modules; with AWA.Tests.Helpers.Users; package body AWA.Blogs.Services.Tests is use Util.Tests; use ADO; package Caller is new Util.Test_Caller (Test, "Blogs.Services"); procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is begin Caller.Add_Test (Suite, "Test AWA.Blogs.Services.Create_Blog", Test_Create_Blog'Access); Caller.Add_Test (Suite, "Test AWA.Blogs.Services.Create_Post", Test_Create_Post'Access); end Add_Tests; -- ------------------------------ -- Test creation of a blog -- ------------------------------ procedure Test_Create_Blog (T : in out Test) is Manager : AWA.Blogs.Services.Blog_Service_Access; Blog_Id : ADO.Identifier; Sec_Ctx : Security.Contexts.Security_Context; Context : AWA.Services.Contexts.Service_Context; begin AWA.Tests.Helpers.Users.Login (Context, Sec_Ctx, "[email protected]"); Manager := AWA.Blogs.Modules.Get_Blog_Manager; Manager.Create_Blog (Workspace_Id => 0, Title => "My blog", Result => Blog_Id); T.Assert (Blog_Id > 0, "Invalid blog identifier"); end Test_Create_Blog; -- ------------------------------ -- Test creating and updating of a blog post -- ------------------------------ procedure Test_Create_Post (T : in out Test) is Manager : AWA.Blogs.Services.Blog_Service_Access; Blog_Id : ADO.Identifier; Post_Id : ADO.Identifier; Sec_Ctx : Security.Contexts.Security_Context; Context : AWA.Services.Contexts.Service_Context; begin AWA.Tests.Helpers.Users.Login (Context, Sec_Ctx, "[email protected]"); Manager := AWA.Blogs.Modules.Get_Blog_Manager; Manager.Create_Blog (Workspace_Id => 0, Title => "My blog post", Result => Blog_Id); T.Assert (Blog_Id > 0, "Invalid blog identifier"); for I in 1 .. 5 loop Manager.Create_Post (Blog_Id => Blog_Id, Title => "Testing blog title", URI => "testing-blog-title", Text => "The blog content", Status => AWA.Blogs.Models.POST_DRAFT, Result => Post_Id); T.Assert (Post_Id > 0, "Invalid post identifier"); Manager.Update_Post (Post_Id => Post_Id, Title => "New blog post title", Text => "The new post content", Status => AWA.Blogs.Models.POST_DRAFT); -- Keep the last post in the database. exit when I = 5; Manager.Delete_Post (Post_Id => Post_Id); -- Verify that a Not_Found exception is raised if the post was deleted. begin Manager.Update_Post (Post_Id => Post_Id, Title => "Something", Text => "Content", Status => AWA.Blogs.Models.POST_DRAFT); T.Assert (False, "Exception Not_Found was not raised"); exception when Not_Found => null; end; -- Verify that a Not_Found exception is raised if the post was deleted. begin Manager.Delete_Post (Post_Id => Post_Id); T.Assert (False, "Exception Not_Found was not raised"); exception when Not_Found => null; end; end loop; end Test_Create_Post; end AWA.Blogs.Services.Tests;
Fix compilation of unit tests
Fix compilation of unit tests
Ada
apache-2.0
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
f59440ed9525a21a841ff46605439044d6ebc7a7
src/security-policies-urls.ads
src/security-policies-urls.ads
----------------------------------------------------------------------- -- security-policies-urls -- URL security policy -- Copyright (C) 2010, 2011, 2012 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Containers.Hashed_Maps; with Ada.Containers.Vectors; with Util.Refs; with Util.Strings; with Util.Serialize.IO.XML; with GNAT.Regexp; package Security.Policies.Urls is NAME : constant String := "URL-Policy"; -- ------------------------------ -- URI Permission -- ------------------------------ -- Represents a permission to access a given URI. type URI_Permission (Id : Permissions.Permission_Index; Len : Natural) is new Permissions.Permission (Id) with record URI : String (1 .. Len); end record; -- ------------------------------ -- URL policy -- ------------------------------ type URL_Policy is new Policy with private; type URL_Policy_Access is access all URL_Policy'Class; Invalid_Name : exception; -- Get the policy name. overriding function Get_Name (From : in URL_Policy) return String; -- Returns True if the user has the permission to access the given URI permission. function Has_Permission (Manager : in URL_Policy; Context : in Security_Context_Access; Permission : in URI_Permission'Class) return Boolean; -- Grant the permission to access to the given <b>URI</b> to users having the <b>To</b> -- permissions. procedure Grant_URI_Permission (Manager : in out URL_Policy; URI : in String; To : in String); -- Initialize the permission manager. overriding procedure Initialize (Manager : in out URL_Policy); -- Finalize the permission manager. overriding procedure Finalize (Manager : in out URL_Policy); -- Setup the XML parser to read the <b>policy</b> description. overriding procedure Prepare_Config (Policy : in out URL_Policy; Reader : in out Util.Serialize.IO.XML.Parser); -- Finish reading the XML policy configuration. The security policy implementation can use -- this procedure to perform any configuration setup after the configuration is parsed. overriding procedure Finish_Config (Into : in out URL_Policy; Reader : in out Util.Serialize.IO.XML.Parser); private use Util.Strings; -- The <b>Access_Rule</b> represents a list of permissions to verify to grant -- access to the resource. To make it simple, the user must have one of the -- permission from the list. Each permission will refer to a specific permission -- controller. type Access_Rule (Count : Natural) is new Util.Refs.Ref_Entity with record Permissions : Permission_Index_Array (1 .. Count); end record; type Access_Rule_Access is access all Access_Rule; package Access_Rule_Refs is new Util.Refs.Indefinite_References (Element_Type => Access_Rule, Element_Access => Access_Rule_Access); subtype Access_Rule_Ref is Access_Rule_Refs.Ref; -- Find the access rule of the policy that matches the given URI. -- Returns the No_Rule value (disable access) if no rule is found. function Find_Access_Rule (Manager : in URL_Policy; URI : in String) return Access_Rule_Ref; -- The <b>Policy</b> defines the access rules that are applied on a given -- URL, set of URLs or files. type Policy is record Id : Natural; Pattern : GNAT.Regexp.Regexp; Rule : Access_Rule_Ref; end record; -- The <b>Policy_Vector</b> represents the whole permission policy. The order of -- policy in the list is important as policies can override each other. package Policy_Vector is new Ada.Containers.Vectors (Index_Type => Positive, Element_Type => Policy); package Rules_Maps is new Ada.Containers.Hashed_Maps (Key_Type => String_Ref, Element_Type => Access_Rule_Ref, Hash => Hash, Equivalent_Keys => Equivalent_Keys, "=" => Access_Rule_Refs."="); type Rules is new Util.Refs.Ref_Entity with record Map : Rules_Maps.Map; end record; type Rules_Access is access all Rules; package Rules_Ref is new Util.Refs.References (Rules, Rules_Access); type Rules_Ref_Access is access Rules_Ref.Atomic_Ref; type Controller_Access_Array_Access is access all Controller_Access_Array; type URL_Policy is new Security.Policies.Policy with record Cache : Rules_Ref_Access; Policies : Policy_Vector.Vector; end record; end Security.Policies.Urls;
----------------------------------------------------------------------- -- security-policies-urls -- URL security policy -- Copyright (C) 2010, 2011, 2012 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Containers.Hashed_Maps; with Ada.Containers.Vectors; with Util.Refs; with Util.Strings; with Util.Serialize.IO.XML; with GNAT.Regexp; -- == URL Security Policy == -- The <tt>Security.Policies.Urls</tt> implements a security policy intended to be used -- in web servers. -- -- === Policy creation === -- An instance of the <tt>URL_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.Urls.URL_Policy_Access; -- -- Create the URL policy and register it in the policy manager as follows: -- -- Policy := new URL_Policy; -- Manager.Add_Policy (Policy.all'Access); -- -- === Policy Configuration === -- Once the URL policy is registered, the policy manager can read and process the following -- XML configuration: -- -- <url-policy id='1'> -- <permission>create-workspace</permission> -- <permission>admin</permission> -- <url-pattern>/workspace/create</url-pattern> -- <url-pattern>/workspace/setup/*</url-pattern> -- </url-policy> -- -- This policy gives access to the URL that match one of the URL pattern if the -- security context has the permission <b>create-workspace</b> or <b>admin</b>. -- These two permissions are checked according to another security policy. -- The XML configuration can define several <tt>url-policy</tt>. They are checked in -- the order defined in the XML. In other words, the first <tt>url-policy</tt> that matches -- the URL is used to verify the permission. -- -- The <tt>url-policy</tt> definition can contain several <tt>permission</tt>. -- -- === Checking for permission === -- package Security.Policies.Urls is NAME : constant String := "URL-Policy"; -- ------------------------------ -- URI Permission -- ------------------------------ -- Represents a permission to access a given URI. type URI_Permission (Id : Permissions.Permission_Index; Len : Natural) is new Permissions.Permission (Id) with record URI : String (1 .. Len); end record; -- ------------------------------ -- URL policy -- ------------------------------ type URL_Policy is new Policy with private; type URL_Policy_Access is access all URL_Policy'Class; Invalid_Name : exception; -- Get the policy name. overriding function Get_Name (From : in URL_Policy) return String; -- Returns True if the user has the permission to access the given URI permission. function Has_Permission (Manager : in URL_Policy; Context : in Security_Context_Access; Permission : in URI_Permission'Class) return Boolean; -- Grant the permission to access to the given <b>URI</b> to users having the <b>To</b> -- permissions. procedure Grant_URI_Permission (Manager : in out URL_Policy; URI : in String; To : in String); -- Initialize the permission manager. overriding procedure Initialize (Manager : in out URL_Policy); -- Finalize the permission manager. overriding procedure Finalize (Manager : in out URL_Policy); -- Setup the XML parser to read the <b>policy</b> description. overriding procedure Prepare_Config (Policy : in out URL_Policy; Reader : in out Util.Serialize.IO.XML.Parser); -- Finish reading the XML policy configuration. The security policy implementation can use -- this procedure to perform any configuration setup after the configuration is parsed. overriding procedure Finish_Config (Into : in out URL_Policy; Reader : in out Util.Serialize.IO.XML.Parser); private use Util.Strings; -- The <b>Access_Rule</b> represents a list of permissions to verify to grant -- access to the resource. To make it simple, the user must have one of the -- permission from the list. Each permission will refer to a specific permission -- controller. type Access_Rule (Count : Natural) is new Util.Refs.Ref_Entity with record Permissions : Permission_Index_Array (1 .. Count); end record; type Access_Rule_Access is access all Access_Rule; package Access_Rule_Refs is new Util.Refs.Indefinite_References (Element_Type => Access_Rule, Element_Access => Access_Rule_Access); subtype Access_Rule_Ref is Access_Rule_Refs.Ref; -- Find the access rule of the policy that matches the given URI. -- Returns the No_Rule value (disable access) if no rule is found. function Find_Access_Rule (Manager : in URL_Policy; URI : in String) return Access_Rule_Ref; -- The <b>Policy</b> defines the access rules that are applied on a given -- URL, set of URLs or files. type Policy is record Id : Natural; Pattern : GNAT.Regexp.Regexp; Rule : Access_Rule_Ref; end record; -- The <b>Policy_Vector</b> represents the whole permission policy. The order of -- policy in the list is important as policies can override each other. package Policy_Vector is new Ada.Containers.Vectors (Index_Type => Positive, Element_Type => Policy); package Rules_Maps is new Ada.Containers.Hashed_Maps (Key_Type => String_Ref, Element_Type => Access_Rule_Ref, Hash => Hash, Equivalent_Keys => Equivalent_Keys, "=" => Access_Rule_Refs."="); type Rules is new Util.Refs.Ref_Entity with record Map : Rules_Maps.Map; end record; type Rules_Access is access all Rules; package Rules_Ref is new Util.Refs.References (Rules, Rules_Access); type Rules_Ref_Access is access Rules_Ref.Atomic_Ref; type Controller_Access_Array_Access is access all Controller_Access_Array; type URL_Policy is new Security.Policies.Policy with record Cache : Rules_Ref_Access; Policies : Policy_Vector.Vector; end record; end Security.Policies.Urls;
Document the URL policy
Document the URL policy
Ada
apache-2.0
stcarrez/ada-security
955ee4407f9d071729cf67278695300e06262722
regtests/util-streams-tests.ads
regtests/util-streams-tests.ads
----------------------------------------------------------------------- -- util-streams-tests -- Unit tests for encoding buffered streams -- Copyright (C) 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 Util.Tests; with Util.Encoders.AES; package Util.Streams.Tests is procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite); type Test is new Util.Tests.Test with null record; procedure Test_AES (T : in out Test; Item : in String; Count : in Positive; Mode : in Util.Encoders.AES.AES_Mode; Label : in String); procedure Test_Base64_Stream (T : in out Test); end Util.Streams.Tests;
----------------------------------------------------------------------- -- util-streams-tests -- Unit tests for encoding buffered streams -- Copyright (C) 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 Util.Tests; with Util.Encoders.AES; package Util.Streams.Tests is procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite); type Test is new Util.Tests.Test with null record; procedure Test_AES (T : in out Test; Item : in String; Count : in Positive; Mode : in Util.Encoders.AES.AES_Mode; Label : in String); procedure Test_Base64_Stream (T : in out Test); procedure Test_Copy_Stream (T : in out Test); end Util.Streams.Tests;
Declare the Test_Copy_Stream procedure to test the Util.Streams.Copy procedures
Declare the Test_Copy_Stream procedure to test the Util.Streams.Copy procedures
Ada
apache-2.0
stcarrez/ada-util,stcarrez/ada-util
76f094c3ca6b6aa22be0983a367d4a19fd9b6e81
src/security-policies-roles.adb
src/security-policies-roles.adb
----------------------------------------------------------------------- -- security-policies-roles -- Role based policies -- Copyright (C) 2010, 2011, 2012, 2017 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Log.Loggers; with Util.Serialize.Mappers.Record_Mapper; with Util.Strings.Tokenizers; with Security.Controllers; with Security.Controllers.Roles; package body Security.Policies.Roles is -- The logger Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("Security.Policies.Roles"); -- ------------------------------ -- Set the roles which are assigned to the user in the security context. -- The role policy will use these roles to verify a permission. -- ------------------------------ procedure Set_Role_Context (Context : in out Security.Contexts.Security_Context'Class; Roles : in Role_Map) is Policy : constant Security.Policies.Policy_Access := Context.Get_Policy (NAME); Data : Role_Policy_Context_Access; begin if Policy = null then Log.Error ("There is no security policy: " & NAME); end if; Data := new Role_Policy_Context; Data.Roles := Roles; Context.Set_Policy_Context (Policy, Data.all'Access); end Set_Role_Context; -- ------------------------------ -- Set the roles which are assigned to the user in the security context. -- The role policy will use these roles to verify a permission. -- ------------------------------ procedure Set_Role_Context (Context : in out Security.Contexts.Security_Context'Class; Roles : in String) is Policy : constant Security.Policies.Policy_Access := Context.Get_Policy (NAME); Data : Role_Policy_Context_Access; Map : Role_Map; begin if Policy = null then Log.Error ("There is no security policy: " & NAME); end if; Role_Policy'Class (Policy.all).Set_Roles (Roles, Map); Data := new Role_Policy_Context; Data.Roles := Map; Context.Set_Policy_Context (Policy, Data.all'Access); end Set_Role_Context; -- ------------------------------ -- Get the policy name. -- ------------------------------ overriding function Get_Name (From : in Role_Policy) return String is pragma Unreferenced (From); begin return NAME; end Get_Name; -- ------------------------------ -- Get the role name. -- ------------------------------ function Get_Role_Name (Manager : in Role_Policy; Role : in Role_Type) return String is use type Ada.Strings.Unbounded.String_Access; begin if Manager.Names (Role) = null then return ""; else return Manager.Names (Role).all; end if; end Get_Role_Name; -- ------------------------------ -- Get the roles that grant the given permission. -- ------------------------------ function Get_Grants (Manager : in Role_Policy; Permission : in Permissions.Permission_Index) return Role_Map is begin return Manager.Grants (Permission); end Get_Grants; -- ------------------------------ -- Find the role type associated with the role name identified by <b>Name</b>. -- Raises <b>Invalid_Name</b> if there is no role type. -- ------------------------------ function Find_Role (Manager : in Role_Policy; Name : in String) return Role_Type is use type Ada.Strings.Unbounded.String_Access; begin Log.Debug ("Searching role {0}", Name); for I in Role_Type'First .. Manager.Next_Role loop exit when Manager.Names (I) = null; if Name = Manager.Names (I).all then return I; end if; end loop; Log.Debug ("Role {0} not found", Name); raise Invalid_Name; end Find_Role; -- ------------------------------ -- Create a role -- ------------------------------ procedure Create_Role (Manager : in out Role_Policy; Name : in String; Role : out Role_Type) is begin Role := Manager.Next_Role; Log.Info ("Role {0} is {1}", Name, Role_Type'Image (Role)); if Manager.Next_Role = Role_Type'Last then Log.Error ("Too many roles allocated. Number of roles is {0}", Role_Type'Image (Role_Type'Last)); else Manager.Next_Role := Manager.Next_Role + 1; end if; Manager.Names (Role) := new String '(Name); end Create_Role; -- ------------------------------ -- Get or build a permission type for the given name. -- ------------------------------ procedure Add_Role_Type (Manager : in out Role_Policy; Name : in String; Result : out Role_Type) is begin Result := Manager.Find_Role (Name); exception when Invalid_Name => Manager.Create_Role (Name, Result); end Add_Role_Type; -- ------------------------------ -- Set the roles specified in the <tt>Roles</tt> parameter. Each role is represented by -- its name and multiple roles are separated by ','. -- Raises Invalid_Name if a role was not found. -- ------------------------------ procedure Set_Roles (Manager : in Role_Policy; Roles : in String; Into : out Role_Map) is procedure Process (Role : in String; Done : out Boolean); procedure Process (Role : in String; Done : out Boolean) is begin Into (Manager.Find_Role (Role)) := True; Done := False; end Process; begin Into := (others => False); Util.Strings.Tokenizers.Iterate_Tokens (Content => Roles, Pattern => ",", Process => Process'Access, Going => Ada.Strings.Forward); end Set_Roles; type Config_Fields is (FIELD_NAME, FIELD_ROLE, FIELD_ROLE_PERMISSION, FIELD_ROLE_NAME); procedure Set_Member (Into : in out Role_Policy'Class; Field : in Config_Fields; Value : in Util.Beans.Objects.Object); -- ------------------------------ -- Called while parsing the XML policy file when the <name>, <role> and <role-permission> -- XML entities are found. Create the new permission when the complete permission definition -- has been parsed and save the permission in the security manager. -- ------------------------------ procedure Set_Member (Into : in out Role_Policy'Class; Field : in Config_Fields; Value : in Util.Beans.Objects.Object) is use Security.Controllers.Roles; begin case Field is when FIELD_NAME => Into.Name := Value; when FIELD_ROLE => declare Role : constant String := Util.Beans.Objects.To_String (Value); begin Into.Roles (Into.Count + 1) := Into.Find_Role (Role); Into.Count := Into.Count + 1; exception when Invalid_Name => raise Util.Serialize.Mappers.Field_Error with "Invalid role: " & Role; end; when FIELD_ROLE_PERMISSION => if Into.Count = 0 then raise Util.Serialize.Mappers.Field_Error with "Missing at least one role"; end if; declare Name : constant String := Util.Beans.Objects.To_String (Into.Name); Perm : constant Role_Controller_Access := new Role_Controller '(Count => Into.Count, Roles => Into.Roles (1 .. Into.Count)); Index : Permission_Index; begin Security.Permissions.Add_Permission (Name, Index); for I in 1 .. Into.Count loop Into.Grants (Index) (Into.Roles (I)) := True; end loop; Into.Manager.Add_Permission (Name, Perm.all'Access); Into.Count := 0; end; when FIELD_ROLE_NAME => declare Name : constant String := Util.Beans.Objects.To_String (Value); Role : Role_Type; begin Into.Add_Role_Type (Name, Role); end; end case; end Set_Member; package Config_Mapper is new Util.Serialize.Mappers.Record_Mapper (Element_Type => Role_Policy'Class, Element_Type_Access => Role_Policy_Access, Fields => Config_Fields, Set_Member => Set_Member); Mapper : aliased Config_Mapper.Mapper; -- ------------------------------ -- Setup the XML parser to read the <b>role-permission</b> description. -- ------------------------------ procedure Prepare_Config (Policy : in out Role_Policy; Reader : in out Util.Serialize.IO.XML.Parser) is begin Reader.Add_Mapping ("policy-rules", Mapper'Access); Reader.Add_Mapping ("module", Mapper'Access); Config_Mapper.Set_Context (Reader, Policy'Unchecked_Access); end Prepare_Config; -- ------------------------------ -- Finalize the policy manager. -- ------------------------------ overriding procedure Finalize (Policy : in out Role_Policy) is use type Ada.Strings.Unbounded.String_Access; begin for I in Policy.Names'Range loop exit when Policy.Names (I) = null; Ada.Strings.Unbounded.Free (Policy.Names (I)); end loop; end Finalize; -- ------------------------------ -- Get the role policy associated with the given policy manager. -- Returns the role policy instance or null if it was not registered in the policy manager. -- ------------------------------ function Get_Role_Policy (Manager : in Security.Policies.Policy_Manager'Class) return Role_Policy_Access is Policy : constant Security.Policies.Policy_Access := Manager.Get_Policy (NAME); begin if Policy = null or else not (Policy.all in Role_Policy'Class) then return null; else return Role_Policy'Class (Policy.all)'Access; end if; end Get_Role_Policy; begin Mapper.Add_Mapping ("role-permission", FIELD_ROLE_PERMISSION); Mapper.Add_Mapping ("role-permission/name", FIELD_NAME); Mapper.Add_Mapping ("role-permission/role", FIELD_ROLE); Mapper.Add_Mapping ("security-role/role-name", FIELD_ROLE_NAME); end Security.Policies.Roles;
----------------------------------------------------------------------- -- security-policies-roles -- Role based policies -- Copyright (C) 2010, 2011, 2012, 2017 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Log.Loggers; with Util.Serialize.Mappers.Record_Mapper; with Util.Strings.Tokenizers; with Security.Controllers; with Security.Controllers.Roles; package body Security.Policies.Roles is -- The logger Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("Security.Policies.Roles"); -- ------------------------------ -- Set the roles which are assigned to the user in the security context. -- The role policy will use these roles to verify a permission. -- ------------------------------ procedure Set_Role_Context (Context : in out Security.Contexts.Security_Context'Class; Roles : in Role_Map) is Policy : constant Security.Policies.Policy_Access := Context.Get_Policy (NAME); Data : Role_Policy_Context_Access; begin if Policy = null then Log.Error ("There is no security policy: " & NAME); end if; Data := new Role_Policy_Context; Data.Roles := Roles; Context.Set_Policy_Context (Policy, Data.all'Access); end Set_Role_Context; -- ------------------------------ -- Set the roles which are assigned to the user in the security context. -- The role policy will use these roles to verify a permission. -- ------------------------------ procedure Set_Role_Context (Context : in out Security.Contexts.Security_Context'Class; Roles : in String) is Policy : constant Security.Policies.Policy_Access := Context.Get_Policy (NAME); Data : Role_Policy_Context_Access; Map : Role_Map; begin if Policy = null then Log.Error ("There is no security policy: " & NAME); end if; Role_Policy'Class (Policy.all).Set_Roles (Roles, Map); Data := new Role_Policy_Context; Data.Roles := Map; Context.Set_Policy_Context (Policy, Data.all'Access); end Set_Role_Context; -- ------------------------------ -- Get the policy name. -- ------------------------------ overriding function Get_Name (From : in Role_Policy) return String is pragma Unreferenced (From); begin return NAME; end Get_Name; -- ------------------------------ -- Get the role name. -- ------------------------------ function Get_Role_Name (Manager : in Role_Policy; Role : in Role_Type) return String is use type Ada.Strings.Unbounded.String_Access; begin if Manager.Names (Role) = null then return ""; else return Manager.Names (Role).all; end if; end Get_Role_Name; -- ------------------------------ -- Get the roles that grant the given permission. -- ------------------------------ function Get_Grants (Manager : in Role_Policy; Permission : in Permissions.Permission_Index) return Role_Map is begin return Manager.Grants (Permission); end Get_Grants; -- ------------------------------ -- 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 is Result : Role_Name_Array (1 .. Get_Count (Map)); Pos : Positive := 1; begin for Role in Map'Range loop if Map (Role) then Result (Pos) := Manager.Names (Role); Pos := Pos + 1; end if; end loop; return Result; end Get_Role_Names; -- ------------------------------ -- Find the role type associated with the role name identified by <b>Name</b>. -- Raises <b>Invalid_Name</b> if there is no role type. -- ------------------------------ function Find_Role (Manager : in Role_Policy; Name : in String) return Role_Type is use type Ada.Strings.Unbounded.String_Access; begin Log.Debug ("Searching role {0}", Name); for I in Role_Type'First .. Manager.Next_Role loop exit when Manager.Names (I) = null; if Name = Manager.Names (I).all then return I; end if; end loop; Log.Debug ("Role {0} not found", Name); raise Invalid_Name; end Find_Role; -- ------------------------------ -- Create a role -- ------------------------------ procedure Create_Role (Manager : in out Role_Policy; Name : in String; Role : out Role_Type) is begin Role := Manager.Next_Role; Log.Info ("Role {0} is {1}", Name, Role_Type'Image (Role)); if Manager.Next_Role = Role_Type'Last then Log.Error ("Too many roles allocated. Number of roles is {0}", Role_Type'Image (Role_Type'Last)); else Manager.Next_Role := Manager.Next_Role + 1; end if; Manager.Names (Role) := new String '(Name); end Create_Role; -- ------------------------------ -- Get or build a permission type for the given name. -- ------------------------------ procedure Add_Role_Type (Manager : in out Role_Policy; Name : in String; Result : out Role_Type) is begin Result := Manager.Find_Role (Name); exception when Invalid_Name => Manager.Create_Role (Name, Result); end Add_Role_Type; -- ------------------------------ -- Set the roles specified in the <tt>Roles</tt> parameter. Each role is represented by -- its name and multiple roles are separated by ','. -- Raises Invalid_Name if a role was not found. -- ------------------------------ procedure Set_Roles (Manager : in Role_Policy; Roles : in String; Into : out Role_Map) is procedure Process (Role : in String; Done : out Boolean); procedure Process (Role : in String; Done : out Boolean) is begin Into (Manager.Find_Role (Role)) := True; Done := False; end Process; begin Into := (others => False); Util.Strings.Tokenizers.Iterate_Tokens (Content => Roles, Pattern => ",", Process => Process'Access, Going => Ada.Strings.Forward); end Set_Roles; type Config_Fields is (FIELD_NAME, FIELD_ROLE, FIELD_ROLE_PERMISSION, FIELD_ROLE_NAME); procedure Set_Member (Into : in out Role_Policy'Class; Field : in Config_Fields; Value : in Util.Beans.Objects.Object); -- ------------------------------ -- Called while parsing the XML policy file when the <name>, <role> and <role-permission> -- XML entities are found. Create the new permission when the complete permission definition -- has been parsed and save the permission in the security manager. -- ------------------------------ procedure Set_Member (Into : in out Role_Policy'Class; Field : in Config_Fields; Value : in Util.Beans.Objects.Object) is use Security.Controllers.Roles; begin case Field is when FIELD_NAME => Into.Name := Value; when FIELD_ROLE => declare Role : constant String := Util.Beans.Objects.To_String (Value); begin Into.Roles (Into.Count + 1) := Into.Find_Role (Role); Into.Count := Into.Count + 1; exception when Invalid_Name => raise Util.Serialize.Mappers.Field_Error with "Invalid role: " & Role; end; when FIELD_ROLE_PERMISSION => if Into.Count = 0 then raise Util.Serialize.Mappers.Field_Error with "Missing at least one role"; end if; declare Name : constant String := Util.Beans.Objects.To_String (Into.Name); Perm : constant Role_Controller_Access := new Role_Controller '(Count => Into.Count, Roles => Into.Roles (1 .. Into.Count)); Index : Permission_Index; begin Security.Permissions.Add_Permission (Name, Index); for I in 1 .. Into.Count loop Into.Grants (Index) (Into.Roles (I)) := True; end loop; Into.Manager.Add_Permission (Name, Perm.all'Access); Into.Count := 0; end; when FIELD_ROLE_NAME => declare Name : constant String := Util.Beans.Objects.To_String (Value); Role : Role_Type; begin Into.Add_Role_Type (Name, Role); end; end case; end Set_Member; package Config_Mapper is new Util.Serialize.Mappers.Record_Mapper (Element_Type => Role_Policy'Class, Element_Type_Access => Role_Policy_Access, Fields => Config_Fields, Set_Member => Set_Member); Mapper : aliased Config_Mapper.Mapper; -- ------------------------------ -- Setup the XML parser to read the <b>role-permission</b> description. -- ------------------------------ procedure Prepare_Config (Policy : in out Role_Policy; Reader : in out Util.Serialize.IO.XML.Parser) is begin Reader.Add_Mapping ("policy-rules", Mapper'Access); Reader.Add_Mapping ("module", Mapper'Access); Config_Mapper.Set_Context (Reader, Policy'Unchecked_Access); end Prepare_Config; -- ------------------------------ -- Finalize the policy manager. -- ------------------------------ overriding procedure Finalize (Policy : in out Role_Policy) is use type Ada.Strings.Unbounded.String_Access; begin for I in Policy.Names'Range loop exit when Policy.Names (I) = null; Ada.Strings.Unbounded.Free (Policy.Names (I)); end loop; end Finalize; -- ------------------------------ -- Get the role policy associated with the given policy manager. -- Returns the role policy instance or null if it was not registered in the policy manager. -- ------------------------------ function Get_Role_Policy (Manager : in Security.Policies.Policy_Manager'Class) return Role_Policy_Access is Policy : constant Security.Policies.Policy_Access := Manager.Get_Policy (NAME); begin if Policy = null or else not (Policy.all in Role_Policy'Class) then return null; else return Role_Policy'Class (Policy.all)'Access; end if; end Get_Role_Policy; begin Mapper.Add_Mapping ("role-permission", FIELD_ROLE_PERMISSION); Mapper.Add_Mapping ("role-permission/name", FIELD_NAME); Mapper.Add_Mapping ("role-permission/role", FIELD_ROLE); Mapper.Add_Mapping ("security-role/role-name", FIELD_ROLE_NAME); end Security.Policies.Roles;
Implement the Get_Role_Names function
Implement the Get_Role_Names function
Ada
apache-2.0
stcarrez/ada-security
475e71730f3bfc77c93bccf4dd067da3629384a6
awa/regtests/awa-testsuite.adb
awa/regtests/awa-testsuite.adb
----------------------------------------------------------------------- -- Util testsuite - Util Testsuite -- Copyright (C) 2009, 2010, 2011, 2012, 2013, 2014, 2015, 2016, 2017, 2018 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with AWA.Users.Services.Tests; with AWA.Users.Tests; with AWA.Blogs.Modules.Tests; with AWA.Blogs.Tests; with AWA.Helpers.Selectors.Tests; with AWA.Storages.Services.Tests; with AWA.Events.Services.Tests; with AWA.Mail.Clients.Tests; with AWA.Mail.Modules.Tests; with AWA.Images.Modules.Tests; with AWA.Votes.Modules.Tests; with AWA.Tags.Modules.Tests; with AWA.Questions.Modules.Tests; with AWA.Questions.Tests; with AWA.Counters.Modules.Tests; with AWA.Workspaces.Tests; with AWA.Modules.Tests; with ASF.Converters.Dates; with AWA.Users.Modules; with AWA.Mail.Modules; with AWA.Blogs.Modules; with AWA.Workspaces.Modules; with AWA.Storages.Modules; with AWA.Images.Modules; with AWA.Questions.Modules; with AWA.Votes.Modules; with AWA.Tags.Modules; with AWA.Changelogs.Modules; with AWA.Counters.Modules; with AWA.Converters.Dates; with AWA.Tests; with AWA.Services.Contexts; with AWA.Jobs.Services.Tests; with AWA.Jobs.Modules.Tests; with AWA.Settings.Modules.Tests; with AWA.Comments.Modules.Tests; with AWA.Changelogs.Modules.Tests; with AWA.Wikis.Modules.Tests; with AWA.Wikis.Tests; with ADO.Drivers; with Servlet.Server; package body AWA.Testsuite is Users : aliased AWA.Users.Modules.User_Module; Workspaces : aliased AWA.Workspaces.Modules.Workspace_Module; Mail : aliased AWA.Mail.Modules.Mail_Module; Jobs : aliased AWA.Jobs.Modules.Job_Module; Comments : aliased AWA.Comments.Modules.Comment_Module; Blogs : aliased AWA.Blogs.Modules.Blog_Module; Storages : aliased AWA.Storages.Modules.Storage_Module; Images : aliased AWA.Images.Modules.Image_Module; Questions : aliased AWA.Questions.Modules.Question_Module; Votes : aliased AWA.Votes.Modules.Vote_Module; Tags : aliased AWA.Tags.Modules.Tag_Module; Settings : aliased AWA.Settings.Modules.Setting_Module; Changelogs : aliased AWA.Changelogs.Modules.Changelog_Module; Wikis : aliased AWA.Wikis.Modules.Wiki_Module; Counters : aliased AWA.Counters.Modules.Counter_Module; Date_Converter : aliased ASF.Converters.Dates.Date_Converter; Rel_Date_Converter : aliased AWA.Converters.Dates.Relative_Date_Converter; Tests : aliased Util.Tests.Test_Suite; function Suite return Util.Tests.Access_Test_Suite is Ret : constant Util.Tests.Access_Test_Suite := Tests'Access; begin AWA.Modules.Tests.Add_Tests (Ret); AWA.Events.Services.Tests.Add_Tests (Ret); AWA.Mail.Clients.Tests.Add_Tests (Ret); AWA.Mail.Modules.Tests.Add_Tests (Ret); AWA.Users.Services.Tests.Add_Tests (Ret); AWA.Users.Tests.Add_Tests (Ret); AWA.Workspaces.Tests.Add_Tests (Ret); AWA.Counters.Modules.Tests.Add_Tests (Ret); AWA.Helpers.Selectors.Tests.Add_Tests (Ret); AWA.Jobs.Modules.Tests.Add_Tests (Ret); AWA.Jobs.Services.Tests.Add_Tests (Ret); AWA.Settings.Modules.Tests.Add_Tests (Ret); AWA.Comments.Modules.Tests.Add_Tests (Ret); AWA.Blogs.Modules.Tests.Add_Tests (Ret); AWA.Blogs.Tests.Add_Tests (Ret); AWA.Storages.Services.Tests.Add_Tests (Ret); AWA.Images.Modules.Tests.Add_Tests (Ret); AWA.Changelogs.Modules.Tests.Add_Tests (Ret); AWA.Votes.Modules.Tests.Add_Tests (Ret); AWA.Tags.Modules.Tests.Add_Tests (Ret); AWA.Questions.Modules.Tests.Add_Tests (Ret); AWA.Questions.Tests.Add_Tests (Ret); AWA.Wikis.Modules.Tests.Add_Tests (Ret); AWA.Wikis.Tests.Add_Tests (Ret); return Ret; end Suite; procedure Initialize (Props : in Util.Properties.Manager) is begin Initialize (null, Props, True); end Initialize; -- ------------------------------ -- Initialize the AWA test framework mockup. -- ------------------------------ procedure Initialize (App : in AWA.Applications.Application_Access; Props : in Util.Properties.Manager; Add_Modules : in Boolean) is use AWA.Applications; begin ADO.Drivers.Initialize; AWA.Tests.Initialize (App, Props, Add_Modules); if Add_Modules then declare Application : constant Applications.Application_Access := AWA.Tests.Get_Application; Ctx : AWA.Services.Contexts.Service_Context; Users : constant AWA.Users.Modules.User_Module_Access := AWA.Testsuite.Users'Access; begin Ctx.Set_Context (Application, null); Register (App => Application.all'Access, Name => AWA.Users.Modules.NAME, URI => "user", Module => Users.all'Access); Register (App => Application.all'Access, Name => "mail", URI => "mail", Module => Mail'Access); Register (App => Application.all'Access, Name => "workspaces", URI => "workspaces", Module => Workspaces'Access); Register (App => Application.all'Access, Name => AWA.Counters.Modules.NAME, URI => "counters", Module => Counters'Access); Register (App => Application.all'Access, Name => AWA.Comments.Modules.NAME, URI => "comments", Module => Comments'Access); Register (App => Application.all'Access, Name => AWA.Storages.Modules.NAME, URI => "storages", Module => Storages'Access); Register (App => Application.all'Access, Name => AWA.Jobs.Modules.NAME, URI => "jobs", Module => Jobs'Access); Register (App => Application.all'Access, Name => AWA.Images.Modules.NAME, URI => "images", Module => Images'Access); Register (App => Application.all'Access, Name => AWA.Settings.Modules.NAME, URI => "settings", Module => Settings'Access); Register (App => Application.all'Access, Name => AWA.Votes.Modules.NAME, URI => "votes", Module => Votes'Access); Register (App => Application.all'Access, Name => AWA.Changelogs.Modules.NAME, URI => "changelogs", Module => Changelogs'Access); Register (App => Application.all'Access, Name => AWA.Tags.Modules.NAME, URI => "tags", Module => Tags'Access); Register (App => Application.all'Access, Name => AWA.Blogs.Modules.NAME, URI => "blogs", Module => Blogs'Access); Register (App => Application.all'Access, Name => AWA.Questions.Modules.NAME, URI => "questions", Module => Questions'Access); Register (App => Application.all'Access, Name => AWA.Wikis.Modules.NAME, URI => "wikis", Module => Wikis'Access); Application.Add_Converter (Name => "dateConverter", Converter => Date_Converter'Access); Application.Add_Converter (Name => "smartDateConverter", Converter => Rel_Date_Converter'Access); Application.Start; -- if Props.Exists ("test.server") then -- declare -- WS : ASF.Server.Web.AWS_Container; -- begin -- Application.Add_Converter (Name => "dateConverter", -- Converter => Date_Converter'Access); -- Application.Add_Converter (Name => "smartDateConverter", -- Converter => Rel_Date_Converter'Access); -- -- WS.Register_Application ("/asfunit", Application.all'Access); -- -- WS.Start; -- delay 6000.0; -- end; -- end if; Servlet.Server.Set_Context (Application.all'Access); end; end if; end Initialize; end AWA.Testsuite;
----------------------------------------------------------------------- -- Util testsuite - Util Testsuite -- Copyright (C) 2009, 2010, 2011, 2012, 2013, 2014, 2015, 2016, 2017, 2018 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with AWA.Users.Services.Tests; with AWA.Users.Tests; with AWA.Blogs.Modules.Tests; with AWA.Blogs.Tests; with AWA.Helpers.Selectors.Tests; with AWA.Storages.Services.Tests; with AWA.Events.Services.Tests; with AWA.Mail.Clients.Tests; with AWA.Mail.Modules.Tests; with AWA.Images.Modules.Tests; with AWA.Votes.Modules.Tests; with AWA.Tags.Modules.Tests; with AWA.Questions.Modules.Tests; with AWA.Questions.Tests; with AWA.Counters.Modules.Tests; with AWA.Workspaces.Tests; with AWA.Modules.Tests; with ASF.Converters.Dates; with AWA.Users.Modules; with AWA.Mail.Modules; with AWA.Blogs.Modules; with AWA.Workspaces.Modules; with AWA.Storages.Modules; with AWA.Images.Modules; with AWA.Questions.Modules; with AWA.Votes.Modules; with AWA.Tags.Modules; with AWA.Changelogs.Modules; with AWA.Counters.Modules; with AWA.Converters.Dates; with AWA.Tests; with AWA.Services.Contexts; with AWA.Jobs.Services.Tests; with AWA.Jobs.Modules.Tests; with AWA.Settings.Modules.Tests; with AWA.Comments.Modules.Tests; with AWA.Changelogs.Modules.Tests; with AWA.Wikis.Modules.Tests; with AWA.Wikis.Tests; with AWA.Commands.Tests; with ADO.Drivers; with Servlet.Server; package body AWA.Testsuite is Users : aliased AWA.Users.Modules.User_Module; Workspaces : aliased AWA.Workspaces.Modules.Workspace_Module; Mail : aliased AWA.Mail.Modules.Mail_Module; Jobs : aliased AWA.Jobs.Modules.Job_Module; Comments : aliased AWA.Comments.Modules.Comment_Module; Blogs : aliased AWA.Blogs.Modules.Blog_Module; Storages : aliased AWA.Storages.Modules.Storage_Module; Images : aliased AWA.Images.Modules.Image_Module; Questions : aliased AWA.Questions.Modules.Question_Module; Votes : aliased AWA.Votes.Modules.Vote_Module; Tags : aliased AWA.Tags.Modules.Tag_Module; Settings : aliased AWA.Settings.Modules.Setting_Module; Changelogs : aliased AWA.Changelogs.Modules.Changelog_Module; Wikis : aliased AWA.Wikis.Modules.Wiki_Module; Counters : aliased AWA.Counters.Modules.Counter_Module; Date_Converter : aliased ASF.Converters.Dates.Date_Converter; Rel_Date_Converter : aliased AWA.Converters.Dates.Relative_Date_Converter; Tests : aliased Util.Tests.Test_Suite; function Suite return Util.Tests.Access_Test_Suite is Ret : constant Util.Tests.Access_Test_Suite := Tests'Access; begin AWA.Modules.Tests.Add_Tests (Ret); AWA.Events.Services.Tests.Add_Tests (Ret); AWA.Mail.Clients.Tests.Add_Tests (Ret); AWA.Mail.Modules.Tests.Add_Tests (Ret); AWA.Users.Services.Tests.Add_Tests (Ret); AWA.Users.Tests.Add_Tests (Ret); AWA.Workspaces.Tests.Add_Tests (Ret); AWA.Counters.Modules.Tests.Add_Tests (Ret); AWA.Helpers.Selectors.Tests.Add_Tests (Ret); AWA.Jobs.Modules.Tests.Add_Tests (Ret); AWA.Jobs.Services.Tests.Add_Tests (Ret); AWA.Settings.Modules.Tests.Add_Tests (Ret); AWA.Comments.Modules.Tests.Add_Tests (Ret); AWA.Blogs.Modules.Tests.Add_Tests (Ret); AWA.Blogs.Tests.Add_Tests (Ret); AWA.Storages.Services.Tests.Add_Tests (Ret); AWA.Images.Modules.Tests.Add_Tests (Ret); AWA.Changelogs.Modules.Tests.Add_Tests (Ret); AWA.Votes.Modules.Tests.Add_Tests (Ret); AWA.Tags.Modules.Tests.Add_Tests (Ret); AWA.Questions.Modules.Tests.Add_Tests (Ret); AWA.Questions.Tests.Add_Tests (Ret); AWA.Wikis.Modules.Tests.Add_Tests (Ret); AWA.Wikis.Tests.Add_Tests (Ret); AWA.Commands.Tests.Add_Tests (Ret); return Ret; end Suite; procedure Initialize (Props : in Util.Properties.Manager) is begin Initialize (null, Props, True); end Initialize; -- ------------------------------ -- Initialize the AWA test framework mockup. -- ------------------------------ procedure Initialize (App : in AWA.Applications.Application_Access; Props : in Util.Properties.Manager; Add_Modules : in Boolean) is use AWA.Applications; begin ADO.Drivers.Initialize; AWA.Tests.Initialize (App, Props, Add_Modules); if Add_Modules then declare Application : constant Applications.Application_Access := AWA.Tests.Get_Application; Ctx : AWA.Services.Contexts.Service_Context; Users : constant AWA.Users.Modules.User_Module_Access := AWA.Testsuite.Users'Access; begin Ctx.Set_Context (Application, null); Register (App => Application.all'Access, Name => AWA.Users.Modules.NAME, URI => "user", Module => Users.all'Access); Register (App => Application.all'Access, Name => "mail", URI => "mail", Module => Mail'Access); Register (App => Application.all'Access, Name => "workspaces", URI => "workspaces", Module => Workspaces'Access); Register (App => Application.all'Access, Name => AWA.Counters.Modules.NAME, URI => "counters", Module => Counters'Access); Register (App => Application.all'Access, Name => AWA.Comments.Modules.NAME, URI => "comments", Module => Comments'Access); Register (App => Application.all'Access, Name => AWA.Storages.Modules.NAME, URI => "storages", Module => Storages'Access); Register (App => Application.all'Access, Name => AWA.Jobs.Modules.NAME, URI => "jobs", Module => Jobs'Access); Register (App => Application.all'Access, Name => AWA.Images.Modules.NAME, URI => "images", Module => Images'Access); Register (App => Application.all'Access, Name => AWA.Settings.Modules.NAME, URI => "settings", Module => Settings'Access); Register (App => Application.all'Access, Name => AWA.Votes.Modules.NAME, URI => "votes", Module => Votes'Access); Register (App => Application.all'Access, Name => AWA.Changelogs.Modules.NAME, URI => "changelogs", Module => Changelogs'Access); Register (App => Application.all'Access, Name => AWA.Tags.Modules.NAME, URI => "tags", Module => Tags'Access); Register (App => Application.all'Access, Name => AWA.Blogs.Modules.NAME, URI => "blogs", Module => Blogs'Access); Register (App => Application.all'Access, Name => AWA.Questions.Modules.NAME, URI => "questions", Module => Questions'Access); Register (App => Application.all'Access, Name => AWA.Wikis.Modules.NAME, URI => "wikis", Module => Wikis'Access); Application.Add_Converter (Name => "dateConverter", Converter => Date_Converter'Access); Application.Add_Converter (Name => "smartDateConverter", Converter => Rel_Date_Converter'Access); Application.Start; -- if Props.Exists ("test.server") then -- declare -- WS : ASF.Server.Web.AWS_Container; -- begin -- Application.Add_Converter (Name => "dateConverter", -- Converter => Date_Converter'Access); -- Application.Add_Converter (Name => "smartDateConverter", -- Converter => Rel_Date_Converter'Access); -- -- WS.Register_Application ("/asfunit", Application.all'Access); -- -- WS.Start; -- delay 6000.0; -- end; -- end if; Servlet.Server.Set_Context (Application.all'Access); end; end if; end Initialize; end AWA.Testsuite;
Add the AWA.Commands.Tests in the testsuite for execution
Add the AWA.Commands.Tests in the testsuite for execution
Ada
apache-2.0
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
eb0f59b4078eabe3aa7053584848cc0c5d4b95f6
src/asf-sessions.adb
src/asf-sessions.adb
----------------------------------------------------------------------- -- asf.sessions -- ASF Sessions -- Copyright (C) 2010, 2011 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Unchecked_Deallocation; -- The <b>ASF.Sessions</b> package is an Ada implementation of the -- Java servlet Specification (See JSR 315 at jcp.org). package body ASF.Sessions is use Ada.Strings.Unbounded; -- ------------------------------ -- Returns true if the session is valid. -- ------------------------------ function Is_Valid (Sess : in Session'Class) return Boolean is begin return Sess.Impl /= null and then Sess.Impl.Is_Active; end Is_Valid; -- ------------------------------ -- Returns a string containing the unique identifier assigned to this session. -- The identifier is assigned by the servlet container and is implementation dependent. -- ------------------------------ function Get_Id (Sess : in Session) return String is begin if Sess.Impl = null or else not Sess.Impl.Is_Active then raise No_Session; else return Sess.Impl.Id.all; end if; end Get_Id; -- ------------------------------ -- Returns the last time the client sent a request associated with this session, -- as the number of milliseconds since midnight January 1, 1970 GMT, and marked -- by the time the container recieved the request. -- -- Actions that your application takes, such as getting or setting a value associated -- with the session, do not affect the access time. -- ------------------------------ function Get_Last_Accessed_Time (Sess : in Session) return Ada.Calendar.Time is begin if Sess.Impl = null or else not Sess.Impl.Is_Active then raise No_Session; else return Sess.Impl.Access_Time; end if; end Get_Last_Accessed_Time; -- ------------------------------ -- Returns the maximum time interval, in seconds, that the servlet container will -- keep this session open between client accesses. After this interval, the servlet -- container will invalidate the session. The maximum time interval can be set with -- the Set_Max_Inactive_Interval method. -- A negative time indicates the session should never timeout. -- ------------------------------ function Get_Max_Inactive_Interval (Sess : in Session) return Duration is begin if Sess.Impl = null or else not Sess.Impl.Is_Active then raise No_Session; else return Sess.Impl.Max_Inactive; end if; end Get_Max_Inactive_Interval; -- ------------------------------ -- Specifies the time, in seconds, between client requests before the servlet -- container will invalidate this session. A negative time indicates the session -- should never timeout. -- ------------------------------ procedure Set_Max_Inactive_Interval (Sess : in Session; Interval : in Duration) is begin if Sess.Impl = null or else not Sess.Impl.Is_Active then raise No_Session; else Sess.Impl.Max_Inactive := Interval; end if; end Set_Max_Inactive_Interval; -- ------------------------------ -- Returns the object bound with the specified name in this session, -- or null if no object is bound under the name. -- ------------------------------ function Get_Attribute (Sess : in Session; Name : in String) return EL.Objects.Object is Key : constant Unbounded_String := To_Unbounded_String (Name); begin if Sess.Impl = null or else not Sess.Impl.Is_Active then raise No_Session; end if; Sess.Impl.Lock.Read; declare Pos : constant EL.Objects.Maps.Cursor := Sess.Impl.Attributes.Find (Key); begin if EL.Objects.Maps.Has_Element (Pos) then return Value : constant EL.Objects.Object := EL.Objects.Maps.Element (Pos) do Sess.Impl.Lock.Release_Read; end return; end if; exception when others => Sess.Impl.Lock.Release_Read; raise; end; Sess.Impl.Lock.Release_Read; return EL.Objects.Null_Object; end Get_Attribute; -- ------------------------------ -- Binds an object to this session, using the name specified. -- If an object of the same name is already bound to the session, -- the object is replaced. -- -- If the value passed in is null, this has the same effect as calling -- removeAttribute(). -- ------------------------------ procedure Set_Attribute (Sess : in out Session; Name : in String; Value : in EL.Objects.Object) is begin if Sess.Impl = null or else not Sess.Impl.Is_Active then raise No_Session; end if; declare Key : constant Unbounded_String := To_Unbounded_String (Name); begin Sess.Impl.Lock.Write; if EL.Objects.Is_Null (Value) then Sess.Impl.Attributes.Delete (Key); else Sess.Impl.Attributes.Include (Key, Value); end if; exception when others => Sess.Impl.Lock.Release_Write; raise; end; Sess.Impl.Lock.Release_Write; end Set_Attribute; -- ------------------------------ -- Removes the object bound with the specified name from this session. -- If the session does not have an object bound with the specified name, -- this method does nothing. -- ------------------------------ procedure Remove_Attribute (Sess : in out Session; Name : in String) is begin Set_Attribute (Sess, Name, EL.Objects.Null_Object); end Remove_Attribute; -- ------------------------------ -- Gets the principal that authenticated to the session. -- Returns null if there is no principal authenticated. -- ------------------------------ function Get_Principal (Sess : in Session) return ASF.Principals.Principal_Access is begin if Sess.Impl = null or else not Sess.Impl.Is_Active then raise No_Session; end if; return Sess.Impl.Principal; end Get_Principal; -- ------------------------------ -- Sets the principal associated with the session. -- ------------------------------ procedure Set_Principal (Sess : in out Session; Principal : in ASF.Principals.Principal_Access) is begin if Sess.Impl = null or else not Sess.Impl.Is_Active then raise No_Session; end if; Sess.Impl.Principal := Principal; end Set_Principal; -- ------------------------------ -- Invalidates this session then unbinds any objects bound to it. -- ------------------------------ procedure Invalidate (Sess : in out Session) is begin if Sess.Impl /= null then Sess.Impl.Is_Active := False; Finalize (Sess); end if; end Invalidate; -- ------------------------------ -- Adjust (increment) the session record reference counter. -- ------------------------------ overriding procedure Adjust (Object : in out Session) is begin if Object.Impl /= null then Util.Concurrent.Counters.Increment (Object.Impl.Ref_Counter); end if; end Adjust; procedure Free is new Ada.Unchecked_Deallocation (Object => Session_Record'Class, Name => Session_Record_Access); -- ------------------------------ -- Decrement the session record reference counter and free the session record -- if this was the last session reference. -- ------------------------------ overriding procedure Finalize (Object : in out Session) is Release : Boolean; begin if Object.Impl /= null then Util.Concurrent.Counters.Decrement (Object.Impl.Ref_Counter, Release); if Release then Free (Object.Impl); else Object.Impl := null; end if; end if; end Finalize; overriding procedure Finalize (Object : in out Session_Record) is begin Free (Object.Id); end Finalize; end ASF.Sessions;
----------------------------------------------------------------------- -- asf.sessions -- ASF Sessions -- Copyright (C) 2010, 2011 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Unchecked_Deallocation; -- The <b>ASF.Sessions</b> package is an Ada implementation of the -- Java servlet Specification (See JSR 315 at jcp.org). package body ASF.Sessions is use Ada.Strings.Unbounded; -- ------------------------------ -- Returns true if the session is valid. -- ------------------------------ function Is_Valid (Sess : in Session'Class) return Boolean is begin return Sess.Impl /= null and then Sess.Impl.Is_Active; end Is_Valid; -- ------------------------------ -- Returns a string containing the unique identifier assigned to this session. -- The identifier is assigned by the servlet container and is implementation dependent. -- ------------------------------ function Get_Id (Sess : in Session) return String is begin if Sess.Impl = null or else not Sess.Impl.Is_Active then raise No_Session; else return Sess.Impl.Id.all; end if; end Get_Id; -- ------------------------------ -- Returns the last time the client sent a request associated with this session, -- as the number of milliseconds since midnight January 1, 1970 GMT, and marked -- by the time the container recieved the request. -- -- Actions that your application takes, such as getting or setting a value associated -- with the session, do not affect the access time. -- ------------------------------ function Get_Last_Accessed_Time (Sess : in Session) return Ada.Calendar.Time is begin if Sess.Impl = null or else not Sess.Impl.Is_Active then raise No_Session; else return Sess.Impl.Access_Time; end if; end Get_Last_Accessed_Time; -- ------------------------------ -- Returns the maximum time interval, in seconds, that the servlet container will -- keep this session open between client accesses. After this interval, the servlet -- container will invalidate the session. The maximum time interval can be set with -- the Set_Max_Inactive_Interval method. -- A negative time indicates the session should never timeout. -- ------------------------------ function Get_Max_Inactive_Interval (Sess : in Session) return Duration is begin if Sess.Impl = null or else not Sess.Impl.Is_Active then raise No_Session; else return Sess.Impl.Max_Inactive; end if; end Get_Max_Inactive_Interval; -- ------------------------------ -- Specifies the time, in seconds, between client requests before the servlet -- container will invalidate this session. A negative time indicates the session -- should never timeout. -- ------------------------------ procedure Set_Max_Inactive_Interval (Sess : in Session; Interval : in Duration) is begin if Sess.Impl = null or else not Sess.Impl.Is_Active then raise No_Session; else Sess.Impl.Max_Inactive := Interval; end if; end Set_Max_Inactive_Interval; -- ------------------------------ -- Returns the object bound with the specified name in this session, -- or null if no object is bound under the name. -- ------------------------------ function Get_Attribute (Sess : in Session; Name : in String) return EL.Objects.Object is Key : constant Unbounded_String := To_Unbounded_String (Name); begin if Sess.Impl = null or else not Sess.Impl.Is_Active then raise No_Session; end if; Sess.Impl.Lock.Read; declare Pos : constant EL.Objects.Maps.Cursor := Sess.Impl.Attributes.Find (Key); begin if EL.Objects.Maps.Has_Element (Pos) then return Value : constant EL.Objects.Object := EL.Objects.Maps.Element (Pos) do Sess.Impl.Lock.Release_Read; end return; end if; exception when others => Sess.Impl.Lock.Release_Read; raise; end; Sess.Impl.Lock.Release_Read; return EL.Objects.Null_Object; end Get_Attribute; -- ------------------------------ -- Binds an object to this session, using the name specified. -- If an object of the same name is already bound to the session, -- the object is replaced. -- -- If the value passed in is null, this has the same effect as calling -- removeAttribute(). -- ------------------------------ procedure Set_Attribute (Sess : in out Session; Name : in String; Value : in EL.Objects.Object) is begin if Sess.Impl = null or else not Sess.Impl.Is_Active then raise No_Session; end if; declare Key : constant Unbounded_String := To_Unbounded_String (Name); begin Sess.Impl.Lock.Write; if EL.Objects.Is_Null (Value) then Sess.Impl.Attributes.Delete (Key); else Sess.Impl.Attributes.Include (Key, Value); end if; exception when others => Sess.Impl.Lock.Release_Write; raise; end; Sess.Impl.Lock.Release_Write; end Set_Attribute; -- ------------------------------ -- Removes the object bound with the specified name from this session. -- If the session does not have an object bound with the specified name, -- this method does nothing. -- ------------------------------ procedure Remove_Attribute (Sess : in out Session; Name : in String) is begin Set_Attribute (Sess, Name, EL.Objects.Null_Object); end Remove_Attribute; -- ------------------------------ -- Gets the principal that authenticated to the session. -- Returns null if there is no principal authenticated. -- ------------------------------ function Get_Principal (Sess : in Session) return ASF.Principals.Principal_Access is begin if Sess.Impl = null or else not Sess.Impl.Is_Active then raise No_Session; end if; return Sess.Impl.Principal; end Get_Principal; -- ------------------------------ -- Sets the principal associated with the session. -- ------------------------------ procedure Set_Principal (Sess : in out Session; Principal : in ASF.Principals.Principal_Access) is begin if Sess.Impl = null or else not Sess.Impl.Is_Active then raise No_Session; end if; Sess.Impl.Principal := Principal; end Set_Principal; -- ------------------------------ -- Invalidates this session then unbinds any objects bound to it. -- ------------------------------ procedure Invalidate (Sess : in out Session) is begin if Sess.Impl /= null then Sess.Impl.Is_Active := False; Finalize (Sess); end if; end Invalidate; -- ------------------------------ -- Adjust (increment) the session record reference counter. -- ------------------------------ overriding procedure Adjust (Object : in out Session) is begin if Object.Impl /= null then Util.Concurrent.Counters.Increment (Object.Impl.Ref_Counter); end if; end Adjust; procedure Free is new Ada.Unchecked_Deallocation (Object => Session_Record'Class, Name => Session_Record_Access); procedure Free is new Ada.Unchecked_Deallocation (Object => ASF.Principals.Principal'Class, Name => ASF.Principals.Principal_Access); -- ------------------------------ -- Decrement the session record reference counter and free the session record -- if this was the last session reference. -- ------------------------------ overriding procedure Finalize (Object : in out Session) is Release : Boolean; begin if Object.Impl /= null then Util.Concurrent.Counters.Decrement (Object.Impl.Ref_Counter, Release); if Release then Free (Object.Impl.Principal); Free (Object.Impl); else Object.Impl := null; end if; end if; end Finalize; overriding procedure Finalize (Object : in out Session_Record) is begin Free (Object.Id); end Finalize; end ASF.Sessions;
Delete the principal object when the session is deleted.
Delete the principal object when the session is deleted.
Ada
apache-2.0
Letractively/ada-asf,Letractively/ada-asf,Letractively/ada-asf
7e73dc65aa11d95afab6b0c40514c099a4c1a0c1
src/gen-model.adb
src/gen-model.adb
----------------------------------------------------------------------- -- gen-model -- Model for Code Generator -- Copyright (C) 2009, 2010, 2011, 2012, 2018 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Strings.Fixed; with Ada.Strings.Maps; with DOM.Core.Nodes; with Gen.Utils; package body Gen.Model is Trim_Chars : constant Ada.Strings.Maps.Character_Set := Ada.Strings.Maps.To_Set (" " & ASCII.HT & ASCII.LF & ASCII.CR); -- ------------------------------ -- Get the object unique name. -- ------------------------------ function Get_Name (From : in Definition) return String is begin return Ada.Strings.Unbounded.To_String (From.Def_Name); end Get_Name; function Name (From : in Definition) return Ada.Strings.Unbounded.Unbounded_String is begin return From.Def_Name; end Name; -- ------------------------------ -- Set the object unique name. -- ------------------------------ procedure Set_Name (Def : in out Definition; Name : in String) is begin Def.Def_Name := Ada.Strings.Unbounded.To_Unbounded_String (Name); end Set_Name; procedure Set_Name (Def : in out Definition; Name : in Ada.Strings.Unbounded.Unbounded_String) is begin Def.Def_Name := Name; end Set_Name; -- ------------------------------ -- 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 Definition; Name : in String) return Util.Beans.Objects.Object is begin if Name = "comment" then return From.Comment; elsif Name = "rowIndex" then return Util.Beans.Objects.To_Object (From.Row_Index); elsif Name = "name" then return Util.Beans.Objects.To_Object (From.Def_Name); else return From.Attrs.Get_Value (Name); end if; end Get_Value; -- ------------------------------ -- Get the value identified by the name. -- If the name cannot be found, the method should return the Null object. -- ------------------------------ function Get_Attribute (From : in Definition; Name : in String) return String is V : constant Util.Beans.Objects.Object := From.Get_Value (Name); begin return Util.Beans.Objects.To_String (V); end Get_Attribute; -- ------------------------------ -- Get the value identified by the name. -- If the name cannot be found, the method should return the Null object. -- ------------------------------ function Get_Attribute (From : in Definition; Name : in String) return Ada.Strings.Unbounded.Unbounded_String is begin return Ada.Strings.Unbounded.To_Unbounded_String (From.Get_Attribute (Name)); end Get_Attribute; -- ------------------------------ -- Set the comment associated with the element. -- ------------------------------ procedure Set_Comment (Def : in out Definition; Comment : in String) is Trimmed_Comment : constant String := Ada.Strings.Fixed.Trim (Comment, Trim_Chars, Trim_Chars); begin Def.Comment := Util.Beans.Objects.To_Object (Trimmed_Comment); end Set_Comment; -- ------------------------------ -- Get the comment associated with the element. -- ------------------------------ function Get_Comment (Def : in Definition) return Util.Beans.Objects.Object is begin return Def.Comment; end Get_Comment; -- ------------------------------ -- Set the location (file and line) where the model element is defined in the XMI file. -- ------------------------------ procedure Set_Location (Node : in out Definition; Location : in String) is begin Node.Location := Ada.Strings.Unbounded.To_Unbounded_String (Location); end Set_Location; -- ------------------------------ -- Get the location file and line where the model element is defined. -- ------------------------------ function Get_Location (Node : in Definition) return String is begin return Ada.Strings.Unbounded.To_String (Node.Location); end Get_Location; -- ------------------------------ -- Initialize the definition from the DOM node attributes. -- ------------------------------ procedure Initialize (Def : in out Definition; Name : in Ada.Strings.Unbounded.Unbounded_String; Node : in DOM.Core.Node) is use type DOM.Core.Node; Attrs : constant DOM.Core.Named_Node_Map := DOM.Core.Nodes.Attributes (Node); begin Def.Def_Name := Name; Def.Comment := Util.Beans.Objects.To_Object (Gen.Utils.Get_Comment (Node)); for I in 0 .. DOM.Core.Nodes.Length (Attrs) loop declare A : constant DOM.Core.Node := DOM.Core.Nodes.Item (Attrs, I); begin if A /= null then declare Name : constant DOM.Core.DOM_String := DOM.Core.Nodes.Node_Name (A); Value : constant DOM.Core.DOM_String := DOM.Core.Nodes.Node_Value (A); begin Def.Attrs.Include (Name, Util.Beans.Objects.To_Object (Value)); end; end if; end; end loop; end Initialize; end Gen.Model;
----------------------------------------------------------------------- -- gen-model -- Model for Code Generator -- Copyright (C) 2009, 2010, 2011, 2012, 2018 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Strings.Fixed; with Ada.Strings.Maps; with DOM.Core.Nodes; with Gen.Utils; package body Gen.Model is Trim_Chars : constant Ada.Strings.Maps.Character_Set := Ada.Strings.Maps.To_Set (" " & ASCII.HT & ASCII.LF & ASCII.CR); -- ------------------------------ -- Get the object unique name. -- ------------------------------ function Get_Name (From : in Definition) return String is begin return Ada.Strings.Unbounded.To_String (From.Def_Name); end Get_Name; function Name (From : in Definition) return Ada.Strings.Unbounded.Unbounded_String is begin return From.Def_Name; end Name; -- ------------------------------ -- Set the object unique name. -- ------------------------------ procedure Set_Name (Def : in out Definition; Name : in String) is begin Def.Def_Name := Ada.Strings.Unbounded.To_Unbounded_String (Name); end Set_Name; procedure Set_Name (Def : in out Definition; Name : in Ada.Strings.Unbounded.Unbounded_String) is begin Def.Def_Name := Name; end Set_Name; -- ------------------------------ -- 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 Definition; Name : in String) return Util.Beans.Objects.Object is begin if Name = "comment" then return From.Comment; elsif Name = "rowIndex" then return Util.Beans.Objects.To_Object (From.Row_Index); elsif Name = "name" then return Util.Beans.Objects.To_Object (From.Def_Name); else return From.Attrs.Get_Value (Name); end if; end Get_Value; -- ------------------------------ -- Get the value identified by the name. -- If the name cannot be found, the method should return the Null object. -- ------------------------------ function Get_Attribute (From : in Definition; Name : in String) return String is V : constant Util.Beans.Objects.Object := From.Get_Value (Name); begin return Util.Beans.Objects.To_String (V); end Get_Attribute; -- ------------------------------ -- Get the value identified by the name. -- If the name cannot be found, the method should return the Null object. -- ------------------------------ function Get_Attribute (From : in Definition; Name : in String) return Ada.Strings.Unbounded.Unbounded_String is begin return Ada.Strings.Unbounded.To_Unbounded_String (From.Get_Attribute (Name)); end Get_Attribute; -- ------------------------------ -- Set the comment associated with the element. -- ------------------------------ procedure Set_Comment (Def : in out Definition; Comment : in String) is Trimmed_Comment : constant String := Ada.Strings.Fixed.Trim (Comment, Trim_Chars, Trim_Chars); begin Def.Comment := Util.Beans.Objects.To_Object (Trimmed_Comment); end Set_Comment; -- ------------------------------ -- Get the comment associated with the element. -- ------------------------------ function Get_Comment (Def : in Definition) return Util.Beans.Objects.Object is begin return Def.Comment; end Get_Comment; -- ------------------------------ -- Set the location (file and line) where the model element is defined in the XMI file. -- ------------------------------ procedure Set_Location (Node : in out Definition; Location : in String) is begin Node.Location := Ada.Strings.Unbounded.To_Unbounded_String (Location); end Set_Location; -- ------------------------------ -- Get the location file and line where the model element is defined. -- ------------------------------ function Get_Location (Node : in Definition) return String is begin return Ada.Strings.Unbounded.To_String (Node.Location); end Get_Location; -- ------------------------------ -- Initialize the definition from the DOM node attributes. -- ------------------------------ procedure Initialize (Def : in out Definition; Name : in Ada.Strings.Unbounded.Unbounded_String; Node : in DOM.Core.Node) is use type DOM.Core.Node; Attrs : constant DOM.Core.Named_Node_Map := DOM.Core.Nodes.Attributes (Node); begin Def.Def_Name := Name; Def.Comment := Util.Beans.Objects.To_Object (Gen.Utils.Get_Comment (Node)); for I in 0 .. DOM.Core.Nodes.Length (Attrs) loop declare A : constant DOM.Core.Node := DOM.Core.Nodes.Item (Attrs, I); begin if A /= null then declare Name : constant DOM.Core.DOM_String := DOM.Core.Nodes.Node_Name (A); Value : constant DOM.Core.DOM_String := DOM.Core.Nodes.Node_Value (A); begin Def.Attrs.Include (Name, Util.Beans.Objects.To_Object (Value)); end; end if; end; end loop; end Initialize; -- ------------------------------ -- Validate the definition by checking and reporting problems to the logger interface. -- ------------------------------ procedure Validate (Def : in out Definition; Log : in out Util.Log.Logging'Class) is begin if Ada.Strings.Unbounded.Length (Def.Def_Name) = 0 then Log.Error (Def.Get_Location & ": name is empty"); end if; end Validate; end Gen.Model;
Implement the Validate procedure
Implement the Validate procedure
Ada
apache-2.0
stcarrez/dynamo,stcarrez/dynamo,stcarrez/dynamo
5b23f9f17a749f7fceab1084c37f642fa43366a8
mat/src/mat-readers-streams-sockets.adb
mat/src/mat-readers-streams-sockets.adb
----------------------------------------------------------------------- -- mat-readers-sockets -- Reader for TCP/IP sockets -- Copyright (C) 2014 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Streams; with Util.Log.Loggers; package body MAT.Readers.Streams.Sockets is -- The logger Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("MAT.Readers.Sockets"); BUFFER_SIZE : constant Natural := 100 * 1024; -- ------------------------------ -- Initialize the socket listener. -- ------------------------------ overriding procedure Initialize (Listener : in out Socket_Listener_Type) is begin GNAT.Sockets.Create_Selector (Listener.Accept_Selector); end Initialize; -- ------------------------------ -- Destroy the socket listener. -- ------------------------------ overriding procedure Finalize (Listener : in out Socket_Listener_Type) is use type GNAT.Sockets.Selector_Type; begin GNAT.Sockets.Close_Selector (Listener.Accept_Selector); end Finalize; -- ------------------------------ -- Open the socket to accept connections and start the listener task. -- ------------------------------ procedure Start (Listener : in out Socket_Listener_Type; List : in MAT.Readers.Reader_List_Type_Access; Address : in GNAT.Sockets.Sock_Addr_Type) is begin Log.Info ("Starting the listener socket task"); Listener.List := List; Listener.Listener.Start (Listener'Unchecked_Access, Address); end Start; -- ------------------------------ -- Stop the listener socket. -- ------------------------------ procedure Stop (Listener : in out Socket_Listener_Type) is begin GNAT.Sockets.Abort_Selector (Listener.Accept_Selector); end Stop; -- ------------------------------ -- Create a target instance for the new client. -- ------------------------------ procedure Create_Target (Listener : in out Socket_Listener_Type; Client : in GNAT.Sockets.Socket_Type; Address : in GNAT.Sockets.Sock_Addr_Type) is Reader : constant Socket_Reader_Type_Access := new Socket_Reader_Type; begin Reader.Client := Client; Reader.Stream.Initialize (Size => BUFFER_SIZE, Input => Reader.Socket'Unchecked_Access, Output => null); Reader.Server.Start (Reader, Client); Listener.List.Initialize (Reader.all); Listener.Clients.Append (Reader); end Create_Target; task body Socket_Listener_Task is use type GNAT.Sockets.Socket_Type; use type GNAT.Sockets.Selector_Status; Peer : GNAT.Sockets.Sock_Addr_Type; Server : GNAT.Sockets.Socket_Type; Instance : Socket_Listener_Type_Access; Client : GNAT.Sockets.Socket_Type; Selector_Status : GNAT.Sockets.Selector_Status; begin select accept Start (Listener : in Socket_Listener_Type_Access; Address : in GNAT.Sockets.Sock_Addr_Type) do Instance := Listener; GNAT.Sockets.Create_Socket (Server); GNAT.Sockets.Set_Socket_Option (Server, GNAT.Sockets.Socket_Level, (GNAT.Sockets.Reuse_Address, True)); GNAT.Sockets.Bind_Socket (Server, Address); GNAT.Sockets.Listen_Socket (Server); end Start; or terminate; end select; loop GNAT.Sockets.Accept_Socket (Server => Server, Socket => Client, Address => Peer, Timeout => GNAT.Sockets.Forever, Selector => Instance.Accept_Selector'Access, Status => Selector_Status); exit when Selector_Status = GNAT.Sockets.Aborted; if Selector_Status = GNAT.Sockets.Completed then Instance.Create_Target (Client => Client, Address => Peer); end if; end loop; GNAT.Sockets.Close_Socket (Server); declare Iter : Socket_Client_Lists.Cursor := Instance.Clients.First; begin while Socket_Client_Lists.Has_Element (Iter) loop GNAT.Sockets.Close_Socket (Socket_Client_Lists.Element (Iter).Client); Iter := Socket_Client_Lists.Next (Iter); end loop; end; end Socket_Listener_Task; task body Socket_Reader_Task is use type GNAT.Sockets.Socket_Type; Instance : Socket_Reader_Type_Access; Socket : GNAT.Sockets.Socket_Type; begin select accept Start (Reader : in Socket_Reader_Type_Access; Client : in GNAT.Sockets.Socket_Type) do Instance := Reader; Socket := Client; end Start; or terminate; end select; Instance.Socket.Open (Socket); Instance.Read_All; GNAT.Sockets.Close_Socket (Socket); exception when E : others => Log.Error ("Exception", E, True); GNAT.Sockets.Close_Socket (Socket); end Socket_Reader_Task; procedure Close (Reader : in out Socket_Reader_Type) is begin Reader.Stop := True; end Close; end MAT.Readers.Streams.Sockets;
----------------------------------------------------------------------- -- mat-readers-sockets -- Reader for TCP/IP sockets -- Copyright (C) 2014 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Log.Loggers; package body MAT.Readers.Streams.Sockets is -- The logger Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("MAT.Readers.Sockets"); BUFFER_SIZE : constant Natural := 100 * 1024; -- ------------------------------ -- Initialize the socket listener. -- ------------------------------ overriding procedure Initialize (Listener : in out Socket_Listener_Type) is begin GNAT.Sockets.Create_Selector (Listener.Accept_Selector); end Initialize; -- ------------------------------ -- Destroy the socket listener. -- ------------------------------ overriding procedure Finalize (Listener : in out Socket_Listener_Type) is use type GNAT.Sockets.Selector_Type; begin GNAT.Sockets.Close_Selector (Listener.Accept_Selector); end Finalize; -- ------------------------------ -- Open the socket to accept connections and start the listener task. -- ------------------------------ procedure Start (Listener : in out Socket_Listener_Type; List : in MAT.Readers.Reader_List_Type_Access; Address : in GNAT.Sockets.Sock_Addr_Type) is begin Log.Info ("Starting the listener socket task"); Listener.List := List; Listener.Listener.Start (Listener'Unchecked_Access, Address); end Start; -- ------------------------------ -- Stop the listener socket. -- ------------------------------ procedure Stop (Listener : in out Socket_Listener_Type) is begin GNAT.Sockets.Abort_Selector (Listener.Accept_Selector); end Stop; -- ------------------------------ -- Create a target instance for the new client. -- ------------------------------ procedure Create_Target (Listener : in out Socket_Listener_Type; Client : in GNAT.Sockets.Socket_Type; Address : in GNAT.Sockets.Sock_Addr_Type) is Reader : constant Socket_Reader_Type_Access := new Socket_Reader_Type; begin Reader.Client := Client; Reader.Stream.Initialize (Size => BUFFER_SIZE, Input => Reader.Socket'Unchecked_Access, Output => null); Reader.Server.Start (Reader, Client); Listener.List.Initialize (Reader.all); Listener.Clients.Append (Reader); end Create_Target; task body Socket_Listener_Task is use type GNAT.Sockets.Socket_Type; use type GNAT.Sockets.Selector_Status; Peer : GNAT.Sockets.Sock_Addr_Type; Server : GNAT.Sockets.Socket_Type; Instance : Socket_Listener_Type_Access; Client : GNAT.Sockets.Socket_Type; Selector_Status : GNAT.Sockets.Selector_Status; begin select accept Start (Listener : in Socket_Listener_Type_Access; Address : in GNAT.Sockets.Sock_Addr_Type) do Instance := Listener; GNAT.Sockets.Create_Socket (Server); GNAT.Sockets.Set_Socket_Option (Server, GNAT.Sockets.Socket_Level, (GNAT.Sockets.Reuse_Address, True)); GNAT.Sockets.Bind_Socket (Server, Address); GNAT.Sockets.Listen_Socket (Server); end Start; or terminate; end select; loop GNAT.Sockets.Accept_Socket (Server => Server, Socket => Client, Address => Peer, Timeout => GNAT.Sockets.Forever, Selector => Instance.Accept_Selector'Access, Status => Selector_Status); exit when Selector_Status = GNAT.Sockets.Aborted; if Selector_Status = GNAT.Sockets.Completed then Instance.Create_Target (Client => Client, Address => Peer); end if; end loop; GNAT.Sockets.Close_Socket (Server); declare Iter : Socket_Client_Lists.Cursor := Instance.Clients.First; begin while Socket_Client_Lists.Has_Element (Iter) loop GNAT.Sockets.Close_Socket (Socket_Client_Lists.Element (Iter).Client); Iter := Socket_Client_Lists.Next (Iter); end loop; end; end Socket_Listener_Task; task body Socket_Reader_Task is use type GNAT.Sockets.Socket_Type; Instance : Socket_Reader_Type_Access; Socket : GNAT.Sockets.Socket_Type; begin select accept Start (Reader : in Socket_Reader_Type_Access; Client : in GNAT.Sockets.Socket_Type) do Instance := Reader; Socket := Client; end Start; or terminate; end select; Instance.Socket.Open (Socket); Instance.Read_All; GNAT.Sockets.Close_Socket (Socket); exception when E : others => Log.Error ("Exception", E, True); GNAT.Sockets.Close_Socket (Socket); end Socket_Reader_Task; procedure Close (Reader : in out Socket_Reader_Type) is begin Reader.Stop := True; end Close; end MAT.Readers.Streams.Sockets;
Fix compilation warnings
Fix compilation warnings
Ada
apache-2.0
stcarrez/mat,stcarrez/mat,stcarrez/mat
c45135e633bbb15f5e24a67c70092fc9de67330d
awa/regtests/awa-blogs-modules-tests.adb
awa/regtests/awa-blogs-modules-tests.adb
----------------------------------------------------------------------- -- awa-blogs-tests -- Unit tests for blogs 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 Util.Test_Caller; with ADO; with Security.Contexts; with AWA.Services.Contexts; with AWA.Blogs.Modules; with AWA.Tests.Helpers.Users; package body AWA.Blogs.Modules.Tests is use Util.Tests; use ADO; package Caller is new Util.Test_Caller (Test, "Blogs.Services"); procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is begin Caller.Add_Test (Suite, "Test AWA.Blogs.Services.Create_Blog", Test_Create_Blog'Access); Caller.Add_Test (Suite, "Test AWA.Blogs.Services.Create_Post", Test_Create_Post'Access); end Add_Tests; -- ------------------------------ -- Test creation of a blog -- ------------------------------ procedure Test_Create_Blog (T : in out Test) is Manager : AWA.Blogs.Modules.Blog_Module_Access; Blog_Id : ADO.Identifier; Sec_Ctx : Security.Contexts.Security_Context; Context : AWA.Services.Contexts.Service_Context; begin AWA.Tests.Helpers.Users.Login (Context, Sec_Ctx, "[email protected]"); Manager := AWA.Blogs.Modules.Get_Blog_Module; Manager.Create_Blog (Workspace_Id => 0, Title => "My blog", Result => Blog_Id); T.Assert (Blog_Id > 0, "Invalid blog identifier"); end Test_Create_Blog; -- ------------------------------ -- Test creating and updating of a blog post -- ------------------------------ procedure Test_Create_Post (T : in out Test) is Manager : AWA.Blogs.Modules.Blog_Module_Access; Blog_Id : ADO.Identifier; Post_Id : ADO.Identifier; Sec_Ctx : Security.Contexts.Security_Context; Context : AWA.Services.Contexts.Service_Context; begin AWA.Tests.Helpers.Users.Login (Context, Sec_Ctx, "[email protected]"); Manager := AWA.Blogs.Modules.Get_Blog_Module; Manager.Create_Blog (Workspace_Id => 0, Title => "My blog post", Result => Blog_Id); T.Assert (Blog_Id > 0, "Invalid blog identifier"); for I in 1 .. 5 loop Manager.Create_Post (Blog_Id => Blog_Id, Title => "Testing blog title", URI => "testing-blog-title", Text => "The blog content", Comment => False, Status => AWA.Blogs.Models.POST_DRAFT, Result => Post_Id); T.Assert (Post_Id > 0, "Invalid post identifier"); Manager.Update_Post (Post_Id => Post_Id, Title => "New blog post title", URI => "testing-blog-title", Text => "The new post content", Comment => True, Status => AWA.Blogs.Models.POST_DRAFT); -- Keep the last post in the database. exit when I = 5; Manager.Delete_Post (Post_Id => Post_Id); -- Verify that a Not_Found exception is raised if the post was deleted. begin Manager.Update_Post (Post_Id => Post_Id, Title => "Something", Text => "Content", URI => "testing-blog-title", Comment => True, Status => AWA.Blogs.Models.POST_DRAFT); T.Assert (False, "Exception Not_Found was not raised"); exception when Not_Found => null; end; -- Verify that a Not_Found exception is raised if the post was deleted. begin Manager.Delete_Post (Post_Id => Post_Id); T.Assert (False, "Exception Not_Found was not raised"); exception when Not_Found => null; end; end loop; end Test_Create_Post; end AWA.Blogs.Modules.Tests;
----------------------------------------------------------------------- -- awa-blogs-tests -- Unit tests for blogs module -- Copyright (C) 2011, 2012, 2013, 2014, 2015 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Test_Caller; with ADO; with Security.Contexts; with AWA.Services.Contexts; with AWA.Blogs.Modules; with AWA.Tests.Helpers.Users; package body AWA.Blogs.Modules.Tests is use Util.Tests; use ADO; package Caller is new Util.Test_Caller (Test, "Blogs.Services"); procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is begin Caller.Add_Test (Suite, "Test AWA.Blogs.Services.Create_Blog", Test_Create_Blog'Access); Caller.Add_Test (Suite, "Test AWA.Blogs.Services.Create_Post", Test_Create_Post'Access); end Add_Tests; -- ------------------------------ -- Test creation of a blog -- ------------------------------ procedure Test_Create_Blog (T : in out Test) is Manager : AWA.Blogs.Modules.Blog_Module_Access; Blog_Id : ADO.Identifier; Sec_Ctx : Security.Contexts.Security_Context; Context : AWA.Services.Contexts.Service_Context; begin AWA.Tests.Helpers.Users.Login (Context, Sec_Ctx, "[email protected]"); Manager := AWA.Blogs.Modules.Get_Blog_Module; Manager.Create_Blog (Title => "My blog", Result => Blog_Id); T.Assert (Blog_Id > 0, "Invalid blog identifier"); end Test_Create_Blog; -- ------------------------------ -- Test creating and updating of a blog post -- ------------------------------ procedure Test_Create_Post (T : in out Test) is Manager : AWA.Blogs.Modules.Blog_Module_Access; Blog_Id : ADO.Identifier; Post_Id : ADO.Identifier; Sec_Ctx : Security.Contexts.Security_Context; Context : AWA.Services.Contexts.Service_Context; begin AWA.Tests.Helpers.Users.Login (Context, Sec_Ctx, "[email protected]"); Manager := AWA.Blogs.Modules.Get_Blog_Module; Manager.Create_Blog (Title => "My blog post", Result => Blog_Id); T.Assert (Blog_Id > 0, "Invalid blog identifier"); for I in 1 .. 5 loop Manager.Create_Post (Blog_Id => Blog_Id, Title => "Testing blog title", URI => "testing-blog-title", Text => "The blog content", Comment => False, Status => AWA.Blogs.Models.POST_DRAFT, Result => Post_Id); T.Assert (Post_Id > 0, "Invalid post identifier"); Manager.Update_Post (Post_Id => Post_Id, Title => "New blog post title", URI => "testing-blog-title", Text => "The new post content", Comment => True, Status => AWA.Blogs.Models.POST_DRAFT); -- Keep the last post in the database. exit when I = 5; Manager.Delete_Post (Post_Id => Post_Id); -- Verify that a Not_Found exception is raised if the post was deleted. begin Manager.Update_Post (Post_Id => Post_Id, Title => "Something", Text => "Content", URI => "testing-blog-title", Comment => True, Status => AWA.Blogs.Models.POST_DRAFT); T.Assert (False, "Exception Not_Found was not raised"); exception when Not_Found => null; end; -- Verify that a Not_Found exception is raised if the post was deleted. begin Manager.Delete_Post (Post_Id => Post_Id); T.Assert (False, "Exception Not_Found was not raised"); exception when Not_Found => null; end; end loop; end Test_Create_Post; end AWA.Blogs.Modules.Tests;
Remove the Workspace_Id parameter for the Create_Blog procedure
Remove the Workspace_Id parameter for the Create_Blog procedure
Ada
apache-2.0
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
ce6bc7d4cc1f1f8d2448cdc11f65c3d3337d1047
src/wiki-strings.ads
src/wiki-strings.ads
----------------------------------------------------------------------- -- wiki-strings -- Wiki string types and operations -- Copyright (C) 2016 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Strings.Wide_Wide_Unbounded; with Ada.Characters.Conversions; with Util.Texts.Builders; package Wiki.Strings is pragma Preelaborate; subtype WChar is Wide_Wide_Character; subtype WString is Wide_Wide_String; subtype UString is Ada.Strings.Wide_Wide_Unbounded.Unbounded_Wide_Wide_String; function To_WChar (C : in Character) return WChar renames Ada.Characters.Conversions.To_Wide_Wide_Character; function To_Char (C : in WChar; Substitute : in Character := ' ') return Character renames Ada.Characters.Conversions.To_Character; function To_String (S : in WString; Substitute : in Character := ' ') return String renames Ada.Characters.Conversions.To_String; function To_UString (S : in WString) return UString renames Ada.Strings.Wide_Wide_Unbounded.To_Unbounded_Wide_Wide_String; function To_WString (S : in UString) return WString renames Ada.Strings.Wide_Wide_Unbounded.To_Wide_Wide_String; function To_WString (S : in String) return WString renames Ada.Characters.Conversions.To_Wide_Wide_String; procedure Append (Into : in out UString; S : in WString) renames Ada.Strings.Wide_Wide_Unbounded.Append; procedure Append (Into : in out UString; S : in WChar) renames Ada.Strings.Wide_Wide_Unbounded.Append; function Length (S : in UString) return Natural renames Ada.Strings.Wide_Wide_Unbounded.Length; function Element (S : in UString; Pos : in Positive) return WChar renames Ada.Strings.Wide_Wide_Unbounded.Element; Null_UString : UString renames Ada.Strings.Wide_Wide_Unbounded.Null_Unbounded_Wide_Wide_String; package Wide_Wide_Builders is new Util.Texts.Builders (Element_Type => WChar, Input => WString, Chunk_Size => 512); subtype BString is Wide_Wide_Builders.Builder; end Wiki.Strings;
----------------------------------------------------------------------- -- wiki-strings -- Wiki string types and operations -- Copyright (C) 2016 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Strings.Wide_Wide_Unbounded; with Ada.Characters.Conversions; with Ada.Wide_Wide_Characters.Handling; with Util.Texts.Builders; package Wiki.Strings is pragma Preelaborate; subtype WChar is Wide_Wide_Character; subtype WString is Wide_Wide_String; subtype UString is Ada.Strings.Wide_Wide_Unbounded.Unbounded_Wide_Wide_String; function To_WChar (C : in Character) return WChar renames Ada.Characters.Conversions.To_Wide_Wide_Character; function To_Char (C : in WChar; Substitute : in Character := ' ') return Character renames Ada.Characters.Conversions.To_Character; function To_String (S : in WString; Substitute : in Character := ' ') return String renames Ada.Characters.Conversions.To_String; function To_UString (S : in WString) return UString renames Ada.Strings.Wide_Wide_Unbounded.To_Unbounded_Wide_Wide_String; function To_WString (S : in UString) return WString renames Ada.Strings.Wide_Wide_Unbounded.To_Wide_Wide_String; function To_WString (S : in String) return WString renames Ada.Characters.Conversions.To_Wide_Wide_String; procedure Append (Into : in out UString; S : in WString) renames Ada.Strings.Wide_Wide_Unbounded.Append; procedure Append (Into : in out UString; S : in WChar) renames Ada.Strings.Wide_Wide_Unbounded.Append; function Length (S : in UString) return Natural renames Ada.Strings.Wide_Wide_Unbounded.Length; function Element (S : in UString; Pos : in Positive) return WChar renames Ada.Strings.Wide_Wide_Unbounded.Element; function Is_Alphanumeric (C : in WChar) return Boolean renames Ada.Wide_Wide_Characters.Handling.Is_Alphanumeric; Null_UString : UString renames Ada.Strings.Wide_Wide_Unbounded.Null_Unbounded_Wide_Wide_String; package Wide_Wide_Builders is new Util.Texts.Builders (Element_Type => WChar, Input => WString, Chunk_Size => 512); subtype BString is Wide_Wide_Builders.Builder; end Wiki.Strings;
Declare the Is_Alphanumeric function
Declare the Is_Alphanumeric function
Ada
apache-2.0
stcarrez/ada-wiki,stcarrez/ada-wiki
cc1f7a462034b028bbef565c5110252c5b66d91f
samples/evaluate.adb
samples/evaluate.adb
----------------------------------------------------------------------- -- el -- Evaluate an EL expression -- Copyright (C) 2009, 2010 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with EL.Expressions; with EL.Objects; with EL.Contexts.Default; with Ada.Text_IO; procedure Evaluate is Ctx : EL.Contexts.Default.Default_Context; E : EL.Expressions.Expression; Result : EL.Objects.Object; begin E := EL.Expressions.Create_Expression ("#{1 + (2 - 3) * 4}", Ctx); Result := E.Get_Value (Ctx); Ada.Text_IO.Put_Line ("Result: " & EL.Objects.To_String (Result)); end Evaluate;
----------------------------------------------------------------------- -- el -- Evaluate an EL expression -- Copyright (C) 2009, 2010, 2011 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with EL.Expressions; with EL.Objects; with EL.Contexts.Default; with Ada.Text_IO; procedure Evaluate is Expr : constant String := "#{1 + (2 - 3) * 4}"; Ctx : EL.Contexts.Default.Default_Context; E : EL.Expressions.Expression; Result : EL.Objects.Object; begin Ada.Text_IO.Put_Line ("Evaluate: " & Expr); E := EL.Expressions.Create_Expression (Expr, Ctx); Result := E.Get_Value (Ctx); Ada.Text_IO.Put_Line ("Result: " & EL.Objects.To_String (Result)); end Evaluate;
Print the expression being evaluated
Print the expression being evaluated
Ada
apache-2.0
Letractively/ada-el
cf9970287216ea273ca0019908f8f6cfc695a0d3
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 MAT.Types; package MAT.Consoles is type Field_Type is (F_ADDR, F_SIZE, F_THREAD); type Console_Type is abstract tagged limited private; -- 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; -- 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); private type Console_Type is abstract tagged limited record N : Natural; 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 MAT.Types; package MAT.Consoles is type Field_Type is (F_ADDR, F_SIZE, F_THREAD); type Console_Type is abstract tagged limited private; -- 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; -- 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); private type Console_Type is abstract tagged limited record N : Natural; end record; end MAT.Consoles;
Declare the Print_Size operation
Declare the Print_Size operation
Ada
apache-2.0
stcarrez/mat,stcarrez/mat,stcarrez/mat
4086fd94fb8fe8deaf8b477e101848881df27efd
samples/encodes.adb
samples/encodes.adb
----------------------------------------------------------------------- -- encodes -- Encodes strings -- Copyright (C) 2010, 2011 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Text_IO; with Ada.Command_Line; with Util.Encoders; procedure Encodes is use Util.Encoders; Encode : Boolean := True; Count : constant Natural := Ada.Command_Line.Argument_Count; begin if Count <= 1 then Ada.Text_IO.Put_Line ("Usage: encodes {encoder} [-d|-e] string..."); Ada.Text_IO.Put_Line ("Encoders: " & Util.Encoders.BASE_64 & ", " & Util.Encoders.BASE_64_URL & ", " & Util.Encoders.BASE_16); return; end if; declare Name : constant String := Ada.Command_Line.Argument (1); C : constant Encoder := Util.Encoders.Create (Name); begin for I in 2 .. Count loop declare S : constant String := Ada.Command_Line.Argument (I); begin if S = "-d" then Encode := False; elsif S = "-e" then Encode := True; elsif Encode then Ada.Text_IO.Put_Line ("Encodes " & Name & ": " & C.Encode (S)); else Ada.Text_IO.Put_Line ("Decodes " & Name & ": " & C.Decode (S)); end if; end; end loop; end; end Encodes;
----------------------------------------------------------------------- -- encodes -- Encodes strings -- Copyright (C) 2010, 2011 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Text_IO; with Ada.Command_Line; with Util.Encoders; procedure Encodes is use Util.Encoders; Encode : Boolean := True; Count : constant Natural := Ada.Command_Line.Argument_Count; begin if Count <= 1 then Ada.Text_IO.Put_Line ("Usage: encodes {encoder} [-d|-e] string..."); Ada.Text_IO.Put_Line ("Encoders: " & Util.Encoders.BASE_64 & ", " & Util.Encoders.BASE_64_URL & ", " & Util.Encoders.BASE_16 & ", " & Util.Encoders.HASH_SHA1); return; end if; declare Name : constant String := Ada.Command_Line.Argument (1); C : constant Encoder := Util.Encoders.Create (Name); begin for I in 2 .. Count loop declare S : constant String := Ada.Command_Line.Argument (I); begin if S = "-d" then Encode := False; elsif S = "-e" then Encode := True; elsif Encode then Ada.Text_IO.Put_Line ("Encodes " & Name & ": " & C.Encode (S)); else Ada.Text_IO.Put_Line ("Decodes " & Name & ": " & C.Decode (S)); end if; end; end loop; end; end Encodes;
Add sha1 encoding
Add sha1 encoding
Ada
apache-2.0
Letractively/ada-util,flottokarotto/ada-util,flottokarotto/ada-util,Letractively/ada-util
748977d15020f1de8b3a654f6acadeb4f3c450ef
regtests/ado-schemas-tests.adb
regtests/ado-schemas-tests.adb
----------------------------------------------------------------------- -- schemas Tests -- Test loading of database schema -- 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 Util.Test_Caller; with ADO.Sessions; with ADO.Schemas.Entities; with Regtests; with Regtests.Simple.Model; package body ADO.Schemas.Tests is use Util.Tests; package Caller is new Util.Test_Caller (Test, "ADO.Schemas"); procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is begin Caller.Add_Test (Suite, "Test ADO.Schemas.Entities.Find_Entity_Type", Test_Find_Entity_Type'Access); Caller.Add_Test (Suite, "Test ADO.Schemas.Entities.Find_Entity_Type (error)", Test_Find_Entity_Type_Error'Access); Caller.Add_Test (Suite, "Test ADO.Sessions.Load_Schema", Test_Load_Schema'Access); Caller.Add_Test (Suite, "Test ADO.Schemas.Get_Table", Test_Table_Iterator'Access); Caller.Add_Test (Suite, "Test ADO.Schemas.Get_Table (Empty schema)", Test_Empty_Schema'Access); end Add_Tests; -- ------------------------------ -- Test reading the entity cache and the Find_Entity_Type operation -- ------------------------------ procedure Test_Find_Entity_Type (T : in out Test) is S : ADO.Sessions.Session := Regtests.Get_Database; C : ADO.Schemas.Entities.Entity_Cache; begin ADO.Schemas.Entities.Initialize (Cache => C, Session => S); declare -- T1 : constant ADO.Model.Entity_Type_Ref -- := Entities.Find_Entity_Type (Cache => C, -- Table => Regtests.Simple.Model.USER_TABLE'Access); -- T2 : constant ADO.Model.Entity_Type_Ref -- := Entities.Find_Entity_Type (Cache => C, -- Table => Regtests.Simple.Model.ALLOCATE_TABLE'Access); T4 : constant ADO.Entity_Type := Entities.Find_Entity_Type (Cache => C, Table => Regtests.Simple.Model.ALLOCATE_TABLE); T5 : constant ADO.Entity_Type := Entities.Find_Entity_Type (Cache => C, Table => Regtests.Simple.Model.USER_TABLE); begin -- T.Assert (not ADO.Objects.Is_Null (T1), "Find_Entity_Type returned a null value"); -- T.Assert (not ADO.Objects.Is_Null (T2), "Find_Entity_Type returned a null value"); T.Assert (T4 /= T5, "Two distinct tables have different entity types"); T.Assert (T4 > 0, "T1.Id must be positive"); T.Assert (T5 > 0, "T2.Id must be positive"); -- T.Assert (T1.Get_Id /= T2.Get_Id, "Two distinct tables have different ids"); -- -- Assert_Equals (T, Integer (T2.Get_Id), Integer (T4), -- "Invalid entity type for allocate_table"); -- Assert_Equals (T, Integer (T1.Get_Id), Integer (T5), -- "Invalid entity type for user_table"); end; end Test_Find_Entity_Type; -- ------------------------------ -- Test calling Find_Entity_Type with an invalid table. -- ------------------------------ procedure Test_Find_Entity_Type_Error (T : in out Test) is C : ADO.Schemas.Entities.Entity_Cache; begin declare R : ADO.Entity_Type; pragma Unreferenced (R); begin R := Entities.Find_Entity_Type (Cache => C, Table => Regtests.Simple.Model.USER_TABLE); T.Assert (False, "Find_Entity_Type did not raise the No_Entity_Type exception"); exception when ADO.Schemas.Entities.No_Entity_Type => null; end; end Test_Find_Entity_Type_Error; -- ------------------------------ -- Test the Load_Schema operation and check the result schema. -- ------------------------------ procedure Test_Load_Schema (T : in out Test) is S : constant ADO.Sessions.Session := Regtests.Get_Database; Schema : Schema_Definition; Table : Table_Definition; begin S.Load_Schema (Schema); Table := ADO.Schemas.Find_Table (Schema, "allocate"); T.Assert (Table /= null, "Table schema for test_allocate not found"); Assert_Equals (T, "allocate", Get_Name (Table)); declare C : Column_Cursor := Get_Columns (Table); Nb_Columns : Integer := 0; begin while Has_Element (C) loop Nb_Columns := Nb_Columns + 1; Next (C); end loop; Assert_Equals (T, 3, Nb_Columns, "Invalid number of columns"); end; declare C : constant Column_Definition := Find_Column (Table, "ID"); begin T.Assert (C /= null, "Cannot find column 'id' in table schema"); Assert_Equals (T, "ID", Get_Name (C), "Invalid column name"); T.Assert (Get_Type (C) = T_LONG_INTEGER, "Invalid column type"); T.Assert (not Is_Null (C), "Column is null"); end; declare C : constant Column_Definition := Find_Column (Table, "NAME"); begin T.Assert (C /= null, "Cannot find column 'NAME' in table schema"); Assert_Equals (T, "NAME", Get_Name (C), "Invalid column name"); T.Assert (Get_Type (C) = T_VARCHAR, "Invalid column type"); T.Assert (Is_Null (C), "Column is null"); end; declare C : constant Column_Definition := Find_Column (Table, "version"); begin T.Assert (C /= null, "Cannot find column 'version' in table schema"); Assert_Equals (T, "version", Get_Name (C), "Invalid column name"); T.Assert (Get_Type (C) = T_INTEGER, "Invalid column type"); T.Assert (not Is_Null (C), "Column is null"); end; declare C : constant Column_Definition := Find_Column (Table, "this_column_does_not_exist"); begin T.Assert (C = null, "Find_Column must return null for an unknown column"); end; end Test_Load_Schema; -- ------------------------------ -- Test the Table_Cursor operations and check the result schema. -- ------------------------------ procedure Test_Table_Iterator (T : in out Test) is S : constant ADO.Sessions.Session := Regtests.Get_Database; Schema : Schema_Definition; Table : Table_Definition; Driver : constant String := S.Get_Driver.Get_Driver_Name; begin S.Load_Schema (Schema); declare Iter : Table_Cursor := Schema.Get_Tables; Count : Natural := 0; begin T.Assert (Has_Element (Iter), "The Get_Tables returns an empty iterator"); while Has_Element (Iter) loop Table := Element (Iter); T.Assert (Table /= null, "Element function must not return null"); declare Col_Iter : Column_Cursor := Get_Columns (Table); begin -- T.Assert (Has_Element (Col_Iter), "Table has a column"); while Has_Element (Col_Iter) loop T.Assert (Element (Col_Iter) /= null, "Element function must not return null"); Next (Col_Iter); end loop; end; Count := Count + 1; Next (Iter); end loop; if Driver = "sqlite" then Util.Tests.Assert_Equals (T, 15, Count, "Invalid number of tables found in the schema"); elsif Driver = "mysql" then Util.Tests.Assert_Equals (T, 8, Count, "Invalid number of tables found in the schema"); end if; end; end Test_Table_Iterator; -- ------------------------------ -- Test the Table_Cursor operations on an empty schema. -- ------------------------------ procedure Test_Empty_Schema (T : in out Test) is Schema : Schema_Definition; Iter : constant Table_Cursor := Schema.Get_Tables; begin T.Assert (not Has_Element (Iter), "The Get_Tables must return an empty iterator"); T.Assert (Schema.Find_Table ("test") = null, "The Find_Table must return null"); end Test_Empty_Schema; end ADO.Schemas.Tests;
----------------------------------------------------------------------- -- schemas Tests -- Test loading of database schema -- Copyright (C) 2009, 2010, 2011, 2012, 2015, 2017, 2018 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Test_Caller; with Util.Strings.Transforms; with ADO.Sessions; with ADO.Schemas.Entities; with Regtests; with Regtests.Simple.Model; package body ADO.Schemas.Tests is use Util.Tests; function To_Lower_Case (S : in String) return String renames Util.Strings.Transforms.To_Lower_Case; package Caller is new Util.Test_Caller (Test, "ADO.Schemas"); procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is begin Caller.Add_Test (Suite, "Test ADO.Schemas.Entities.Find_Entity_Type", Test_Find_Entity_Type'Access); Caller.Add_Test (Suite, "Test ADO.Schemas.Entities.Find_Entity_Type (error)", Test_Find_Entity_Type_Error'Access); Caller.Add_Test (Suite, "Test ADO.Sessions.Load_Schema", Test_Load_Schema'Access); Caller.Add_Test (Suite, "Test ADO.Schemas.Get_Table", Test_Table_Iterator'Access); Caller.Add_Test (Suite, "Test ADO.Schemas.Get_Table (Empty schema)", Test_Empty_Schema'Access); end Add_Tests; -- ------------------------------ -- Test reading the entity cache and the Find_Entity_Type operation -- ------------------------------ procedure Test_Find_Entity_Type (T : in out Test) is S : ADO.Sessions.Session := Regtests.Get_Database; C : ADO.Schemas.Entities.Entity_Cache; begin ADO.Schemas.Entities.Initialize (Cache => C, Session => S); declare -- T1 : constant ADO.Model.Entity_Type_Ref -- := Entities.Find_Entity_Type (Cache => C, -- Table => Regtests.Simple.Model.USER_TABLE'Access); -- T2 : constant ADO.Model.Entity_Type_Ref -- := Entities.Find_Entity_Type (Cache => C, -- Table => Regtests.Simple.Model.ALLOCATE_TABLE'Access); T4 : constant ADO.Entity_Type := Entities.Find_Entity_Type (Cache => C, Table => Regtests.Simple.Model.ALLOCATE_TABLE); T5 : constant ADO.Entity_Type := Entities.Find_Entity_Type (Cache => C, Table => Regtests.Simple.Model.USER_TABLE); begin -- T.Assert (not ADO.Objects.Is_Null (T1), "Find_Entity_Type returned a null value"); -- T.Assert (not ADO.Objects.Is_Null (T2), "Find_Entity_Type returned a null value"); T.Assert (T4 /= T5, "Two distinct tables have different entity types"); T.Assert (T4 > 0, "T1.Id must be positive"); T.Assert (T5 > 0, "T2.Id must be positive"); -- T.Assert (T1.Get_Id /= T2.Get_Id, "Two distinct tables have different ids"); -- -- Assert_Equals (T, Integer (T2.Get_Id), Integer (T4), -- "Invalid entity type for allocate_table"); -- Assert_Equals (T, Integer (T1.Get_Id), Integer (T5), -- "Invalid entity type for user_table"); end; end Test_Find_Entity_Type; -- ------------------------------ -- Test calling Find_Entity_Type with an invalid table. -- ------------------------------ procedure Test_Find_Entity_Type_Error (T : in out Test) is C : ADO.Schemas.Entities.Entity_Cache; begin declare R : ADO.Entity_Type; pragma Unreferenced (R); begin R := Entities.Find_Entity_Type (Cache => C, Table => Regtests.Simple.Model.USER_TABLE); T.Assert (False, "Find_Entity_Type did not raise the No_Entity_Type exception"); exception when ADO.Schemas.Entities.No_Entity_Type => null; end; end Test_Find_Entity_Type_Error; -- ------------------------------ -- Test the Load_Schema operation and check the result schema. -- ------------------------------ procedure Test_Load_Schema (T : in out Test) is S : constant ADO.Sessions.Session := Regtests.Get_Database; Schema : Schema_Definition; Table : Table_Definition; begin S.Load_Schema (Schema); Table := ADO.Schemas.Find_Table (Schema, "allocate"); T.Assert (Table /= null, "Table schema for test_allocate not found"); Assert_Equals (T, "allocate", Get_Name (Table)); declare C : Column_Cursor := Get_Columns (Table); Nb_Columns : Integer := 0; begin while Has_Element (C) loop Nb_Columns := Nb_Columns + 1; Next (C); end loop; Assert_Equals (T, 3, Nb_Columns, "Invalid number of columns"); end; declare C : constant Column_Definition := Find_Column (Table, "ID"); begin T.Assert (C /= null, "Cannot find column 'id' in table schema"); Assert_Equals (T, "id", To_Lower_Case (Get_Name (C)), "Invalid column name"); T.Assert (Get_Type (C) = T_LONG_INTEGER, "Invalid column type"); T.Assert (not Is_Null (C), "Column is null"); end; declare C : constant Column_Definition := Find_Column (Table, "NAME"); begin T.Assert (C /= null, "Cannot find column 'NAME' in table schema"); Assert_Equals (T, "name", To_Lower_Case (Get_Name (C)), "Invalid column name"); T.Assert (Get_Type (C) = T_VARCHAR, "Invalid column type"); T.Assert (Is_Null (C), "Column is null"); end; declare C : constant Column_Definition := Find_Column (Table, "version"); begin T.Assert (C /= null, "Cannot find column 'version' in table schema"); Assert_Equals (T, "version", To_Lower_Case (Get_Name (C)), "Invalid column name"); T.Assert (Get_Type (C) = T_INTEGER, "Invalid column type"); T.Assert (not Is_Null (C), "Column is null"); end; declare C : constant Column_Definition := Find_Column (Table, "this_column_does_not_exist"); begin T.Assert (C = null, "Find_Column must return null for an unknown column"); end; end Test_Load_Schema; -- ------------------------------ -- Test the Table_Cursor operations and check the result schema. -- ------------------------------ procedure Test_Table_Iterator (T : in out Test) is S : constant ADO.Sessions.Session := Regtests.Get_Database; Schema : Schema_Definition; Table : Table_Definition; Driver : constant String := S.Get_Driver.Get_Driver_Name; begin S.Load_Schema (Schema); declare Iter : Table_Cursor := Schema.Get_Tables; Count : Natural := 0; begin T.Assert (Has_Element (Iter), "The Get_Tables returns an empty iterator"); while Has_Element (Iter) loop Table := Element (Iter); T.Assert (Table /= null, "Element function must not return null"); declare Col_Iter : Column_Cursor := Get_Columns (Table); begin -- T.Assert (Has_Element (Col_Iter), "Table has a column"); while Has_Element (Col_Iter) loop T.Assert (Element (Col_Iter) /= null, "Element function must not return null"); Next (Col_Iter); end loop; end; Count := Count + 1; Next (Iter); end loop; if Driver = "sqlite" then Util.Tests.Assert_Equals (T, 15, Count, "Invalid number of tables found in the schema"); elsif Driver = "mysql" then Util.Tests.Assert_Equals (T, 8, Count, "Invalid number of tables found in the schema"); elsif Driver = "postgresql" then Util.Tests.Assert_Equals (T, 8, Count, "Invalid number of tables found in the schema"); end if; end; end Test_Table_Iterator; -- ------------------------------ -- Test the Table_Cursor operations on an empty schema. -- ------------------------------ procedure Test_Empty_Schema (T : in out Test) is Schema : Schema_Definition; Iter : constant Table_Cursor := Schema.Get_Tables; begin T.Assert (not Has_Element (Iter), "The Get_Tables must return an empty iterator"); T.Assert (Schema.Find_Table ("test") = null, "The Find_Table must return null"); end Test_Empty_Schema; end ADO.Schemas.Tests;
Update the test to ignore the case of table and column names
Update the test to ignore the case of table and column names
Ada
apache-2.0
stcarrez/ada-ado
d7ec1ff61859cc64b324005a40a6f78468939a76
matp/src/mat-types.adb
matp/src/mat-types.adb
----------------------------------------------------------------------- -- mat-types -- Global types -- 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. ----------------------------------------------------------------------- package body MAT.Types is -- ------------------------------ -- Return an hexadecimal string representation of the value. -- ------------------------------ function Hex_Image (Value : in Uint32; Length : in Positive := 8) return String is use type Interfaces.Unsigned_32; Conversion : constant String (1 .. 16) := "0123456789ABCDEF"; S : String (1 .. Length) := (others => '0'); P : Uint32 := Value; N : Uint32; I : Positive := Length; begin while P /= 0 loop N := P mod 16; P := P / 16; S (I) := Conversion (Natural (N + 1)); exit when I = 1; I := I - 1; end loop; return S; end Hex_Image; -- ------------------------------ -- Return an hexadecimal string representation of the value. -- ------------------------------ function Hex_Image (Value : in Uint64; Length : in Positive := 16) return String is use type Interfaces.Unsigned_64; Conversion : constant String (1 .. 16) := "0123456789ABCDEF"; S : String (1 .. Length) := (others => '0'); P : Uint64 := Value; N : Uint64; I : Positive := Length; begin while P /= 0 loop N := P mod 16; P := P / 16; S (I) := Conversion (Natural (N + 1)); exit when I = 1; I := I - 1; end loop; return S; end Hex_Image; -- ------------------------------ -- Format the target time to a printable representation. -- ------------------------------ function Tick_Image (Value : in Target_Tick_Ref) return String is use Interfaces; Sec : constant Unsigned_32 := Unsigned_32 (Interfaces.Shift_Right (Uint64 (Value), 32)); Usec : constant Unsigned_32 := Interfaces.Unsigned_32 (Value and 16#0ffffffff#); Frac : constant String := Interfaces.Unsigned_32'Image (Usec); Img : String (1 .. 6) := (others => '0'); begin Img (Img'Last - Frac'Length + 2 .. Img'Last) := Frac (Frac'First + 1 .. Frac'Last); return Interfaces.Unsigned_32'Image (Sec) & "." & Img; end Tick_Image; function "-" (Left, Right : in Target_Tick_Ref) return Target_Tick_Ref is use Interfaces; Res : Target_Tick_Ref := Target_Tick_Ref (Uint64 (Left) - Uint64 (Right)); Usec1 : constant Unsigned_32 := Interfaces.Unsigned_32 (Left and 16#0ffffffff#); Usec2 : constant Unsigned_32 := Interfaces.Unsigned_32 (Right and 16#0ffffffff#); begin if Usec1 < Usec2 then Res := Res and 16#ffffffff00000000#; Res := Target_Tick_Ref (Uint64 (Res) - 16#100000000#); Res := Res or Target_Tick_Ref (1000000 - (Usec2 - Usec1)); end if; return Res; end "-"; end MAT.Types;
----------------------------------------------------------------------- -- mat-types -- Global types -- 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. ----------------------------------------------------------------------- package body MAT.Types is -- ------------------------------ -- Return an hexadecimal string representation of the value. -- ------------------------------ function Hex_Image (Value : in Uint32; Length : in Positive := 8) return String is use type Interfaces.Unsigned_32; Conversion : constant String (1 .. 16) := "0123456789ABCDEF"; S : String (1 .. Length) := (others => '0'); P : Uint32 := Value; N : Uint32; I : Positive := Length; begin while P /= 0 loop N := P mod 16; P := P / 16; S (I) := Conversion (Natural (N + 1)); exit when I = 1; I := I - 1; end loop; return S; end Hex_Image; -- ------------------------------ -- Return an hexadecimal string representation of the value. -- ------------------------------ function Hex_Image (Value : in Uint64; Length : in Positive := 16) return String is use type Interfaces.Unsigned_64; Conversion : constant String (1 .. 16) := "0123456789ABCDEF"; S : String (1 .. Length) := (others => '0'); P : Uint64 := Value; N : Uint64; I : Positive := Length; begin while P /= 0 loop N := P mod 16; P := P / 16; S (I) := Conversion (Natural (N + 1)); exit when I = 1; I := I - 1; end loop; return S; end Hex_Image; -- ------------------------------ -- Format the target time to a printable representation. -- ------------------------------ function Tick_Image (Value : in Target_Tick_Ref) return String is use Interfaces; Sec : constant Unsigned_32 := Unsigned_32 (Interfaces.Shift_Right (Uint64 (Value), 32)); Usec : constant Unsigned_32 := Interfaces.Unsigned_32 (Value and 16#0ffffffff#); Frac : constant String := Interfaces.Unsigned_32'Image (Usec); Img : String (1 .. 6) := (others => '0'); begin Img (Img'Last - Frac'Length + 2 .. Img'Last) := Frac (Frac'First + 1 .. Frac'Last); return Interfaces.Unsigned_32'Image (Sec) & "." & Img; end Tick_Image; function "-" (Left, Right : in Target_Tick_Ref) return Target_Tick_Ref is use Interfaces; Res : Target_Tick_Ref := Target_Tick_Ref (Uint64 (Left) - Uint64 (Right)); Usec1 : constant Unsigned_32 := Interfaces.Unsigned_32 (Left and 16#0ffffffff#); Usec2 : constant Unsigned_32 := Interfaces.Unsigned_32 (Right and 16#0ffffffff#); begin if Usec1 < Usec2 then Res := Res and 16#ffffffff00000000#; Res := Target_Tick_Ref (Uint64 (Res) - 16#100000000#); Res := Res or Target_Tick_Ref (1000000 - (Usec2 - Usec1)); end if; return Res; end "-"; -- ------------------------------ -- Convert the hexadecimal string into an unsigned integer. -- ------------------------------ function Hex_Value (Value : in String) return Uint64 is use type Interfaces.Unsigned_64; Result : Uint64 := 0; begin if Value'Length = 0 then raise Constraint_Error with "Empty string"; end if; for I in Value'Range loop declare C : constant Character := Value (I); begin if C >= '0' and C <= '9' then Result := (Result * 16) + (Character'Pos (C) - Character'Pos ('0')); elsif C >= 'A' and C <= 'F' then Result := (Result * 16) + (Character'Pos (C) - Character'Pos ('F') + 10); elsif C >= 'a' and C <= 'f' then Result := (Result * 16) + (Character'Pos (C) - Character'Pos ('f') + 10); else raise Constraint_Error with "Invalid character: " & C; end if; end; end loop; return Result; end Hex_Value; end MAT.Types;
Implement the Hex_Value function to convert a hexadecimal string into a number
Implement the Hex_Value function to convert a hexadecimal string into a number
Ada
apache-2.0
stcarrez/mat,stcarrez/mat,stcarrez/mat
6d412940f0662164b8b6b09c0e455ecfa90345c1
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.Next.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.Next.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.Next.Add_Header (Document, Header, Level); else Wiki.Nodes.Append (Document, Header, Level); end if; end Add_Header; -- ------------------------------ -- 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) is begin if Filter.Next /= null then Filter.Next.Push_Node (Document, Tag, Attributes); else Wiki.Nodes.Push_Node (Document, Tag, Attributes); end if; end Push_Node; -- ------------------------------ -- 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) is begin if Filter.Next /= null then Filter.Next.Pop_Node (Document, Tag); else Wiki.Nodes.Pop_Node (Document, Tag); end if; end Pop_Node; -- ------------------------------ -- Add a blockquote (<blockquote>). The level indicates the blockquote nested level. -- The blockquote must be closed at the next header. -- ------------------------------ procedure Add_Blockquote (Filter : in out Filter_Type; Document : in out Wiki.Nodes.Document; Level : in Natural) is begin if Filter.Next /= null then Filter.Next.Add_Blockquote (Document, Level); else Wiki.Nodes.Add_Blockquote (Document, Level); end if; 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. -- ------------------------------ procedure Add_List_Item (Filter : in out Filter_Type; Document : in out Wiki.Nodes.Document; Level : in Positive; Ordered : in Boolean) is begin if Filter.Next /= null then Filter.Next.Add_List_Item (Document, Level, Ordered); else Wiki.Nodes.Add_List_Item (Document, Level, Ordered); end if; end Add_List_Item; -- ------------------------------ -- 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) is begin if Filter.Next /= null then Filter.Next.Add_Link (Document, Name, Attributes); else Wiki.Nodes.Add_Link (Document, Name, Attributes); end if; end Add_Link; -- ------------------------------ -- 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) is begin if Filter.Next /= null then Filter.Next.Add_Image (Document, Name, Attributes); else Wiki.Nodes.Add_Image (Document, Name, Attributes); end if; end Add_Image; -- ------------------------------ -- 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) is begin if Filter.Next /= null then Filter.Next.Add_Quote (Document, Name, Attributes); else Wiki.Nodes.Add_Quote (Document, Name, Attributes); end if; end Add_Quote; -- ------------------------------ -- Add a text block that is pre-formatted. -- ------------------------------ procedure Add_Preformatted (Filter : in out Filter_Type; Document : in out Wiki.Nodes.Document; Text : in Wiki.Strings.WString; Format : in Unbounded_Wide_Wide_String) is begin if Filter.Next /= null then Filter.Next.Add_Preformatted (Document, Text, Format); else Wiki.Nodes.Add_Preformatted (Document, Text, Format); end if; end Add_Preformatted; -- ------------------------------ -- Finish the document after complete wiki text has been parsed. -- ------------------------------ procedure Finish (Filter : in out Filter_Type) is begin if Filter.Next /= null then Filter.Next.Finish; end if; end Finish; 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.Next.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.Next.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.Next.Add_Header (Document, Header, Level); else Wiki.Nodes.Append (Document, Header, Level); end if; end Add_Header; -- ------------------------------ -- 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) is begin if Filter.Next /= null then Filter.Next.Push_Node (Document, Tag, Attributes); else Wiki.Nodes.Push_Node (Document, Tag, Attributes); end if; end Push_Node; -- ------------------------------ -- 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) is begin if Filter.Next /= null then Filter.Next.Pop_Node (Document, Tag); else Wiki.Nodes.Pop_Node (Document, Tag); end if; end Pop_Node; -- ------------------------------ -- Add a blockquote (<blockquote>). The level indicates the blockquote nested level. -- The blockquote must be closed at the next header. -- ------------------------------ procedure Add_Blockquote (Filter : in out Filter_Type; Document : in out Wiki.Nodes.Document; Level : in Natural) is begin if Filter.Next /= null then Filter.Next.Add_Blockquote (Document, Level); else Wiki.Nodes.Add_Blockquote (Document, Level); end if; 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. -- ------------------------------ procedure Add_List_Item (Filter : in out Filter_Type; Document : in out Wiki.Nodes.Document; Level : in Positive; Ordered : in Boolean) is begin if Filter.Next /= null then Filter.Next.Add_List_Item (Document, Level, Ordered); else Wiki.Nodes.Add_List_Item (Document, Level, Ordered); end if; end Add_List_Item; -- ------------------------------ -- 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) is begin if Filter.Next /= null then Filter.Next.Add_Link (Document, Name, Attributes); else Wiki.Nodes.Add_Link (Document, Name, Attributes); end if; end Add_Link; -- ------------------------------ -- 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) is begin if Filter.Next /= null then Filter.Next.Add_Image (Document, Name, Attributes); else Wiki.Nodes.Add_Image (Document, Name, Attributes); end if; end Add_Image; -- ------------------------------ -- 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) is begin if Filter.Next /= null then Filter.Next.Add_Quote (Document, Name, Attributes); else Wiki.Nodes.Add_Quote (Document, Name, Attributes); end if; end Add_Quote; -- ------------------------------ -- Add a text block that is pre-formatted. -- ------------------------------ procedure Add_Preformatted (Filter : in out Filter_Type; Document : in out Wiki.Nodes.Document; Text : in Wiki.Strings.WString; Format : in Unbounded_Wide_Wide_String) is begin if Filter.Next /= null then Filter.Next.Add_Preformatted (Document, Text, Format); else Wiki.Nodes.Add_Preformatted (Document, Text, Format); end if; end Add_Preformatted; -- ------------------------------ -- Finish the document after complete wiki text has been parsed. -- ------------------------------ procedure Finish (Filter : in out Filter_Type; Document : in out Wiki.Nodes.Document) is begin if Filter.Next /= null then Filter.Next.Finish (Document); end if; end Finish; end Wiki.Filters;
Add a Document parameter to the Finish procedure
Add a Document parameter to the Finish procedure
Ada
apache-2.0
stcarrez/ada-wiki,stcarrez/ada-wiki
e0ffd8c943268661686fabb0702e9e90a9f7c884
src/asf-lifecycles-restore.adb
src/asf-lifecycles-restore.adb
----------------------------------------------------------------------- -- asf-lifecycles-restore -- Restore view phase -- Copyright (C) 2010, 2011, 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 Ada.Exceptions; with ASF.Applications.Main; with ASF.Components.Root; with ASF.Requests; with Util.Log.Loggers; package body ASF.Lifecycles.Restore is use Ada.Exceptions; use ASF.Applications; -- The logger Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("ASF.Lifecycles.Restore"); -- ------------------------------ -- Initialize the phase controller. -- ------------------------------ overriding procedure Initialize (Controller : in out Restore_Controller; App : access ASF.Applications.Main.Application'Class) is begin Controller.View_Handler := App.Get_View_Handler; end Initialize; -- ------------------------------ -- Execute the restore view phase. -- ------------------------------ overriding procedure Execute (Controller : in Restore_Controller; Context : in out ASF.Contexts.Faces.Faces_Context'Class) is use ASF.Components; Req : constant ASF.Requests.Request_Access := Context.Get_Request; Page : constant String := Context.Get_View_Name; View : Components.Root.UIViewRoot; begin Controller.View_Handler.Restore_View (Page, Context, View); Context.Set_View_Root (View); -- If the view was not found, render the response immediately. -- The missing page will be handled by the lifecycle response handler. if Components.Root.Get_Root (View) = null then Context.Render_Response; -- If this is not a postback, check for view parameters. elsif Req.Get_Method = "GET" then -- We need to process the ASF lifecycle towards the meta data component tree. -- This allows some Ada beans to be initialized from the request parameters -- and have some component actions called on the http GET (See <f:viewActions)). Components.Root.Set_Meta (View); -- If the view has no meta data, render the response immediately. if not Components.Root.Has_Meta (View) then Context.Render_Response; end if; end if; exception when E : others => Log.Error ("Error when restoring view {0}: {1}: {2}", Page, Exception_Name (E), Exception_Message (E)); raise; end Execute; end ASF.Lifecycles.Restore;
----------------------------------------------------------------------- -- asf-lifecycles-restore -- Restore view phase -- Copyright (C) 2010, 2011, 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 Ada.Exceptions; with ASF.Applications.Main; with ASF.Components.Root; with ASF.Requests; with Util.Log.Loggers; package body ASF.Lifecycles.Restore is use Ada.Exceptions; use ASF.Applications; -- The logger Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("ASF.Lifecycles.Restore"); -- ------------------------------ -- Initialize the phase controller. -- ------------------------------ overriding procedure Initialize (Controller : in out Restore_Controller; Views : access ASF.Applications.Views.View_Handler'Class) is begin Controller.View_Handler := Views; end Initialize; -- ------------------------------ -- Execute the restore view phase. -- ------------------------------ overriding procedure Execute (Controller : in Restore_Controller; Context : in out ASF.Contexts.Faces.Faces_Context'Class) is use ASF.Components; Req : constant ASF.Requests.Request_Access := Context.Get_Request; Page : constant String := Context.Get_View_Name; View : Components.Root.UIViewRoot; begin Controller.View_Handler.Restore_View (Page, Context, View); Context.Set_View_Root (View); -- If the view was not found, render the response immediately. -- The missing page will be handled by the lifecycle response handler. if Components.Root.Get_Root (View) = null then Context.Render_Response; -- If this is not a postback, check for view parameters. elsif Req.Get_Method = "GET" then -- We need to process the ASF lifecycle towards the meta data component tree. -- This allows some Ada beans to be initialized from the request parameters -- and have some component actions called on the http GET (See <f:viewActions)). Components.Root.Set_Meta (View); -- If the view has no meta data, render the response immediately. if not Components.Root.Has_Meta (View) then Context.Render_Response; end if; end if; exception when E : others => Log.Error ("Error when restoring view {0}: {1}: {2}", Page, Exception_Name (E), Exception_Message (E)); raise; end Execute; end ASF.Lifecycles.Restore;
Update Initialize to use a ASF.Applications.Views.View_Handler'Class
Update Initialize to use a ASF.Applications.Views.View_Handler'Class
Ada
apache-2.0
stcarrez/ada-asf,stcarrez/ada-asf,stcarrez/ada-asf
56739b0a05d3066cbe035f35be5bf7507706f657
src/security-policies-urls.adb
src/security-policies-urls.adb
----------------------------------------------------------------------- -- security-policies-urls -- URL security policy -- Copyright (C) 2010, 2011, 2012 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Unchecked_Deallocation; with Util.Beans.Objects; with Util.Beans.Objects.Vectors; with Util.Serialize.Mappers; with Util.Serialize.Mappers.Record_Mapper; with Security.Controllers.URLs; package body Security.Policies.URLs is -- ------------------------------ -- Get the policy name. -- ------------------------------ overriding function Get_Name (From : in URL_Policy) return String is pragma Unreferenced (From); begin return NAME; end Get_Name; -- ------------------------------ -- Returns True if the user has the permission to access the given URI permission. -- ------------------------------ function Has_Permission (Manager : in URL_Policy; Context : in Contexts.Security_Context'Class; Permission : in URL_Permission'Class) return Boolean is Name : constant String_Ref := To_String_Ref (Permission.URL); Ref : constant Rules_Ref.Ref := Manager.Cache.Get; Rules : constant Rules_Access := Ref.Value; Pos : constant Rules_Maps.Cursor := Rules.Map.Find (Name); Rule : Access_Rule_Ref; begin -- If the rule is not in the cache, search for the access rule that -- matches our URI. Update the cache. This cache update is thread-safe -- as the cache map is never modified: a new cache map is installed. if not Rules_Maps.Has_Element (Pos) then declare New_Ref : constant Rules_Ref.Ref := Rules_Ref.Create; begin Rule := Manager.Find_Access_Rule (Permission.URL); New_Ref.Value.all.Map := Rules.Map; New_Ref.Value.all.Map.Insert (Name, Rule); Manager.Cache.Set (New_Ref); end; else Rule := Rules_Maps.Element (Pos); end if; -- Check if the user has one of the required permission. declare P : constant Access_Rule_Access := Rule.Value; Granted : Boolean; begin if P /= null then for I in P.Permissions'Range loop Context.Has_Permission (P.Permissions (I), Granted); if Granted then return True; end if; end loop; end if; end; return False; end Has_Permission; -- Grant the permission to access to the given <b>URI</b> to users having the <b>To</b> -- permissions. procedure Grant_URI_Permission (Manager : in out URL_Policy; URI : in String; To : in String) is begin null; end Grant_URI_Permission; -- ------------------------------ -- Policy Configuration -- ------------------------------ -- ------------------------------ -- Find the access rule of the policy that matches the given URI. -- Returns the No_Rule value (disable access) if no rule is found. -- ------------------------------ function Find_Access_Rule (Manager : in URL_Policy; URI : in String) return Access_Rule_Ref is Matched : Boolean := False; Result : Access_Rule_Ref; procedure Match (P : in Policy); procedure Match (P : in Policy) is begin if GNAT.Regexp.Match (URI, P.Pattern) then Matched := True; Result := P.Rule; end if; end Match; Last : constant Natural := Manager.Policies.Last_Index; begin for I in 1 .. Last loop Manager.Policies.Query_Element (I, Match'Access); if Matched then return Result; end if; end loop; return Result; end Find_Access_Rule; -- ------------------------------ -- Initialize the permission manager. -- ------------------------------ overriding procedure Initialize (Manager : in out URL_Policy) is begin Manager.Cache := new Rules_Ref.Atomic_Ref; Manager.Cache.Set (Rules_Ref.Create); end Initialize; -- ------------------------------ -- Finalize the permission manager. -- ------------------------------ overriding procedure Finalize (Manager : in out URL_Policy) is procedure Free is new Ada.Unchecked_Deallocation (Rules_Ref.Atomic_Ref, Rules_Ref_Access); begin Free (Manager.Cache); -- for I in Manager.Names'Range loop -- exit when Manager.Names (I) = null; -- Ada.Strings.Unbounded.Free (Manager.Names (I)); -- end loop; end Finalize; type Policy_Fields is (FIELD_ID, FIELD_PERMISSION, FIELD_URL_PATTERN, FIELD_POLICY); procedure Set_Member (P : in out URL_Policy'Class; Field : in Policy_Fields; Value : in Util.Beans.Objects.Object); procedure Process (Policy : in out URL_Policy'Class); procedure Set_Member (P : in out URL_Policy'Class; Field : in Policy_Fields; Value : in Util.Beans.Objects.Object) is begin case Field is when FIELD_ID => P.Id := Util.Beans.Objects.To_Integer (Value); when FIELD_PERMISSION => P.Permissions.Append (Value); when FIELD_URL_PATTERN => P.Patterns.Append (Value); when FIELD_POLICY => Process (P); P.Id := 0; P.Permissions.Clear; P.Patterns.Clear; end case; end Set_Member; procedure Process (Policy : in out URL_Policy'Class) is Pol : Security.Policies.URLs.Policy; Count : constant Natural := Natural (Policy.Permissions.Length); Rule : constant Access_Rule_Ref := Access_Rule_Refs.Create (new Access_Rule (Count)); Iter : Util.Beans.Objects.Vectors.Cursor := Policy.Permissions.First; Pos : Positive := 1; begin Pol.Rule := Rule; -- Step 1: Initialize the list of permission index in Access_Rule from the permission names. while Util.Beans.Objects.Vectors.Has_Element (Iter) loop declare Perm : constant Util.Beans.Objects.Object := Util.Beans.Objects.Vectors.Element (Iter); Name : constant String := Util.Beans.Objects.To_String (Perm); begin Rule.Value.all.Permissions (Pos) := Permissions.Get_Permission_Index (Name); Pos := Pos + 1; exception when Invalid_Name => raise Util.Serialize.Mappers.Field_Error with "Invalid permission: " & Name; end; Util.Beans.Objects.Vectors.Next (Iter); end loop; -- Step 2: Create one policy for each URL pattern Iter := Policy.Patterns.First; while Util.Beans.Objects.Vectors.Has_Element (Iter) loop declare Pattern : constant Util.Beans.Objects.Object := Util.Beans.Objects.Vectors.Element (Iter); begin Pol.Id := Policy.Id; Pol.Pattern := GNAT.Regexp.Compile (Util.Beans.Objects.To_String (Pattern)); Policy.Policies.Append (Pol); end; Util.Beans.Objects.Vectors.Next (Iter); end loop; end Process; package Policy_Mapper is new Util.Serialize.Mappers.Record_Mapper (Element_Type => URL_Policy'Class, Element_Type_Access => URL_Policy_Access, Fields => Policy_Fields, Set_Member => Set_Member); Policy_Mapping : aliased Policy_Mapper.Mapper; -- ------------------------------ -- Setup the XML parser to read the <b>policy</b> description. -- ------------------------------ overriding procedure Prepare_Config (Policy : in out URL_Policy; Reader : in out Util.Serialize.IO.XML.Parser) is Perm : constant Security.Controllers.URLs.URL_Controller_Access := new Security.Controllers.URLs.URL_Controller; begin Perm.Manager := Policy'Unchecked_Access; Reader.Add_Mapping ("policy-rules", Policy_Mapping'Access); Reader.Add_Mapping ("module", Policy_Mapping'Access); Policy_Mapper.Set_Context (Reader, Perm.Manager); Policy.Manager.Add_Permission (Name => "url", Permission => Perm.all'Access); end Prepare_Config; -- ------------------------------ -- Get the URL policy associated with the given policy manager. -- Returns the URL policy instance or null if it was not registered in the policy manager. -- ------------------------------ function Get_URL_Policy (Manager : in Security.Policies.Policy_Manager'Class) return URL_Policy_Access is Policy : constant Security.Policies.Policy_Access := Manager.Get_Policy (NAME); begin if Policy = null or else not (Policy.all in URL_Policy'Class) then return null; else return URL_Policy'Class (Policy.all)'Access; end if; end Get_URL_Policy; begin Policy_Mapping.Add_Mapping ("url-policy", FIELD_POLICY); Policy_Mapping.Add_Mapping ("url-policy/@id", FIELD_ID); Policy_Mapping.Add_Mapping ("url-policy/permission", FIELD_PERMISSION); Policy_Mapping.Add_Mapping ("url-policy/url-pattern", FIELD_URL_PATTERN); end Security.Policies.URLs;
----------------------------------------------------------------------- -- security-policies-urls -- URL security policy -- Copyright (C) 2010, 2011, 2012 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Unchecked_Deallocation; with Util.Beans.Objects; with Util.Beans.Objects.Vectors; with Util.Serialize.Mappers; with Util.Serialize.Mappers.Record_Mapper; with Security.Controllers.URLs; package body Security.Policies.URLs is -- ------------------------------ -- Get the policy name. -- ------------------------------ overriding function Get_Name (From : in URL_Policy) return String is pragma Unreferenced (From); begin return NAME; end Get_Name; -- ------------------------------ -- Returns True if the user has the permission to access the given URI permission. -- ------------------------------ function Has_Permission (Manager : in URL_Policy; Context : in Contexts.Security_Context'Class; Permission : in URL_Permission'Class) return Boolean is Name : constant String_Ref := To_String_Ref (Permission.URL); Ref : constant Rules_Ref.Ref := Manager.Cache.Get; Rules : constant Rules_Access := Ref.Value; Pos : constant Rules_Maps.Cursor := Rules.Map.Find (Name); Rule : Access_Rule_Ref; begin -- If the rule is not in the cache, search for the access rule that -- matches our URI. Update the cache. This cache update is thread-safe -- as the cache map is never modified: a new cache map is installed. if not Rules_Maps.Has_Element (Pos) then declare New_Ref : constant Rules_Ref.Ref := Rules_Ref.Create; begin Rule := Manager.Find_Access_Rule (Permission.URL); New_Ref.Value.all.Map := Rules.Map; New_Ref.Value.all.Map.Insert (Name, Rule); Manager.Cache.Set (New_Ref); end; else Rule := Rules_Maps.Element (Pos); end if; -- Check if the user has one of the required permission. declare P : constant Access_Rule_Access := Rule.Value; begin if P /= null then for I in P.Permissions'Range loop if Context.Has_Permission (P.Permissions (I)) then return True; end if; end loop; end if; end; return False; end Has_Permission; -- Grant the permission to access to the given <b>URI</b> to users having the <b>To</b> -- permissions. procedure Grant_URI_Permission (Manager : in out URL_Policy; URI : in String; To : in String) is begin null; end Grant_URI_Permission; -- ------------------------------ -- Policy Configuration -- ------------------------------ -- ------------------------------ -- Find the access rule of the policy that matches the given URI. -- Returns the No_Rule value (disable access) if no rule is found. -- ------------------------------ function Find_Access_Rule (Manager : in URL_Policy; URI : in String) return Access_Rule_Ref is Matched : Boolean := False; Result : Access_Rule_Ref; procedure Match (P : in Policy); procedure Match (P : in Policy) is begin if GNAT.Regexp.Match (URI, P.Pattern) then Matched := True; Result := P.Rule; end if; end Match; Last : constant Natural := Manager.Policies.Last_Index; begin for I in 1 .. Last loop Manager.Policies.Query_Element (I, Match'Access); if Matched then return Result; end if; end loop; return Result; end Find_Access_Rule; -- ------------------------------ -- Initialize the permission manager. -- ------------------------------ overriding procedure Initialize (Manager : in out URL_Policy) is begin Manager.Cache := new Rules_Ref.Atomic_Ref; Manager.Cache.Set (Rules_Ref.Create); end Initialize; -- ------------------------------ -- Finalize the permission manager. -- ------------------------------ overriding procedure Finalize (Manager : in out URL_Policy) is procedure Free is new Ada.Unchecked_Deallocation (Rules_Ref.Atomic_Ref, Rules_Ref_Access); begin Free (Manager.Cache); -- for I in Manager.Names'Range loop -- exit when Manager.Names (I) = null; -- Ada.Strings.Unbounded.Free (Manager.Names (I)); -- end loop; end Finalize; type Policy_Fields is (FIELD_ID, FIELD_PERMISSION, FIELD_URL_PATTERN, FIELD_POLICY); procedure Set_Member (P : in out URL_Policy'Class; Field : in Policy_Fields; Value : in Util.Beans.Objects.Object); procedure Process (Policy : in out URL_Policy'Class); procedure Set_Member (P : in out URL_Policy'Class; Field : in Policy_Fields; Value : in Util.Beans.Objects.Object) is begin case Field is when FIELD_ID => P.Id := Util.Beans.Objects.To_Integer (Value); when FIELD_PERMISSION => P.Permissions.Append (Value); when FIELD_URL_PATTERN => P.Patterns.Append (Value); when FIELD_POLICY => Process (P); P.Id := 0; P.Permissions.Clear; P.Patterns.Clear; end case; end Set_Member; procedure Process (Policy : in out URL_Policy'Class) is Pol : Security.Policies.URLs.Policy; Count : constant Natural := Natural (Policy.Permissions.Length); Rule : constant Access_Rule_Ref := Access_Rule_Refs.Create (new Access_Rule (Count)); Iter : Util.Beans.Objects.Vectors.Cursor := Policy.Permissions.First; Pos : Positive := 1; begin Pol.Rule := Rule; -- Step 1: Initialize the list of permission index in Access_Rule from the permission names. while Util.Beans.Objects.Vectors.Has_Element (Iter) loop declare Perm : constant Util.Beans.Objects.Object := Util.Beans.Objects.Vectors.Element (Iter); Name : constant String := Util.Beans.Objects.To_String (Perm); begin Rule.Value.all.Permissions (Pos) := Permissions.Get_Permission_Index (Name); Pos := Pos + 1; exception when Invalid_Name => raise Util.Serialize.Mappers.Field_Error with "Invalid permission: " & Name; end; Util.Beans.Objects.Vectors.Next (Iter); end loop; -- Step 2: Create one policy for each URL pattern Iter := Policy.Patterns.First; while Util.Beans.Objects.Vectors.Has_Element (Iter) loop declare Pattern : constant Util.Beans.Objects.Object := Util.Beans.Objects.Vectors.Element (Iter); begin Pol.Id := Policy.Id; Pol.Pattern := GNAT.Regexp.Compile (Util.Beans.Objects.To_String (Pattern)); Policy.Policies.Append (Pol); end; Util.Beans.Objects.Vectors.Next (Iter); end loop; end Process; package Policy_Mapper is new Util.Serialize.Mappers.Record_Mapper (Element_Type => URL_Policy'Class, Element_Type_Access => URL_Policy_Access, Fields => Policy_Fields, Set_Member => Set_Member); Policy_Mapping : aliased Policy_Mapper.Mapper; -- ------------------------------ -- Setup the XML parser to read the <b>policy</b> description. -- ------------------------------ overriding procedure Prepare_Config (Policy : in out URL_Policy; Reader : in out Util.Serialize.IO.XML.Parser) is Perm : constant Security.Controllers.URLs.URL_Controller_Access := new Security.Controllers.URLs.URL_Controller; begin Perm.Manager := Policy'Unchecked_Access; Reader.Add_Mapping ("policy-rules", Policy_Mapping'Access); Reader.Add_Mapping ("module", Policy_Mapping'Access); Policy_Mapper.Set_Context (Reader, Perm.Manager); Policy.Manager.Add_Permission (Name => "url", Permission => Perm.all'Access); end Prepare_Config; -- ------------------------------ -- Get the URL policy associated with the given policy manager. -- Returns the URL policy instance or null if it was not registered in the policy manager. -- ------------------------------ function Get_URL_Policy (Manager : in Security.Policies.Policy_Manager'Class) return URL_Policy_Access is Policy : constant Security.Policies.Policy_Access := Manager.Get_Policy (NAME); begin if Policy = null or else not (Policy.all in URL_Policy'Class) then return null; else return URL_Policy'Class (Policy.all)'Access; end if; end Get_URL_Policy; begin Policy_Mapping.Add_Mapping ("url-policy", FIELD_POLICY); Policy_Mapping.Add_Mapping ("url-policy/@id", FIELD_ID); Policy_Mapping.Add_Mapping ("url-policy/permission", FIELD_PERMISSION); Policy_Mapping.Add_Mapping ("url-policy/url-pattern", FIELD_URL_PATTERN); end Security.Policies.URLs;
Update to use the Has_Permission function
Update to use the Has_Permission function
Ada
apache-2.0
stcarrez/ada-security
95d053422363d891b4dd1c30054357adc27b01e7
src/security-policies-urls.ads
src/security-policies-urls.ads
----------------------------------------------------------------------- -- security-policies-urls -- URL security policy -- Copyright (C) 2010, 2011, 2012 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Containers.Hashed_Maps; with Ada.Containers.Vectors; with Util.Refs; with Util.Strings; with Util.Serialize.IO.XML; with GNAT.Regexp; -- == URL Security Policy == -- The <tt>Security.Policies.Urls</tt> implements a security policy intended to be used -- in web servers. -- -- === Policy creation === -- An instance of the <tt>URL_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.Urls.URL_Policy_Access; -- -- Create the URL policy and register it in the policy manager as follows: -- -- Policy := new URL_Policy; -- Manager.Add_Policy (Policy.all'Access); -- -- === Policy Configuration === -- Once the URL policy is registered, the policy manager can read and process the following -- XML configuration: -- -- <url-policy id='1'> -- <permission>create-workspace</permission> -- <permission>admin</permission> -- <url-pattern>/workspace/create</url-pattern> -- <url-pattern>/workspace/setup/*</url-pattern> -- </url-policy> -- -- This policy gives access to the URL that match one of the URL pattern if the -- security context has the permission <b>create-workspace</b> or <b>admin</b>. -- These two permissions are checked according to another security policy. -- The XML configuration can define several <tt>url-policy</tt>. They are checked in -- the order defined in the XML. In other words, the first <tt>url-policy</tt> that matches -- the URL is used to verify the permission. -- -- The <tt>url-policy</tt> definition can contain several <tt>permission</tt>. -- -- === Checking for permission === -- package Security.Policies.Urls is NAME : constant String := "URL-Policy"; -- ------------------------------ -- URI Permission -- ------------------------------ -- Represents a permission to access a given URI. type URI_Permission (Id : Permissions.Permission_Index; Len : Natural) is new Permissions.Permission (Id) with record URI : String (1 .. Len); end record; -- ------------------------------ -- URL policy -- ------------------------------ type URL_Policy is new Policy with private; type URL_Policy_Access is access all URL_Policy'Class; Invalid_Name : exception; -- Get the policy name. overriding function Get_Name (From : in URL_Policy) return String; -- Returns True if the user has the permission to access the given URI permission. function Has_Permission (Manager : in URL_Policy; Context : in Security_Context_Access; Permission : in URI_Permission'Class) return Boolean; -- Grant the permission to access to the given <b>URI</b> to users having the <b>To</b> -- permissions. procedure Grant_URI_Permission (Manager : in out URL_Policy; URI : in String; To : in String); -- Initialize the permission manager. overriding procedure Initialize (Manager : in out URL_Policy); -- Finalize the permission manager. overriding procedure Finalize (Manager : in out URL_Policy); -- Setup the XML parser to read the <b>policy</b> description. overriding procedure Prepare_Config (Policy : in out URL_Policy; Reader : in out Util.Serialize.IO.XML.Parser); -- Finish reading the XML policy configuration. The security policy implementation can use -- this procedure to perform any configuration setup after the configuration is parsed. overriding procedure Finish_Config (Into : in out URL_Policy; Reader : in out Util.Serialize.IO.XML.Parser); private use Util.Strings; -- The <b>Access_Rule</b> represents a list of permissions to verify to grant -- access to the resource. To make it simple, the user must have one of the -- permission from the list. Each permission will refer to a specific permission -- controller. type Access_Rule (Count : Natural) is new Util.Refs.Ref_Entity with record Permissions : Permission_Index_Array (1 .. Count); end record; type Access_Rule_Access is access all Access_Rule; package Access_Rule_Refs is new Util.Refs.Indefinite_References (Element_Type => Access_Rule, Element_Access => Access_Rule_Access); subtype Access_Rule_Ref is Access_Rule_Refs.Ref; -- Find the access rule of the policy that matches the given URI. -- Returns the No_Rule value (disable access) if no rule is found. function Find_Access_Rule (Manager : in URL_Policy; URI : in String) return Access_Rule_Ref; -- The <b>Policy</b> defines the access rules that are applied on a given -- URL, set of URLs or files. type Policy is record Id : Natural; Pattern : GNAT.Regexp.Regexp; Rule : Access_Rule_Ref; end record; -- The <b>Policy_Vector</b> represents the whole permission policy. The order of -- policy in the list is important as policies can override each other. package Policy_Vector is new Ada.Containers.Vectors (Index_Type => Positive, Element_Type => Policy); package Rules_Maps is new Ada.Containers.Hashed_Maps (Key_Type => String_Ref, Element_Type => Access_Rule_Ref, Hash => Hash, Equivalent_Keys => Equivalent_Keys, "=" => Access_Rule_Refs."="); type Rules is new Util.Refs.Ref_Entity with record Map : Rules_Maps.Map; end record; type Rules_Access is access all Rules; package Rules_Ref is new Util.Refs.References (Rules, Rules_Access); type Rules_Ref_Access is access Rules_Ref.Atomic_Ref; type Controller_Access_Array_Access is access all Controller_Access_Array; type URL_Policy is new Security.Policies.Policy with record Cache : Rules_Ref_Access; Policies : Policy_Vector.Vector; end record; end Security.Policies.Urls;
----------------------------------------------------------------------- -- security-policies-urls -- URL security policy -- Copyright (C) 2010, 2011, 2012 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Containers.Hashed_Maps; with Ada.Containers.Vectors; with Util.Refs; with Util.Strings; with Util.Serialize.IO.XML; with GNAT.Regexp; -- == URL Security Policy == -- The <tt>Security.Policies.Urls</tt> implements a security policy intended to be used -- in web servers. -- -- === Policy creation === -- An instance of the <tt>URL_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.Urls.URL_Policy_Access; -- -- Create the URL policy and register it in the policy manager as follows: -- -- Policy := new URL_Policy; -- Manager.Add_Policy (Policy.all'Access); -- -- === Policy Configuration === -- Once the URL policy is registered, the policy manager can read and process the following -- XML configuration: -- -- <url-policy id='1'> -- <permission>create-workspace</permission> -- <permission>admin</permission> -- <url-pattern>/workspace/create</url-pattern> -- <url-pattern>/workspace/setup/*</url-pattern> -- </url-policy> -- -- This policy gives access to the URL that match one of the URL pattern if the -- security context has the permission <b>create-workspace</b> or <b>admin</b>. -- These two permissions are checked according to another security policy. -- The XML configuration can define several <tt>url-policy</tt>. They are checked in -- the order defined in the XML. In other words, the first <tt>url-policy</tt> that matches -- the URL is used to verify the permission. -- -- The <tt>url-policy</tt> definition can contain several <tt>permission</tt>. -- -- === Checking for permission === -- To check a URL permission, you must declare a <tt>URI_Permission</tt> object with the URL. -- -- URI : constant String := ...; -- Perm : constant Policies.URLs.URI_Permission (1, URI'Length) -- := URI_Permission '(1, Len => URI'Length, URI => URI); -- Result : Boolean; -- -- Having the security context, we can check the permission: -- -- Context.Has_Permission (Perm, Result); -- package Security.Policies.Urls is NAME : constant String := "URL-Policy"; -- ------------------------------ -- URI Permission -- ------------------------------ -- Represents a permission to access a given URI. type URI_Permission (Id : Permissions.Permission_Index; Len : Natural) is new Permissions.Permission (Id) with record URI : String (1 .. Len); end record; -- ------------------------------ -- URL policy -- ------------------------------ type URL_Policy is new Policy with private; type URL_Policy_Access is access all URL_Policy'Class; Invalid_Name : exception; -- Get the policy name. overriding function Get_Name (From : in URL_Policy) return String; -- Returns True if the user has the permission to access the given URI permission. function Has_Permission (Manager : in URL_Policy; Context : in Security_Context_Access; Permission : in URI_Permission'Class) return Boolean; -- Grant the permission to access to the given <b>URI</b> to users having the <b>To</b> -- permissions. procedure Grant_URI_Permission (Manager : in out URL_Policy; URI : in String; To : in String); -- Initialize the permission manager. overriding procedure Initialize (Manager : in out URL_Policy); -- Finalize the permission manager. overriding procedure Finalize (Manager : in out URL_Policy); -- Setup the XML parser to read the <b>policy</b> description. overriding procedure Prepare_Config (Policy : in out URL_Policy; Reader : in out Util.Serialize.IO.XML.Parser); -- Finish reading the XML policy configuration. The security policy implementation can use -- this procedure to perform any configuration setup after the configuration is parsed. overriding procedure Finish_Config (Into : in out URL_Policy; Reader : in out Util.Serialize.IO.XML.Parser); private use Util.Strings; -- The <b>Access_Rule</b> represents a list of permissions to verify to grant -- access to the resource. To make it simple, the user must have one of the -- permission from the list. Each permission will refer to a specific permission -- controller. type Access_Rule (Count : Natural) is new Util.Refs.Ref_Entity with record Permissions : Permission_Index_Array (1 .. Count); end record; type Access_Rule_Access is access all Access_Rule; package Access_Rule_Refs is new Util.Refs.Indefinite_References (Element_Type => Access_Rule, Element_Access => Access_Rule_Access); subtype Access_Rule_Ref is Access_Rule_Refs.Ref; -- Find the access rule of the policy that matches the given URI. -- Returns the No_Rule value (disable access) if no rule is found. function Find_Access_Rule (Manager : in URL_Policy; URI : in String) return Access_Rule_Ref; -- The <b>Policy</b> defines the access rules that are applied on a given -- URL, set of URLs or files. type Policy is record Id : Natural; Pattern : GNAT.Regexp.Regexp; Rule : Access_Rule_Ref; end record; -- The <b>Policy_Vector</b> represents the whole permission policy. The order of -- policy in the list is important as policies can override each other. package Policy_Vector is new Ada.Containers.Vectors (Index_Type => Positive, Element_Type => Policy); package Rules_Maps is new Ada.Containers.Hashed_Maps (Key_Type => String_Ref, Element_Type => Access_Rule_Ref, Hash => Hash, Equivalent_Keys => Equivalent_Keys, "=" => Access_Rule_Refs."="); type Rules is new Util.Refs.Ref_Entity with record Map : Rules_Maps.Map; end record; type Rules_Access is access all Rules; package Rules_Ref is new Util.Refs.References (Rules, Rules_Access); type Rules_Ref_Access is access Rules_Ref.Atomic_Ref; type Controller_Access_Array_Access is access all Controller_Access_Array; type URL_Policy is new Security.Policies.Policy with record Cache : Rules_Ref_Access; Policies : Policy_Vector.Vector; end record; end Security.Policies.Urls;
Update the documentation
Update the documentation
Ada
apache-2.0
Letractively/ada-security
505e374c10760ee562ed5e43f8bd602129d168a0
awa/plugins/awa-storages/src/awa-storages-beans.adb
awa/plugins/awa-storages/src/awa-storages-beans.adb
----------------------------------------------------------------------- -- awa-storages-beans -- Storage Ada Beans -- Copyright (C) 2012, 2013, 2016 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Containers; with ADO; with ADO.Utils; with ADO.Queries; with ADO.Sessions; with ADO.Objects; with ADO.Sessions.Entities; with AWA.Workspaces.Models; with AWA.Services.Contexts; with AWA.Storages.Services; package body AWA.Storages.Beans is -- ------------------------------ -- Get the value identified by the name. -- ------------------------------ overriding function Get_Value (From : in Upload_Bean; Name : in String) return Util.Beans.Objects.Object is begin if Name = "folderId" then return ADO.Utils.To_Object (From.Folder_Id); elsif From.Is_Null then return Util.Beans.Objects.Null_Object; else return AWA.Storages.Models.Storage_Ref (From).Get_Value (Name); end if; end Get_Value; -- ------------------------------ -- Set the value identified by the name. -- ------------------------------ overriding procedure Set_Value (From : in out Upload_Bean; Name : in String; Value : in Util.Beans.Objects.Object) is Manager : constant Services.Storage_Service_Access := From.Module.Get_Storage_Manager; Folder : Models.Storage_Folder_Ref; Found : Boolean; begin if Name = "folderId" then From.Folder_Id := ADO.Utils.To_Identifier (Value); Manager.Load_Folder (Folder, From.Folder_Id); From.Set_Folder (Folder); elsif Name = "id" then Manager.Load_Storage (From, ADO.Utils.To_Identifier (Value)); elsif Name = "name" then Folder := Models.Storage_Folder_Ref (From.Get_Folder); Manager.Load_Storage (From, From.Folder_Id, Util.Beans.Objects.To_String (Value), Found); if not Found then From.Set_Name (Util.Beans.Objects.To_String (Value)); end if; From.Set_Folder (Folder); end if; end Set_Value; -- ------------------------------ -- Save the uploaded file in the storage service. -- ------------------------------ procedure Save_Part (Bean : in out Upload_Bean; Part : in ASF.Parts.Part'Class) is Manager : constant Services.Storage_Service_Access := Bean.Module.Get_Storage_Manager; Name : constant String := Bean.Get_Name; begin if Name'Length = 0 then Bean.Set_Name (Part.Get_Name); end if; Bean.Set_Mime_Type (Part.Get_Content_Type); Bean.Set_File_Size (Part.Get_Size); Manager.Save (Bean, Part, AWA.Storages.Models.DATABASE); end Save_Part; -- ------------------------------ -- Upload the file. -- ------------------------------ procedure Upload (Bean : in out Upload_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is pragma Unreferenced (Bean); begin Outcome := Ada.Strings.Unbounded.To_Unbounded_String ("success"); end Upload; -- ------------------------------ -- Delete the file. -- @method -- ------------------------------ procedure Delete (Bean : in out Upload_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is Manager : constant Services.Storage_Service_Access := Bean.Module.Get_Storage_Manager; begin Manager.Delete (Bean); Outcome := Ada.Strings.Unbounded.To_Unbounded_String ("success"); end Delete; -- ------------------------------ -- Get the value identified by the name. -- ------------------------------ overriding function Get_Value (From : in Folder_Bean; Name : in String) return Util.Beans.Objects.Object is begin if ADO.Objects.Is_Null (From) then return Util.Beans.Objects.Null_Object; else return AWA.Storages.Models.Storage_Folder_Ref (From).Get_Value (Name); end if; end Get_Value; -- ------------------------------ -- Set the value identified by the name. -- ------------------------------ overriding procedure Set_Value (From : in out Folder_Bean; Name : in String; Value : in Util.Beans.Objects.Object) is begin if Name = "name" then From.Set_Name (Util.Beans.Objects.To_String (Value)); end if; end Set_Value; -- ------------------------------ -- Create or save the folder. -- ------------------------------ procedure Save (Bean : in out Folder_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is Manager : constant Services.Storage_Service_Access := Bean.Module.Get_Storage_Manager; begin Manager.Save_Folder (Bean); Outcome := Ada.Strings.Unbounded.To_Unbounded_String ("success"); end Save; -- ------------------------------ -- Load the folder instance. -- ------------------------------ procedure Load_Folder (Storage : in Storage_List_Bean) is use AWA.Storages.Models; use AWA.Services; use type Ada.Containers.Count_Type; Manager : constant Services.Storage_Service_Access := Storage.Module.Get_Storage_Manager; begin Load_Folders (Storage); if Storage.Folder_List.List.Length > 0 then Manager.Load_Folder (Storage.Folder_Bean.all, Storage.Folder_List.List.Element (0).Id); end if; Storage.Flags (INIT_FOLDER) := True; end Load_Folder; -- ------------------------------ -- Load the list of folders. -- ------------------------------ procedure Load_Folders (Storage : in Storage_List_Bean) is use AWA.Storages.Models; use AWA.Services; use type ADO.Identifier; Ctx : constant Contexts.Service_Context_Access := AWA.Services.Contexts.Current; User : constant ADO.Identifier := Ctx.Get_User_Identifier; Session : ADO.Sessions.Session := Storage.Module.Get_Session; Query : ADO.Queries.Context; begin Query.Set_Query (AWA.Storages.Models.Query_Storage_Folder_List); Query.Bind_Param ("user_id", User); ADO.Sessions.Entities.Bind_Param (Query, "table", AWA.Workspaces.Models.WORKSPACE_TABLE, Session); AWA.Storages.Models.List (Storage.Folder_List_Bean.all, Session, Query); Storage.Flags (INIT_FOLDER_LIST) := True; end Load_Folders; -- ------------------------------ -- Load the list of files associated with the current folder. -- ------------------------------ procedure Load_Files (Storage : in Storage_List_Bean) is use AWA.Storages.Models; use AWA.Services; Ctx : constant Contexts.Service_Context_Access := AWA.Services.Contexts.Current; User : constant ADO.Identifier := Ctx.Get_User_Identifier; Session : ADO.Sessions.Session := Storage.Module.Get_Session; Query : ADO.Queries.Context; begin if not Storage.Init_Flags (INIT_FOLDER) then Load_Folder (Storage); end if; Query.Set_Query (AWA.Storages.Models.Query_Storage_List); Query.Bind_Param ("user_id", User); ADO.Sessions.Entities.Bind_Param (Query, "table", AWA.Workspaces.Models.WORKSPACE_TABLE, Session); if Storage.Folder_Bean.Is_Null then Query.Bind_Null_Param ("folder_id"); else Query.Bind_Param ("folder_id", Storage.Folder_Bean.Get_Id); end if; AWA.Storages.Models.List (Storage.Files_List_Bean.all, Session, Query); Storage.Flags (INIT_FILE_LIST) := True; end Load_Files; -- ------------------------------ -- Set the value identified by the name. -- ------------------------------ overriding procedure Set_Value (From : in out Storage_List_Bean; Name : in String; Value : in Util.Beans.Objects.Object) is Manager : constant Services.Storage_Service_Access := From.Module.Get_Storage_Manager; begin if Name = "folderId" and not Util.Beans.Objects.Is_Empty (Value) then Manager.Load_Folder (From.Folder, ADO.Identifier (Util.Beans.Objects.To_Integer (Value))); From.Flags (INIT_FOLDER) := True; end if; end Set_Value; overriding function Get_Value (List : in Storage_List_Bean; Name : in String) return Util.Beans.Objects.Object is begin if Name = "files" then if not List.Init_Flags (INIT_FILE_LIST) then Load_Files (List); end if; return Util.Beans.Objects.To_Object (Value => List.Files_List_Bean, Storage => Util.Beans.Objects.STATIC); elsif Name = "folders" then if not List.Init_Flags (INIT_FOLDER_LIST) then Load_Folders (List); end if; return Util.Beans.Objects.To_Object (Value => List.Folder_List_Bean, Storage => Util.Beans.Objects.STATIC); elsif Name = "folder" then if not List.Init_Flags (INIT_FOLDER) then Load_Folder (List); end if; if List.Folder_Bean.Is_Null then return Util.Beans.Objects.Null_Object; end if; return Util.Beans.Objects.To_Object (Value => List.Folder_Bean, Storage => Util.Beans.Objects.STATIC); else return Util.Beans.Objects.Null_Object; end if; end Get_Value; -- ------------------------------ -- Create the Folder_List_Bean bean instance. -- ------------------------------ function Create_Folder_List_Bean (Module : in AWA.Storages.Modules.Storage_Module_Access) return Util.Beans.Basic.Readonly_Bean_Access is use AWA.Storages.Models; use AWA.Services; use type ADO.Identifier; Ctx : constant Contexts.Service_Context_Access := AWA.Services.Contexts.Current; User : constant ADO.Identifier := Ctx.Get_User_Identifier; Object : constant Folder_Info_List_Bean_Access := new Folder_Info_List_Bean; Session : ADO.Sessions.Session := Module.Get_Session; Query : ADO.Queries.Context; begin Query.Set_Query (AWA.Storages.Models.Query_Storage_Folder_List); Query.Bind_Param ("user_id", User); ADO.Sessions.Entities.Bind_Param (Query, "table", AWA.Workspaces.Models.WORKSPACE_TABLE, Session); AWA.Storages.Models.List (Object.all, Session, Query); return Object.all'Access; end Create_Folder_List_Bean; -- ------------------------------ -- Create the Storage_List_Bean bean instance. -- ------------------------------ function Create_Storage_List_Bean (Module : in AWA.Storages.Modules.Storage_Module_Access) return Util.Beans.Basic.Readonly_Bean_Access is Object : constant Storage_List_Bean_Access := new Storage_List_Bean; begin Object.Module := Module; Object.Folder_Bean := Object.Folder'Access; Object.Folder_List_Bean := Object.Folder_List'Access; Object.Files_List_Bean := Object.Files_List'Access; Object.Flags := Object.Init_Flags'Access; return Object.all'Access; end Create_Storage_List_Bean; end AWA.Storages.Beans;
----------------------------------------------------------------------- -- awa-storages-beans -- Storage Ada Beans -- Copyright (C) 2012, 2013, 2016 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Containers; with ADO; with ADO.Utils; with ADO.Queries; with ADO.Sessions; with ADO.Objects; with ADO.Sessions.Entities; with AWA.Helpers.Requests; with AWA.Workspaces.Models; with AWA.Services.Contexts; with AWA.Storages.Services; package body AWA.Storages.Beans is -- ------------------------------ -- Get the value identified by the name. -- ------------------------------ overriding function Get_Value (From : in Upload_Bean; Name : in String) return Util.Beans.Objects.Object is begin if Name = "folderId" then return ADO.Utils.To_Object (From.Folder_Id); elsif From.Is_Null then return Util.Beans.Objects.Null_Object; else return AWA.Storages.Models.Storage_Ref (From).Get_Value (Name); end if; end Get_Value; -- ------------------------------ -- Set the value identified by the name. -- ------------------------------ overriding procedure Set_Value (From : in out Upload_Bean; Name : in String; Value : in Util.Beans.Objects.Object) is Manager : constant Services.Storage_Service_Access := From.Module.Get_Storage_Manager; Folder : Models.Storage_Folder_Ref; Found : Boolean; begin if Name = "folderId" then From.Folder_Id := ADO.Utils.To_Identifier (Value); Manager.Load_Folder (Folder, From.Folder_Id); From.Set_Folder (Folder); elsif Name = "id" then Manager.Load_Storage (From, ADO.Utils.To_Identifier (Value)); elsif Name = "name" then Folder := Models.Storage_Folder_Ref (From.Get_Folder); Manager.Load_Storage (From, From.Folder_Id, Util.Beans.Objects.To_String (Value), Found); if not Found then From.Set_Name (Util.Beans.Objects.To_String (Value)); end if; From.Set_Folder (Folder); end if; end Set_Value; -- ------------------------------ -- Save the uploaded file in the storage service. -- ------------------------------ procedure Save_Part (Bean : in out Upload_Bean; Part : in ASF.Parts.Part'Class) is Manager : constant Services.Storage_Service_Access := Bean.Module.Get_Storage_Manager; Name : constant String := Bean.Get_Name; begin if Name'Length = 0 then Bean.Set_Name (Part.Get_Name); end if; Bean.Set_Mime_Type (Part.Get_Content_Type); Bean.Set_File_Size (Part.Get_Size); Manager.Save (Bean, Part, AWA.Storages.Models.DATABASE); end Save_Part; -- ------------------------------ -- Upload the file. -- ------------------------------ procedure Upload (Bean : in out Upload_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is pragma Unreferenced (Bean); begin Outcome := Ada.Strings.Unbounded.To_Unbounded_String ("success"); end Upload; -- ------------------------------ -- Delete the file. -- ------------------------------ procedure Delete (Bean : in out Upload_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is Manager : constant Services.Storage_Service_Access := Bean.Module.Get_Storage_Manager; begin Manager.Delete (Bean); Outcome := Ada.Strings.Unbounded.To_Unbounded_String ("success"); end Delete; -- ------------------------------ -- Publish the file. -- ------------------------------ overriding procedure Publish (Bean : in out Upload_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is Manager : constant Services.Storage_Service_Access := Bean.Module.Get_Storage_Manager; Id : constant ADO.Identifier := Helpers.Requests.Get_Parameter ("id"); Value : constant Util.Beans.Objects.Object := Helpers.Requests.Get_Parameter ("status"); begin Manager.Publish (Id, Util.Beans.Objects.To_Boolean (Value), Bean); Outcome := Ada.Strings.Unbounded.To_Unbounded_String ("success"); end Publish; -- ------------------------------ -- Create the Upload_Bean bean instance. -- ------------------------------ function Create_Upload_Bean (Module : in AWA.Storages.Modules.Storage_Module_Access) return Util.Beans.Basic.Readonly_Bean_Access is Result : constant Upload_Bean_Access := new Upload_Bean; begin Result.Module := Module; return Result.all'Access; end Create_Upload_Bean; -- ------------------------------ -- Get the value identified by the name. -- ------------------------------ overriding function Get_Value (From : in Folder_Bean; Name : in String) return Util.Beans.Objects.Object is begin if ADO.Objects.Is_Null (From) then return Util.Beans.Objects.Null_Object; else return AWA.Storages.Models.Storage_Folder_Ref (From).Get_Value (Name); end if; end Get_Value; -- ------------------------------ -- Set the value identified by the name. -- ------------------------------ overriding procedure Set_Value (From : in out Folder_Bean; Name : in String; Value : in Util.Beans.Objects.Object) is begin if Name = "name" then From.Set_Name (Util.Beans.Objects.To_String (Value)); end if; end Set_Value; -- ------------------------------ -- Create or save the folder. -- ------------------------------ procedure Save (Bean : in out Folder_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is Manager : constant Services.Storage_Service_Access := Bean.Module.Get_Storage_Manager; begin Manager.Save_Folder (Bean); Outcome := Ada.Strings.Unbounded.To_Unbounded_String ("success"); end Save; -- ------------------------------ -- Load the folder instance. -- ------------------------------ procedure Load_Folder (Storage : in Storage_List_Bean) is use AWA.Storages.Models; use AWA.Services; use type Ada.Containers.Count_Type; Manager : constant Services.Storage_Service_Access := Storage.Module.Get_Storage_Manager; begin Load_Folders (Storage); if Storage.Folder_List.List.Length > 0 then Manager.Load_Folder (Storage.Folder_Bean.all, Storage.Folder_List.List.Element (0).Id); end if; Storage.Flags (INIT_FOLDER) := True; end Load_Folder; -- ------------------------------ -- Load the list of folders. -- ------------------------------ procedure Load_Folders (Storage : in Storage_List_Bean) is use AWA.Storages.Models; use AWA.Services; use type ADO.Identifier; Ctx : constant Contexts.Service_Context_Access := AWA.Services.Contexts.Current; User : constant ADO.Identifier := Ctx.Get_User_Identifier; Session : ADO.Sessions.Session := Storage.Module.Get_Session; Query : ADO.Queries.Context; begin Query.Set_Query (AWA.Storages.Models.Query_Storage_Folder_List); Query.Bind_Param ("user_id", User); ADO.Sessions.Entities.Bind_Param (Query, "table", AWA.Workspaces.Models.WORKSPACE_TABLE, Session); AWA.Storages.Models.List (Storage.Folder_List_Bean.all, Session, Query); Storage.Flags (INIT_FOLDER_LIST) := True; end Load_Folders; -- ------------------------------ -- Load the list of files associated with the current folder. -- ------------------------------ procedure Load_Files (Storage : in Storage_List_Bean) is use AWA.Storages.Models; use AWA.Services; Ctx : constant Contexts.Service_Context_Access := AWA.Services.Contexts.Current; User : constant ADO.Identifier := Ctx.Get_User_Identifier; Session : ADO.Sessions.Session := Storage.Module.Get_Session; Query : ADO.Queries.Context; begin if not Storage.Init_Flags (INIT_FOLDER) then Load_Folder (Storage); end if; Query.Set_Query (AWA.Storages.Models.Query_Storage_List); Query.Bind_Param ("user_id", User); ADO.Sessions.Entities.Bind_Param (Query, "table", AWA.Workspaces.Models.WORKSPACE_TABLE, Session); if Storage.Folder_Bean.Is_Null then Query.Bind_Null_Param ("folder_id"); else Query.Bind_Param ("folder_id", Storage.Folder_Bean.Get_Id); end if; AWA.Storages.Models.List (Storage.Files_List_Bean.all, Session, Query); Storage.Flags (INIT_FILE_LIST) := True; end Load_Files; -- ------------------------------ -- Set the value identified by the name. -- ------------------------------ overriding procedure Set_Value (From : in out Storage_List_Bean; Name : in String; Value : in Util.Beans.Objects.Object) is Manager : constant Services.Storage_Service_Access := From.Module.Get_Storage_Manager; begin if Name = "folderId" and not Util.Beans.Objects.Is_Empty (Value) then Manager.Load_Folder (From.Folder, ADO.Identifier (Util.Beans.Objects.To_Integer (Value))); From.Flags (INIT_FOLDER) := True; end if; end Set_Value; overriding function Get_Value (List : in Storage_List_Bean; Name : in String) return Util.Beans.Objects.Object is begin if Name = "files" then if not List.Init_Flags (INIT_FILE_LIST) then Load_Files (List); end if; return Util.Beans.Objects.To_Object (Value => List.Files_List_Bean, Storage => Util.Beans.Objects.STATIC); elsif Name = "folders" then if not List.Init_Flags (INIT_FOLDER_LIST) then Load_Folders (List); end if; return Util.Beans.Objects.To_Object (Value => List.Folder_List_Bean, Storage => Util.Beans.Objects.STATIC); elsif Name = "folder" then if not List.Init_Flags (INIT_FOLDER) then Load_Folder (List); end if; if List.Folder_Bean.Is_Null then return Util.Beans.Objects.Null_Object; end if; return Util.Beans.Objects.To_Object (Value => List.Folder_Bean, Storage => Util.Beans.Objects.STATIC); else return Util.Beans.Objects.Null_Object; end if; end Get_Value; -- ------------------------------ -- Create the Folder_List_Bean bean instance. -- ------------------------------ function Create_Folder_List_Bean (Module : in AWA.Storages.Modules.Storage_Module_Access) return Util.Beans.Basic.Readonly_Bean_Access is use AWA.Storages.Models; use AWA.Services; use type ADO.Identifier; Ctx : constant Contexts.Service_Context_Access := AWA.Services.Contexts.Current; User : constant ADO.Identifier := Ctx.Get_User_Identifier; Object : constant Folder_Info_List_Bean_Access := new Folder_Info_List_Bean; Session : ADO.Sessions.Session := Module.Get_Session; Query : ADO.Queries.Context; begin Query.Set_Query (AWA.Storages.Models.Query_Storage_Folder_List); Query.Bind_Param ("user_id", User); ADO.Sessions.Entities.Bind_Param (Query, "table", AWA.Workspaces.Models.WORKSPACE_TABLE, Session); AWA.Storages.Models.List (Object.all, Session, Query); return Object.all'Access; end Create_Folder_List_Bean; -- ------------------------------ -- Create the Storage_List_Bean bean instance. -- ------------------------------ function Create_Storage_List_Bean (Module : in AWA.Storages.Modules.Storage_Module_Access) return Util.Beans.Basic.Readonly_Bean_Access is Object : constant Storage_List_Bean_Access := new Storage_List_Bean; begin Object.Module := Module; Object.Folder_Bean := Object.Folder'Access; Object.Folder_List_Bean := Object.Folder_List'Access; Object.Files_List_Bean := Object.Files_List'Access; Object.Flags := Object.Init_Flags'Access; return Object.all'Access; end Create_Storage_List_Bean; end AWA.Storages.Beans;
Implement the Publish and Create_Upload_Bean operations
Implement the Publish and Create_Upload_Bean operations
Ada
apache-2.0
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
af4a74b951db00933e0e1128341d97d17e20bb3f
samples/multipro.adb
samples/multipro.adb
----------------------------------------------------------------------- -- multipro -- Points out multiprocessor issues when incrementing counters -- Copyright (C) 2010, 2011 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Log; with Util.Log.Loggers; with Util.Concurrent.Counters; with Util.Measures; with Ada.Text_IO; procedure Multipro is use Util.Log; use Util.Concurrent.Counters; Log : constant Loggers.Logger := Loggers.Create ("multipro"); -- Target counter value we would like. Max_Counter : constant Integer := 1_000_000; -- Max number of tasks for executing the concurrent increment. Max_Tasks : constant Integer := 16; -- Performance measurement. Perf : Util.Measures.Measure_Set; T : Util.Measures.Stamp; begin for Task_Count in 1 .. Max_Tasks loop declare -- Each task will increment the counter by the following amount. Increment_By_Task : constant Integer := Max_Counter / Task_Count; -- Counter not protected for concurrency access. Unsafe : Integer := 0; -- Counter protected by concurrent accesses. Counter : Util.Concurrent.Counters.Counter; begin declare -- A task that increments the shared counter <b>Unsafe</b> and <b>Counter</b> by -- the specified amount. task type Worker is entry Start (Count : in Natural); end Worker; task body Worker is Cnt : Natural; begin accept Start (Count : in Natural) do Cnt := Count; end; -- Increment the two counters as many times as necessary. for I in 1 .. Cnt loop Util.Concurrent.Counters.Increment (Counter); Unsafe := Unsafe + 1; end loop; end Worker; type Worker_Array is array (1 .. Task_Count) of Worker; Tasks : Worker_Array; begin Log.Info ("Starting " & Integer'Image (Task_Count) & " tasks"); for I in Tasks'Range loop Tasks (I).Start (Increment_By_Task); end loop; -- Leaving the Worker task scope means we are waiting for our tasks to finish. end; Util.Measures.Report (Measures => Perf, S => T, Title => "Increment counter with " & Integer'Image (Task_Count) & " tasks"); -- Unsafe will be equal to Counter if Task_Count = 1 or if the host is mono-processor. -- On dual/quad core, the Unsafe value becomes random and gets lower each time -- the number of tasks increases. Log.Info ("Expected value at the end : " & Integer'Image (Increment_By_Task * Task_Count)); Log.Info ("Counter value at the end : " & Integer'Image (Value (Counter))); Log.Info ("Unprotected counter at the end : " & Integer'Image (Unsafe)); end; end loop; -- Dump the result Util.Measures.Write (Perf, "Multipro", Ada.Text_IO.Standard_Output); end Multipro;
----------------------------------------------------------------------- -- multipro -- Points out multiprocessor issues when incrementing counters -- Copyright (C) 2010, 2011 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Log; with Util.Log.Loggers; with Util.Concurrent.Counters; with Util.Measures; with Ada.Text_IO; procedure Multipro is use Util.Log; use Util.Concurrent.Counters; Log : constant Loggers.Logger := Loggers.Create ("multipro"); -- Target counter value we would like. Max_Counter : constant Integer := 10_000_000; -- Max number of tasks for executing the concurrent increment. Max_Tasks : constant Integer := 16; -- Performance measurement. Perf : Util.Measures.Measure_Set; T : Util.Measures.Stamp; begin for Task_Count in 1 .. Max_Tasks loop declare -- Each task will increment the counter by the following amount. Increment_By_Task : constant Integer := Max_Counter / Task_Count; -- Counter not protected for concurrency access. Unsafe : Integer := 0; -- Counter protected by concurrent accesses. Counter : Util.Concurrent.Counters.Counter; begin declare -- A task that increments the shared counter <b>Unsafe</b> and <b>Counter</b> by -- the specified amount. task type Worker is entry Start (Count : in Natural); end Worker; task body Worker is Cnt : Natural; begin accept Start (Count : in Natural) do Cnt := Count; end; -- Increment the two counters as many times as necessary. for I in 1 .. Cnt loop Util.Concurrent.Counters.Increment (Counter); Unsafe := Unsafe + 1; end loop; end Worker; type Worker_Array is array (1 .. Task_Count) of Worker; Tasks : Worker_Array; begin Log.Info ("Starting " & Integer'Image (Task_Count) & " tasks"); for I in Tasks'Range loop Tasks (I).Start (Increment_By_Task); end loop; -- Leaving the Worker task scope means we are waiting for our tasks to finish. end; Util.Measures.Report (Measures => Perf, S => T, Title => "Increment counter with " & Integer'Image (Task_Count) & " tasks"); -- Unsafe will be equal to Counter if Task_Count = 1 or if the host is mono-processor. -- On dual/quad core, the Unsafe value becomes random and gets lower each time -- the number of tasks increases. Log.Info ("Expected value at the end : " & Integer'Image (Increment_By_Task * Task_Count)); Log.Info ("Counter value at the end : " & Integer'Image (Value (Counter))); Log.Info ("Unprotected counter at the end : " & Integer'Image (Unsafe)); end; end loop; -- Dump the result Util.Measures.Write (Perf, "Multipro", Ada.Text_IO.Standard_Output); end Multipro;
Increase counter value
Increase counter value
Ada
apache-2.0
flottokarotto/ada-util,Letractively/ada-util,flottokarotto/ada-util,Letractively/ada-util
f5fed69ca1c599f09eb23def656ba27836ab5346
src/ado-sessions.adb
src/ado-sessions.adb
----------------------------------------------------------------------- -- ADO Sessions -- Sessions Management -- 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 Util.Log; with Util.Log.Loggers; with Ada.Unchecked_Deallocation; with ADO.Drivers; with ADO.Sequences; package body ADO.Sessions is Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("ADO.Sessions"); procedure Check_Session (Database : in Session'Class; Message : in String := "") is begin if Database.Impl = null then Log.Error ("Session is closed or not initialized"); raise NOT_OPEN; end if; if Message'Length > 0 then Log.Info (Message, Database.Impl.Database.Get_Ident); end if; end Check_Session; -- --------- -- Session -- --------- -- ------------------------------ -- Get the session status. -- ------------------------------ function Get_Status (Database : in Session) return ADO.Databases.Connection_Status is begin if Database.Impl = null then return ADO.Databases.CLOSED; end if; return Database.Impl.Database.Get_Status; end Get_Status; -- ------------------------------ -- Close the session. -- ------------------------------ procedure Close (Database : in out Session) is procedure Free is new Ada.Unchecked_Deallocation (Object => Session_Record, Name => Session_Record_Access); Is_Zero : Boolean; begin Log.Info ("Closing session"); if Database.Impl /= null then ADO.Objects.Release_Proxy (Database.Impl.Proxy); Database.Impl.Database.Close; Util.Concurrent.Counters.Decrement (Database.Impl.Counter, Is_Zero); if Is_Zero then Free (Database.Impl); end if; Database.Impl := null; end if; end Close; -- ------------------------------ -- Get the database connection. -- ------------------------------ function Get_Connection (Database : in Session) return ADO.Databases.Connection'Class is begin Check_Session (Database); return Database.Impl.Database; end Get_Connection; -- ------------------------------ -- Attach the object to the session. -- ------------------------------ procedure Attach (Database : in out Session; Object : in ADO.Objects.Object_Ref'Class) is pragma Unreferenced (Object); begin Check_Session (Database); end Attach; -- ------------------------------ -- Check if the session contains the object identified by the given key. -- ------------------------------ function Contains (Database : in Session; Item : in ADO.Objects.Object_Key) return Boolean is begin Check_Session (Database); return ADO.Objects.Cache.Contains (Database.Impl.Cache, Item); end Contains; -- ------------------------------ -- Remove the object from the session cache. -- ------------------------------ procedure Evict (Database : in out Session; Item : in ADO.Objects.Object_Key) is begin Check_Session (Database); ADO.Objects.Cache.Remove (Database.Impl.Cache, Item); end Evict; -- ------------------------------ -- Create a query statement. The statement is not prepared -- ------------------------------ function Create_Statement (Database : in Session; Table : in ADO.Schemas.Class_Mapping_Access) return Query_Statement is begin Check_Session (Database); return Database.Impl.Database.Create_Statement (Table); end Create_Statement; -- ------------------------------ -- Create a query statement. The statement is not prepared -- ------------------------------ function Create_Statement (Database : in Session; Query : in String) return Query_Statement is begin Check_Session (Database); return Database.Impl.Database.Create_Statement (Query); end Create_Statement; -- ------------------------------ -- Create a query statement. The statement is not prepared -- ------------------------------ function Create_Statement (Database : in Session; Query : in ADO.Queries.Context'Class) return Query_Statement is begin Check_Session (Database); declare SQL : constant String := Query.Get_SQL (Database.Impl.Database.Get_Driver_Index); Stmt : Query_Statement := Database.Impl.Database.Create_Statement (SQL); begin Stmt.Set_Parameters (Query); return Stmt; end; end Create_Statement; -- ------------------------------ -- Create a query statement and initialize the SQL statement with the query definition. -- ------------------------------ function Create_Statement (Database : in Session; Query : in ADO.Queries.Query_Definition_Access) return Query_Statement is begin Check_Session (Database); declare Index : constant ADO.Drivers.Driver_Index := Database.Impl.Database.Get_Driver_Index; SQL : constant String := ADO.Queries.Get_SQL (Query, Index); begin return Database.Impl.Database.Create_Statement (SQL); end; end Create_Statement; -- ------------------------------ -- Create a query statement. The statement is not prepared -- ------------------------------ function Create_Statement (Database : in Session; Query : in ADO.SQL.Query'Class; Table : in ADO.Schemas.Class_Mapping_Access) return Query_Statement is begin Check_Session (Database); declare Stmt : Query_Statement := Database.Impl.Database.Create_Statement (Table); begin if Query in ADO.Queries.Context'Class then declare Pos : constant ADO.Drivers.Driver_Index := Database.Impl.Database.Get_Driver_Index; SQL : constant String := ADO.Queries.Context'Class (Query).Get_SQL (Pos); begin ADO.SQL.Append (Stmt.Get_Query.SQL, SQL); end; end if; Stmt.Set_Parameters (Query); return Stmt; end; end Create_Statement; -- --------- -- Master Session -- --------- -- ------------------------------ -- Start a transaction. -- ------------------------------ procedure Begin_Transaction (Database : in out Master_Session) is begin Check_Session (Database, "Begin transaction {0}"); Database.Impl.Database.Begin_Transaction; end Begin_Transaction; -- ------------------------------ -- Commit the current transaction. -- ------------------------------ procedure Commit (Database : in out Master_Session) is begin Check_Session (Database, "Commit transaction {0}"); Database.Impl.Database.Commit; end Commit; -- ------------------------------ -- Rollback the current transaction. -- ------------------------------ procedure Rollback (Database : in out Master_Session) is begin Check_Session (Database, "Rollback transaction {0}"); Database.Impl.Database.Rollback; end Rollback; -- ------------------------------ -- Allocate an identifier for the table. -- ------------------------------ procedure Allocate (Database : in out Master_Session; Id : in out ADO.Objects.Object_Record'Class) is begin Check_Session (Database); ADO.Sequences.Allocate (Database.Sequences.all, Id); end Allocate; -- ------------------------------ -- Flush the objects that were modified. -- ------------------------------ procedure Flush (Database : in out Master_Session) is begin Check_Session (Database); end Flush; overriding procedure Adjust (Object : in out Session) is begin if Object.Impl /= null then Util.Concurrent.Counters.Increment (Object.Impl.Counter); end if; end Adjust; overriding procedure Finalize (Object : in out Session) is procedure Free is new Ada.Unchecked_Deallocation (Object => Session_Record, Name => Session_Record_Access); Is_Zero : Boolean; begin if Object.Impl /= null then Util.Concurrent.Counters.Decrement (Object.Impl.Counter, Is_Zero); if Is_Zero then ADO.Objects.Release_Proxy (Object.Impl.Proxy); Object.Impl.Database.Close; Free (Object.Impl); end if; Object.Impl := null; end if; end Finalize; -- ------------------------------ -- Create a delete statement -- ------------------------------ function Create_Statement (Database : in Master_Session; Table : in ADO.Schemas.Class_Mapping_Access) return Delete_Statement is begin Check_Session (Database); return Database.Impl.Database.Create_Statement (Table); end Create_Statement; -- ------------------------------ -- Create an update statement -- ------------------------------ function Create_Statement (Database : in Master_Session; Table : in ADO.Schemas.Class_Mapping_Access) return Update_Statement is begin Check_Session (Database); return Database.Impl.Database.Create_Statement (Table); end Create_Statement; -- ------------------------------ -- Create an insert statement -- ------------------------------ function Create_Statement (Database : in Master_Session; Table : in ADO.Schemas.Class_Mapping_Access) return Insert_Statement is begin Check_Session (Database); return Database.Impl.Database.Create_Statement (Table); end Create_Statement; -- ------------------------------ -- Internal method to get the session proxy associated with the given database session. -- The session proxy is associated with some ADO objects to be able to retrieve the database -- session for the implementation of lazy loading. The session proxy is kept until the -- session exist and at least one ADO object is refering to it. -- ------------------------------ function Get_Session_Proxy (Database : in Session) return ADO.Objects.Session_Proxy_Access is use type ADO.Objects.Session_Proxy_Access; begin Check_Session (Database); if Database.Impl.Proxy = null then Database.Impl.Proxy := ADO.Objects.Create_Session_Proxy (Database.Impl); end if; return Database.Impl.Proxy; end Get_Session_Proxy; end ADO.Sessions;
----------------------------------------------------------------------- -- ADO Sessions -- Sessions Management -- Copyright (C) 2009, 2010, 2011, 2012, 2013, 2014 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Log; with Util.Log.Loggers; with Ada.Unchecked_Deallocation; with ADO.Drivers; with ADO.Sequences; package body ADO.Sessions is Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("ADO.Sessions"); procedure Check_Session (Database : in Session'Class; Message : in String := "") is begin if Database.Impl = null then Log.Error ("Session is closed or not initialized"); raise NOT_OPEN; end if; if Message'Length > 0 then Log.Info (Message, Database.Impl.Database.Get_Ident); end if; end Check_Session; -- --------- -- Session -- --------- -- ------------------------------ -- Get the session status. -- ------------------------------ function Get_Status (Database : in Session) return ADO.Databases.Connection_Status is begin if Database.Impl = null then return ADO.Databases.CLOSED; end if; return Database.Impl.Database.Get_Status; end Get_Status; -- ------------------------------ -- Close the session. -- ------------------------------ procedure Close (Database : in out Session) is procedure Free is new Ada.Unchecked_Deallocation (Object => Session_Record, Name => Session_Record_Access); Is_Zero : Boolean; begin Log.Info ("Closing session"); if Database.Impl /= null then ADO.Objects.Release_Proxy (Database.Impl.Proxy); Database.Impl.Database.Close; Util.Concurrent.Counters.Decrement (Database.Impl.Counter, Is_Zero); if Is_Zero then Free (Database.Impl); end if; Database.Impl := null; end if; end Close; -- ------------------------------ -- Get the database connection. -- ------------------------------ function Get_Connection (Database : in Session) return ADO.Databases.Connection'Class is begin Check_Session (Database); return Database.Impl.Database; end Get_Connection; -- ------------------------------ -- Attach the object to the session. -- ------------------------------ procedure Attach (Database : in out Session; Object : in ADO.Objects.Object_Ref'Class) is pragma Unreferenced (Object); begin Check_Session (Database); end Attach; -- ------------------------------ -- Check if the session contains the object identified by the given key. -- ------------------------------ function Contains (Database : in Session; Item : in ADO.Objects.Object_Key) return Boolean is begin Check_Session (Database); return ADO.Objects.Cache.Contains (Database.Impl.Cache, Item); end Contains; -- ------------------------------ -- Remove the object from the session cache. -- ------------------------------ procedure Evict (Database : in out Session; Item : in ADO.Objects.Object_Key) is begin Check_Session (Database); ADO.Objects.Cache.Remove (Database.Impl.Cache, Item); end Evict; -- ------------------------------ -- Create a query statement. The statement is not prepared -- ------------------------------ function Create_Statement (Database : in Session; Table : in ADO.Schemas.Class_Mapping_Access) return Query_Statement is begin Check_Session (Database); return Database.Impl.Database.Create_Statement (Table); end Create_Statement; -- ------------------------------ -- Create a query statement. The statement is not prepared -- ------------------------------ function Create_Statement (Database : in Session; Query : in String) return Query_Statement is begin Check_Session (Database); return Database.Impl.Database.Create_Statement (Query); end Create_Statement; -- ------------------------------ -- Create a query statement. The statement is not prepared -- ------------------------------ function Create_Statement (Database : in Session; Query : in ADO.Queries.Context'Class) return Query_Statement is begin Check_Session (Database); declare SQL : constant String := Query.Get_SQL (Database.Impl.Database.Get_Driver_Index); Stmt : Query_Statement := Database.Impl.Database.Create_Statement (SQL); begin Stmt.Set_Parameters (Query); return Stmt; end; end Create_Statement; -- ------------------------------ -- Create a query statement and initialize the SQL statement with the query definition. -- ------------------------------ function Create_Statement (Database : in Session; Query : in ADO.Queries.Query_Definition_Access) return Query_Statement is begin Check_Session (Database); declare Index : constant ADO.Drivers.Driver_Index := Database.Impl.Database.Get_Driver_Index; SQL : constant String := ADO.Queries.Get_SQL (Query, Index, False); begin return Database.Impl.Database.Create_Statement (SQL); end; end Create_Statement; -- ------------------------------ -- Create a query statement. The statement is not prepared -- ------------------------------ function Create_Statement (Database : in Session; Query : in ADO.SQL.Query'Class; Table : in ADO.Schemas.Class_Mapping_Access) return Query_Statement is begin Check_Session (Database); declare Stmt : Query_Statement := Database.Impl.Database.Create_Statement (Table); begin if Query in ADO.Queries.Context'Class then declare Pos : constant ADO.Drivers.Driver_Index := Database.Impl.Database.Get_Driver_Index; SQL : constant String := ADO.Queries.Context'Class (Query).Get_SQL (Pos); begin ADO.SQL.Append (Stmt.Get_Query.SQL, SQL); end; end if; Stmt.Set_Parameters (Query); return Stmt; end; end Create_Statement; -- --------- -- Master Session -- --------- -- ------------------------------ -- Start a transaction. -- ------------------------------ procedure Begin_Transaction (Database : in out Master_Session) is begin Check_Session (Database, "Begin transaction {0}"); Database.Impl.Database.Begin_Transaction; end Begin_Transaction; -- ------------------------------ -- Commit the current transaction. -- ------------------------------ procedure Commit (Database : in out Master_Session) is begin Check_Session (Database, "Commit transaction {0}"); Database.Impl.Database.Commit; end Commit; -- ------------------------------ -- Rollback the current transaction. -- ------------------------------ procedure Rollback (Database : in out Master_Session) is begin Check_Session (Database, "Rollback transaction {0}"); Database.Impl.Database.Rollback; end Rollback; -- ------------------------------ -- Allocate an identifier for the table. -- ------------------------------ procedure Allocate (Database : in out Master_Session; Id : in out ADO.Objects.Object_Record'Class) is begin Check_Session (Database); ADO.Sequences.Allocate (Database.Sequences.all, Id); end Allocate; -- ------------------------------ -- Flush the objects that were modified. -- ------------------------------ procedure Flush (Database : in out Master_Session) is begin Check_Session (Database); end Flush; overriding procedure Adjust (Object : in out Session) is begin if Object.Impl /= null then Util.Concurrent.Counters.Increment (Object.Impl.Counter); end if; end Adjust; overriding procedure Finalize (Object : in out Session) is procedure Free is new Ada.Unchecked_Deallocation (Object => Session_Record, Name => Session_Record_Access); Is_Zero : Boolean; begin if Object.Impl /= null then Util.Concurrent.Counters.Decrement (Object.Impl.Counter, Is_Zero); if Is_Zero then ADO.Objects.Release_Proxy (Object.Impl.Proxy); Object.Impl.Database.Close; Free (Object.Impl); end if; Object.Impl := null; end if; end Finalize; -- ------------------------------ -- Create a delete statement -- ------------------------------ function Create_Statement (Database : in Master_Session; Table : in ADO.Schemas.Class_Mapping_Access) return Delete_Statement is begin Check_Session (Database); return Database.Impl.Database.Create_Statement (Table); end Create_Statement; -- ------------------------------ -- Create an update statement -- ------------------------------ function Create_Statement (Database : in Master_Session; Table : in ADO.Schemas.Class_Mapping_Access) return Update_Statement is begin Check_Session (Database); return Database.Impl.Database.Create_Statement (Table); end Create_Statement; -- ------------------------------ -- Create an insert statement -- ------------------------------ function Create_Statement (Database : in Master_Session; Table : in ADO.Schemas.Class_Mapping_Access) return Insert_Statement is begin Check_Session (Database); return Database.Impl.Database.Create_Statement (Table); end Create_Statement; -- ------------------------------ -- Internal method to get the session proxy associated with the given database session. -- The session proxy is associated with some ADO objects to be able to retrieve the database -- session for the implementation of lazy loading. The session proxy is kept until the -- session exist and at least one ADO object is refering to it. -- ------------------------------ function Get_Session_Proxy (Database : in Session) return ADO.Objects.Session_Proxy_Access is use type ADO.Objects.Session_Proxy_Access; begin Check_Session (Database); if Database.Impl.Proxy = null then Database.Impl.Proxy := ADO.Objects.Create_Session_Proxy (Database.Impl); end if; return Database.Impl.Proxy; end Get_Session_Proxy; end ADO.Sessions;
Update the Create_Statement operation to use the normal query definition
Update the Create_Statement operation to use the normal query definition
Ada
apache-2.0
stcarrez/ada-ado
89cc1384bcb562ce315402cb639e0f1162856402
src/ado-sessions.adb
src/ado-sessions.adb
----------------------------------------------------------------------- -- ADO Sessions -- Sessions Management -- 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.Log; with Util.Log.Loggers; with Ada.Unchecked_Deallocation; with ADO.Drivers; with ADO.Sequences; with ADO.Statements.Create; package body ADO.Sessions is Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("ADO.Sessions"); procedure Check_Session (Database : in Session'Class; Message : in String := "") is begin if Database.Impl = null then Log.Error ("Session is closed or not initialized"); raise NOT_OPEN; end if; if Message'Length > 0 then Log.Info (Message, Database.Impl.Database.Value.Ident); end if; end Check_Session; -- --------- -- Session -- --------- -- ------------------------------ -- Get the session status. -- ------------------------------ function Get_Status (Database : in Session) return Connection_Status is begin if Database.Impl = null or else Database.Impl.Database.Is_Null then return CLOSED; else return OPEN; end if; end Get_Status; -- ------------------------------ -- Get the database driver which manages this connection. -- ------------------------------ function Get_Driver (Database : in Session) return ADO.Drivers.Connections.Driver_Access is begin if Database.Impl = null or else Database.Impl.Database.Is_Null then return null; else return Database.Impl.Database.Value.Get_Driver; end if; end Get_Driver; -- ------------------------------ -- Close the session. -- ------------------------------ procedure Close (Database : in out Session) is procedure Free is new Ada.Unchecked_Deallocation (Object => Session_Record, Name => Session_Record_Access); Is_Zero : Boolean; begin Log.Info ("Closing session"); if Database.Impl /= null then ADO.Objects.Release_Proxy (Database.Impl.Proxy); Database.Impl.Database.Value.Close; Util.Concurrent.Counters.Decrement (Database.Impl.Counter, Is_Zero); if Is_Zero then Free (Database.Impl); end if; Database.Impl := null; end if; end Close; -- ------------------------------ -- Insert a new cache in the manager. The cache is identified by the given name. -- ------------------------------ procedure Add_Cache (Database : in out Session; Name : in String; Cache : in ADO.Caches.Cache_Type_Access) is begin Check_Session (Database); Database.Impl.Values.Add_Cache (Name, Cache); end Add_Cache; -- ------------------------------ -- Attach the object to the session. -- ------------------------------ procedure Attach (Database : in out Session; Object : in ADO.Objects.Object_Ref'Class) is pragma Unreferenced (Object); begin Check_Session (Database); end Attach; -- ------------------------------ -- Check if the session contains the object identified by the given key. -- ------------------------------ function Contains (Database : in Session; Item : in ADO.Objects.Object_Key) return Boolean is begin Check_Session (Database); return ADO.Objects.Cache.Contains (Database.Impl.Cache, Item); end Contains; -- ------------------------------ -- Remove the object from the session cache. -- ------------------------------ procedure Evict (Database : in out Session; Item : in ADO.Objects.Object_Key) is begin Check_Session (Database); ADO.Objects.Cache.Remove (Database.Impl.Cache, Item); end Evict; -- ------------------------------ -- Create a query statement. The statement is not prepared -- ------------------------------ function Create_Statement (Database : in Session; Table : in ADO.Schemas.Class_Mapping_Access) return Query_Statement is begin Check_Session (Database); declare Query : constant Query_Statement_Access := Database.Impl.Database.Value.all.Create_Statement (Table); begin return ADO.Statements.Create.Create_Statement (Query, Database.Impl.Values.all'Access); end; end Create_Statement; -- ------------------------------ -- Create a query statement. The statement is not prepared -- ------------------------------ function Create_Statement (Database : in Session; Query : in String) return Query_Statement is begin Check_Session (Database); declare Stmt : constant Query_Statement_Access := Database.Impl.Database.Value.all.Create_Statement (Query); begin return ADO.Statements.Create.Create_Statement (Stmt, Database.Impl.Values.all'Access); end; end Create_Statement; -- ------------------------------ -- Create a query statement. The statement is not prepared -- ------------------------------ function Create_Statement (Database : in Session; Query : in ADO.Queries.Context'Class) return Query_Statement is begin Check_Session (Database); declare SQL : constant String := Query.Get_SQL (Database.Impl.Queries.all); Stmt : Query_Statement := Database.Create_Statement (SQL); begin Stmt.Set_Parameters (Query); return Stmt; end; end Create_Statement; -- ------------------------------ -- Create a query statement and initialize the SQL statement with the query definition. -- ------------------------------ function Create_Statement (Database : in Session; Query : in ADO.Queries.Query_Definition_Access) return Query_Statement is begin Check_Session (Database); declare SQL : constant String := ADO.Queries.Get_SQL (Query, Database.Impl.Queries.all, False); begin return Database.Create_Statement (SQL); end; end Create_Statement; -- ------------------------------ -- Create a query statement. The statement is not prepared -- ------------------------------ function Create_Statement (Database : in Session; Query : in ADO.SQL.Query'Class; Table : in ADO.Schemas.Class_Mapping_Access) return Query_Statement is begin Check_Session (Database); declare Stmt : Query_Statement := Database.Create_Statement (Table); begin if Query in ADO.Queries.Context'Class then declare SQL : constant String := ADO.Queries.Context'Class (Query).Get_SQL (Database.Impl.Queries.all); begin ADO.SQL.Append (Stmt.Get_Query.SQL, SQL); end; end if; Stmt.Set_Parameters (Query); return Stmt; end; end Create_Statement; -- ------------------------------ -- Load the database schema definition for the current database. -- ------------------------------ procedure Load_Schema (Database : in Session; Schema : out ADO.Schemas.Schema_Definition) is begin Check_Session (Database, "Loading schema {0}"); Database.Impl.Database.Value.Load_Schema (Schema); end Load_Schema; -- --------- -- Master Session -- --------- -- ------------------------------ -- Start a transaction. -- ------------------------------ procedure Begin_Transaction (Database : in out Master_Session) is begin Check_Session (Database, "Begin transaction {0}"); Database.Impl.Database.Value.Begin_Transaction; end Begin_Transaction; -- ------------------------------ -- Commit the current transaction. -- ------------------------------ procedure Commit (Database : in out Master_Session) is begin Check_Session (Database, "Commit transaction {0}"); Database.Impl.Database.Value.Commit; end Commit; -- ------------------------------ -- Rollback the current transaction. -- ------------------------------ procedure Rollback (Database : in out Master_Session) is begin Check_Session (Database, "Rollback transaction {0}"); Database.Impl.Database.Value.Rollback; end Rollback; -- ------------------------------ -- Allocate an identifier for the table. -- ------------------------------ procedure Allocate (Database : in out Master_Session; Id : in out ADO.Objects.Object_Record'Class) is begin Check_Session (Database); ADO.Sequences.Allocate (Database.Sequences.all, Id); end Allocate; -- ------------------------------ -- Flush the objects that were modified. -- ------------------------------ procedure Flush (Database : in out Master_Session) is begin Check_Session (Database); end Flush; overriding procedure Adjust (Object : in out Session) is begin if Object.Impl /= null then Util.Concurrent.Counters.Increment (Object.Impl.Counter); end if; end Adjust; overriding procedure Finalize (Object : in out Session) is procedure Free is new Ada.Unchecked_Deallocation (Object => Session_Record, Name => Session_Record_Access); Is_Zero : Boolean; begin if Object.Impl /= null then Util.Concurrent.Counters.Decrement (Object.Impl.Counter, Is_Zero); if Is_Zero then ADO.Objects.Release_Proxy (Object.Impl.Proxy, Detach => True); if not Object.Impl.Database.Is_Null then Object.Impl.Database.Value.Close; end if; Free (Object.Impl); end if; Object.Impl := null; end if; end Finalize; -- ------------------------------ -- Create a delete statement -- ------------------------------ function Create_Statement (Database : in Master_Session; Table : in ADO.Schemas.Class_Mapping_Access) return Delete_Statement is begin Check_Session (Database); declare Stmt : constant Delete_Statement_Access := Database.Impl.Database.Value.all.Create_Statement (Table); begin return ADO.Statements.Create.Create_Statement (Stmt.all'Access, Database.Impl.Values.all'Access); end; end Create_Statement; -- ------------------------------ -- Create an update statement -- ------------------------------ function Create_Statement (Database : in Master_Session; Table : in ADO.Schemas.Class_Mapping_Access) return Update_Statement is begin Check_Session (Database); declare Stmt : constant Update_Statement_Access := Database.Impl.Database.Value.all.Create_Statement (Table); begin return ADO.Statements.Create.Create_Statement (Stmt.all'Access, Database.Impl.Values.all'Access); end; end Create_Statement; -- ------------------------------ -- Create an insert statement -- ------------------------------ function Create_Statement (Database : in Master_Session; Table : in ADO.Schemas.Class_Mapping_Access) return Insert_Statement is begin Check_Session (Database); declare Stmt : constant Insert_Statement_Access := Database.Impl.Database.Value.all.Create_Statement (Table); begin return ADO.Statements.Create.Create_Statement (Stmt.all'Access, Database.Impl.Values.all'Access); end; end Create_Statement; -- ------------------------------ -- Internal method to get the session proxy associated with the given database session. -- The session proxy is associated with some ADO objects to be able to retrieve the database -- session for the implementation of lazy loading. The session proxy is kept until the -- session exist and at least one ADO object is refering to it. -- ------------------------------ function Get_Session_Proxy (Database : in Session) return ADO.Objects.Session_Proxy_Access is use type ADO.Objects.Session_Proxy_Access; begin Check_Session (Database); if Database.Impl.Proxy = null then Database.Impl.Proxy := ADO.Objects.Create_Session_Proxy (Database.Impl); end if; return Database.Impl.Proxy; end Get_Session_Proxy; end ADO.Sessions;
----------------------------------------------------------------------- -- ADO Sessions -- Sessions Management -- Copyright (C) 2009, 2010, 2011, 2012, 2013, 2014, 2015, 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; with Util.Log.Loggers; with Ada.Unchecked_Deallocation; with ADO.Drivers; with ADO.Sequences; with ADO.Statements.Create; package body ADO.Sessions is Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("ADO.Sessions"); procedure Check_Session (Database : in Session'Class; Message : in String := "") is begin if Database.Impl = null then Log.Error ("Session is closed or not initialized"); raise Session_Error; end if; if Message'Length > 0 then Log.Info (Message, Database.Impl.Database.Value.Ident); end if; end Check_Session; -- --------- -- Session -- --------- -- ------------------------------ -- Get the session status. -- ------------------------------ function Get_Status (Database : in Session) return Connection_Status is begin if Database.Impl = null or else Database.Impl.Database.Is_Null then return CLOSED; else return OPEN; end if; end Get_Status; -- ------------------------------ -- Get the database driver which manages this connection. -- ------------------------------ function Get_Driver (Database : in Session) return ADO.Drivers.Connections.Driver_Access is begin if Database.Impl = null or else Database.Impl.Database.Is_Null then return null; else return Database.Impl.Database.Value.Get_Driver; end if; end Get_Driver; -- ------------------------------ -- Close the session. -- ------------------------------ procedure Close (Database : in out Session) is procedure Free is new Ada.Unchecked_Deallocation (Object => Session_Record, Name => Session_Record_Access); Is_Zero : Boolean; begin Log.Info ("Closing session"); if Database.Impl /= null then ADO.Objects.Release_Proxy (Database.Impl.Proxy); Database.Impl.Database.Value.Close; Util.Concurrent.Counters.Decrement (Database.Impl.Counter, Is_Zero); if Is_Zero then Free (Database.Impl); end if; Database.Impl := null; end if; end Close; -- ------------------------------ -- Insert a new cache in the manager. The cache is identified by the given name. -- ------------------------------ procedure Add_Cache (Database : in out Session; Name : in String; Cache : in ADO.Caches.Cache_Type_Access) is begin Check_Session (Database); Database.Impl.Values.Add_Cache (Name, Cache); end Add_Cache; -- ------------------------------ -- Attach the object to the session. -- ------------------------------ procedure Attach (Database : in out Session; Object : in ADO.Objects.Object_Ref'Class) is pragma Unreferenced (Object); begin Check_Session (Database); end Attach; -- ------------------------------ -- Check if the session contains the object identified by the given key. -- ------------------------------ function Contains (Database : in Session; Item : in ADO.Objects.Object_Key) return Boolean is begin Check_Session (Database); return ADO.Objects.Cache.Contains (Database.Impl.Cache, Item); end Contains; -- ------------------------------ -- Remove the object from the session cache. -- ------------------------------ procedure Evict (Database : in out Session; Item : in ADO.Objects.Object_Key) is begin Check_Session (Database); ADO.Objects.Cache.Remove (Database.Impl.Cache, Item); end Evict; -- ------------------------------ -- Create a query statement. The statement is not prepared -- ------------------------------ function Create_Statement (Database : in Session; Table : in ADO.Schemas.Class_Mapping_Access) return Query_Statement is begin Check_Session (Database); declare Query : constant Query_Statement_Access := Database.Impl.Database.Value.all.Create_Statement (Table); begin return ADO.Statements.Create.Create_Statement (Query, Database.Impl.Values.all'Access); end; end Create_Statement; -- ------------------------------ -- Create a query statement. The statement is not prepared -- ------------------------------ function Create_Statement (Database : in Session; Query : in String) return Query_Statement is begin Check_Session (Database); declare Stmt : constant Query_Statement_Access := Database.Impl.Database.Value.all.Create_Statement (Query); begin return ADO.Statements.Create.Create_Statement (Stmt, Database.Impl.Values.all'Access); end; end Create_Statement; -- ------------------------------ -- Create a query statement. The statement is not prepared -- ------------------------------ function Create_Statement (Database : in Session; Query : in ADO.Queries.Context'Class) return Query_Statement is begin Check_Session (Database); declare SQL : constant String := Query.Get_SQL (Database.Impl.Queries.all); Stmt : Query_Statement := Database.Create_Statement (SQL); begin Stmt.Set_Parameters (Query); return Stmt; end; end Create_Statement; -- ------------------------------ -- Create a query statement and initialize the SQL statement with the query definition. -- ------------------------------ function Create_Statement (Database : in Session; Query : in ADO.Queries.Query_Definition_Access) return Query_Statement is begin Check_Session (Database); declare SQL : constant String := ADO.Queries.Get_SQL (Query, Database.Impl.Queries.all, False); begin return Database.Create_Statement (SQL); end; end Create_Statement; -- ------------------------------ -- Create a query statement. The statement is not prepared -- ------------------------------ function Create_Statement (Database : in Session; Query : in ADO.SQL.Query'Class; Table : in ADO.Schemas.Class_Mapping_Access) return Query_Statement is begin Check_Session (Database); declare Stmt : Query_Statement := Database.Create_Statement (Table); begin if Query in ADO.Queries.Context'Class then declare SQL : constant String := ADO.Queries.Context'Class (Query).Get_SQL (Database.Impl.Queries.all); begin ADO.SQL.Append (Stmt.Get_Query.SQL, SQL); end; end if; Stmt.Set_Parameters (Query); return Stmt; end; end Create_Statement; -- ------------------------------ -- Load the database schema definition for the current database. -- ------------------------------ procedure Load_Schema (Database : in Session; Schema : out ADO.Schemas.Schema_Definition) is begin Check_Session (Database, "Loading schema {0}"); Database.Impl.Database.Value.Load_Schema (Schema); end Load_Schema; -- --------- -- Master Session -- --------- -- ------------------------------ -- Start a transaction. -- ------------------------------ procedure Begin_Transaction (Database : in out Master_Session) is begin Check_Session (Database, "Begin transaction {0}"); Database.Impl.Database.Value.Begin_Transaction; end Begin_Transaction; -- ------------------------------ -- Commit the current transaction. -- ------------------------------ procedure Commit (Database : in out Master_Session) is begin Check_Session (Database, "Commit transaction {0}"); Database.Impl.Database.Value.Commit; end Commit; -- ------------------------------ -- Rollback the current transaction. -- ------------------------------ procedure Rollback (Database : in out Master_Session) is begin Check_Session (Database, "Rollback transaction {0}"); Database.Impl.Database.Value.Rollback; end Rollback; -- ------------------------------ -- Allocate an identifier for the table. -- ------------------------------ procedure Allocate (Database : in out Master_Session; Id : in out ADO.Objects.Object_Record'Class) is begin Check_Session (Database); ADO.Sequences.Allocate (Database.Sequences.all, Id); end Allocate; -- ------------------------------ -- Flush the objects that were modified. -- ------------------------------ procedure Flush (Database : in out Master_Session) is begin Check_Session (Database); end Flush; overriding procedure Adjust (Object : in out Session) is begin if Object.Impl /= null then Util.Concurrent.Counters.Increment (Object.Impl.Counter); end if; end Adjust; overriding procedure Finalize (Object : in out Session) is procedure Free is new Ada.Unchecked_Deallocation (Object => Session_Record, Name => Session_Record_Access); Is_Zero : Boolean; begin if Object.Impl /= null then Util.Concurrent.Counters.Decrement (Object.Impl.Counter, Is_Zero); if Is_Zero then ADO.Objects.Release_Proxy (Object.Impl.Proxy, Detach => True); if not Object.Impl.Database.Is_Null then Object.Impl.Database.Value.Close; end if; Free (Object.Impl); end if; Object.Impl := null; end if; end Finalize; -- ------------------------------ -- Create a delete statement -- ------------------------------ function Create_Statement (Database : in Master_Session; Table : in ADO.Schemas.Class_Mapping_Access) return Delete_Statement is begin Check_Session (Database); declare Stmt : constant Delete_Statement_Access := Database.Impl.Database.Value.all.Create_Statement (Table); begin return ADO.Statements.Create.Create_Statement (Stmt.all'Access, Database.Impl.Values.all'Access); end; end Create_Statement; -- ------------------------------ -- Create an update statement -- ------------------------------ function Create_Statement (Database : in Master_Session; Table : in ADO.Schemas.Class_Mapping_Access) return Update_Statement is begin Check_Session (Database); declare Stmt : constant Update_Statement_Access := Database.Impl.Database.Value.all.Create_Statement (Table); begin return ADO.Statements.Create.Create_Statement (Stmt.all'Access, Database.Impl.Values.all'Access); end; end Create_Statement; -- ------------------------------ -- Create an insert statement -- ------------------------------ function Create_Statement (Database : in Master_Session; Table : in ADO.Schemas.Class_Mapping_Access) return Insert_Statement is begin Check_Session (Database); declare Stmt : constant Insert_Statement_Access := Database.Impl.Database.Value.all.Create_Statement (Table); begin return ADO.Statements.Create.Create_Statement (Stmt.all'Access, Database.Impl.Values.all'Access); end; end Create_Statement; -- ------------------------------ -- Internal method to get the session proxy associated with the given database session. -- The session proxy is associated with some ADO objects to be able to retrieve the database -- session for the implementation of lazy loading. The session proxy is kept until the -- session exist and at least one ADO object is refering to it. -- ------------------------------ function Get_Session_Proxy (Database : in Session) return ADO.Objects.Session_Proxy_Access is use type ADO.Objects.Session_Proxy_Access; begin Check_Session (Database); if Database.Impl.Proxy = null then Database.Impl.Proxy := ADO.Objects.Create_Session_Proxy (Database.Impl); end if; return Database.Impl.Proxy; end Get_Session_Proxy; end ADO.Sessions;
Raise the Session_Error exception if the session is not initialized
Raise the Session_Error exception if the session is not initialized
Ada
apache-2.0
stcarrez/ada-ado
b1a0e8118709bd94060ec257726ca194803a21f1
awa/src/awa-comments-module.adb
awa/src/awa-comments-module.adb
----------------------------------------------------------------------- -- awa-comments-module -- Comments module -- Copyright (C) 2011 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- package body AWA.Comments.Module is overriding procedure Initialize (Plugin : in out Comment_Module; App : access ASF.Applications.Main.Application'Class) is begin null; end Initialize; end AWA.Comments.Module;
----------------------------------------------------------------------- -- awa-comments-module -- Comments module -- Copyright (C) 2011 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Log.Loggers; package body AWA.Comments.Module is Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("AWA.Comments.Module"); overriding procedure Initialize (Plugin : in out Comment_Module; App : access ASF.Applications.Main.Application'Class) is begin Log.Info ("Initializing the comments module"); -- Setup the resource bundles. App.Register ("userMsg", "users"); -- Plugin.Manager := Plugin.Create_User_Manager; -- Register.Register (Plugin => Plugin, -- Name => "AWA.Users.Beans.Authenticate_Bean", -- Handler => AWA.Users.Beans.Create_Authenticate_Bean'Access); AWA.Modules.Module (Plugin).Initialize (App); end Initialize; end AWA.Comments.Module;
Update the comments module
Update the comments module
Ada
apache-2.0
tectronics/ada-awa,Letractively/ada-awa,tectronics/ada-awa,tectronics/ada-awa,Letractively/ada-awa,Letractively/ada-awa
5b803e0a8b0403fff89cedce7cf4defaad60ca27
src/ado-sessions.ads
src/ado-sessions.ads
----------------------------------------------------------------------- -- ADO Sessions -- Sessions Management -- Copyright (C) 2009, 2010, 2011, 2012, 2013, 2015, 2017, 2018 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Finalization; with ADO.Configs; with ADO.Schemas; with ADO.Statements; with ADO.Objects; with ADO.Objects.Cache; with ADO.Drivers.Connections; with ADO.Queries; with ADO.SQL; with ADO.Caches; with Util.Concurrent.Counters; limited with ADO.Sequences; limited with ADO.Schemas.Entities; -- = Session = -- The `ADO.Sessions` package defines the control and management of database sessions. -- The database session is represented by the `Session` or `Master_Session` types. -- It provides operation to create a database statement that can be executed. -- The `Session` type is used to represent read-only database sessions. It provides -- operations to query the database but it does not allow to update or delete content. -- The `Master_Session` type extends the `Session` type to provide write -- access and it provides operations to get update or delete statements. The differentiation -- between the two sessions is provided for the support of database replications with -- databases such as MySQL. -- -- @include ado-drivers.ads -- @include ado-sessions-sources.ads -- @include ado-sessions-factory.ads -- @include ado-caches.ads package ADO.Sessions is use ADO.Statements; -- Raised if the database connection is not open. Session_Error : exception; -- Raised when the connection URI is invalid. Connection_Error : exception renames ADO.Configs.Connection_Error; -- The database connection status type Connection_Status is (OPEN, CLOSED); type Object_Factory is tagged private; -- --------- -- Session -- --------- -- Read-only database connection (or slave connection). -- type Session is tagged private; -- Get the session status. function Get_Status (Database : in Session) return Connection_Status; -- Get the database driver which manages this connection. function Get_Driver (Database : in Session) return ADO.Drivers.Connections.Driver_Access; -- Close the session. procedure Close (Database : in out Session); -- Insert a new cache in the manager. The cache is identified by the given name. procedure Add_Cache (Database : in out Session; Name : in String; Cache : in ADO.Caches.Cache_Type_Access); -- Attach the object to the session. procedure Attach (Database : in out Session; Object : in ADO.Objects.Object_Ref'Class); -- Check if the session contains the object identified by the given key. function Contains (Database : in Session; Item : in ADO.Objects.Object_Key) return Boolean; -- Remove the object from the session cache. procedure Evict (Database : in out Session; Item : in ADO.Objects.Object_Key); -- Create a query statement. The statement is not prepared function Create_Statement (Database : in Session; Table : in ADO.Schemas.Class_Mapping_Access) return Query_Statement; -- Create a query statement. The statement is not prepared function Create_Statement (Database : in Session; Query : in String) return Query_Statement; -- Create a query statement. The statement is not prepared function Create_Statement (Database : in Session; Query : in ADO.Queries.Context'Class) return Query_Statement; -- Create a query statement and initialize the SQL statement with the query definition. function Create_Statement (Database : in Session; Query : in ADO.Queries.Query_Definition_Access) return Query_Statement; -- Create a query statement. The statement is not prepared function Create_Statement (Database : in Session; Query : in ADO.SQL.Query'Class; Table : in ADO.Schemas.Class_Mapping_Access) return Query_Statement; -- Load the database schema definition for the current database. procedure Load_Schema (Database : in Session; Schema : out ADO.Schemas.Schema_Definition); -- Internal method to get the session proxy associated with the given database session. -- The session proxy is associated with some ADO objects to be able to retrieve the database -- session for the implementation of lazy loading. The session proxy is kept until the -- session exist and at least one ADO object is refering to it. function Get_Session_Proxy (Database : in Session) return ADO.Objects.Session_Proxy_Access; -- --------- -- Master Session -- --------- -- Read-write session. -- type Master_Session is new Session with private; -- Start a transaction. procedure Begin_Transaction (Database : in out Master_Session); -- Commit the current transaction. procedure Commit (Database : in out Master_Session); -- Rollback the current transaction. procedure Rollback (Database : in out Master_Session); -- Allocate an identifier for the table. procedure Allocate (Database : in out Master_Session; Id : in out ADO.Objects.Object_Record'Class); -- Flush the objects that were modified. procedure Flush (Database : in out Master_Session); -- Create a delete statement function Create_Statement (Database : in Master_Session; Table : in ADO.Schemas.Class_Mapping_Access) return Delete_Statement; -- Create an update statement function Create_Statement (Database : in Master_Session; Table : in ADO.Schemas.Class_Mapping_Access) return Update_Statement; -- Create an insert statement function Create_Statement (Database : in Master_Session; Table : in ADO.Schemas.Class_Mapping_Access) return Insert_Statement; subtype Database_Connection is Drivers.Connections.Database_Connection; -- Internal operation to get access to the database connection. procedure Access_Connection (Database : in out Master_Session; Process : not null access procedure (Connection : in out Database_Connection'Class)); type Session_Record is limited private; type Session_Record_Access is access all Session_Record; private type Entity_Cache_Access is access ADO.Schemas.Entities.Entity_Cache; type Object_Factory is tagged record A : Integer; end record; type Object_Factory_Access is access all Object_Factory'Class; -- The <b>Session_Record</b> maintains the connection information to the database for -- the duration of the session. It also maintains a cache of application objects -- which is used when session objects are fetched (either through Load or a Find). -- The connection is released and the session record is deleted when the session -- is closed with <b>Close</b>. -- -- For the lazy loading support, each object is associated with a shared <b>Session_Proxy</b> -- object that allows to give access to the session record associated with the object. -- When a session is closed, the <b>Session_Proxy</b> is not deleted but it is simply -- unlinked from the session record. type Session_Record is limited record Counter : Util.Concurrent.Counters.Counter := Util.Concurrent.Counters.ONE; Database : ADO.Drivers.Connections.Ref.Ref; Proxy : ADO.Objects.Session_Proxy_Access; Cache : ADO.Objects.Cache.Object_Cache; Entities : Entity_Cache_Access; Values : ADO.Caches.Cache_Manager_Access; Queries : ADO.Queries.Query_Manager_Access; end record; type Session is new Ada.Finalization.Controlled with record Impl : Session_Record_Access := null; end record; overriding procedure Adjust (Object : in out Session); overriding procedure Finalize (Object : in out Session); type Factory_Access is access all ADO.Sequences.Factory; type Master_Session is new Session with record Sequences : Factory_Access; end record; procedure Check_Session (Database : in Session'Class; Message : in String := ""); pragma Inline (Check_Session); end ADO.Sessions;
----------------------------------------------------------------------- -- ADO Sessions -- Sessions Management -- Copyright (C) 2009, 2010, 2011, 2012, 2013, 2015, 2017, 2018 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Finalization; with ADO.Configs; with ADO.Schemas; with ADO.Statements; with ADO.Objects; with ADO.Objects.Cache; with ADO.Drivers.Connections; with ADO.Queries; with ADO.SQL; with ADO.Caches; with Util.Concurrent.Counters; limited with ADO.Sequences; limited with ADO.Schemas.Entities; limited with ADO.Audits; -- = Session = -- The `ADO.Sessions` package defines the control and management of database sessions. -- The database session is represented by the `Session` or `Master_Session` types. -- It provides operation to create a database statement that can be executed. -- The `Session` type is used to represent read-only database sessions. It provides -- operations to query the database but it does not allow to update or delete content. -- The `Master_Session` type extends the `Session` type to provide write -- access and it provides operations to get update or delete statements. The differentiation -- between the two sessions is provided for the support of database replications with -- databases such as MySQL. -- -- @include ado-drivers.ads -- @include ado-sessions-sources.ads -- @include ado-sessions-factory.ads -- @include ado-caches.ads package ADO.Sessions is use ADO.Statements; -- Raised if the database connection is not open. Session_Error : exception; -- Raised when the connection URI is invalid. Connection_Error : exception renames ADO.Configs.Connection_Error; -- The database connection status type Connection_Status is (OPEN, CLOSED); type Object_Factory is tagged private; -- --------- -- Session -- --------- -- Read-only database connection (or slave connection). -- type Session is tagged private; -- Get the session status. function Get_Status (Database : in Session) return Connection_Status; -- Get the database driver which manages this connection. function Get_Driver (Database : in Session) return ADO.Drivers.Connections.Driver_Access; -- Close the session. procedure Close (Database : in out Session); -- Insert a new cache in the manager. The cache is identified by the given name. procedure Add_Cache (Database : in out Session; Name : in String; Cache : in ADO.Caches.Cache_Type_Access); -- Attach the object to the session. procedure Attach (Database : in out Session; Object : in ADO.Objects.Object_Ref'Class); -- Check if the session contains the object identified by the given key. function Contains (Database : in Session; Item : in ADO.Objects.Object_Key) return Boolean; -- Remove the object from the session cache. procedure Evict (Database : in out Session; Item : in ADO.Objects.Object_Key); -- Create a query statement. The statement is not prepared function Create_Statement (Database : in Session; Table : in ADO.Schemas.Class_Mapping_Access) return Query_Statement; -- Create a query statement. The statement is not prepared function Create_Statement (Database : in Session; Query : in String) return Query_Statement; -- Create a query statement. The statement is not prepared function Create_Statement (Database : in Session; Query : in ADO.Queries.Context'Class) return Query_Statement; -- Create a query statement and initialize the SQL statement with the query definition. function Create_Statement (Database : in Session; Query : in ADO.Queries.Query_Definition_Access) return Query_Statement; -- Create a query statement. The statement is not prepared function Create_Statement (Database : in Session; Query : in ADO.SQL.Query'Class; Table : in ADO.Schemas.Class_Mapping_Access) return Query_Statement; -- Load the database schema definition for the current database. procedure Load_Schema (Database : in Session; Schema : out ADO.Schemas.Schema_Definition); -- Internal method to get the session proxy associated with the given database session. -- The session proxy is associated with some ADO objects to be able to retrieve the database -- session for the implementation of lazy loading. The session proxy is kept until the -- session exist and at least one ADO object is refering to it. function Get_Session_Proxy (Database : in Session) return ADO.Objects.Session_Proxy_Access; -- --------- -- Master Session -- --------- -- Read-write session. -- type Master_Session is new Session with private; -- Start a transaction. procedure Begin_Transaction (Database : in out Master_Session); -- Commit the current transaction. procedure Commit (Database : in out Master_Session); -- Rollback the current transaction. procedure Rollback (Database : in out Master_Session); -- Allocate an identifier for the table. procedure Allocate (Database : in out Master_Session; Id : in out ADO.Objects.Object_Record'Class); -- Flush the objects that were modified. procedure Flush (Database : in out Master_Session); -- Create a delete statement function Create_Statement (Database : in Master_Session; Table : in ADO.Schemas.Class_Mapping_Access) return Delete_Statement; -- Create an update statement function Create_Statement (Database : in Master_Session; Table : in ADO.Schemas.Class_Mapping_Access) return Update_Statement; -- Create an insert statement function Create_Statement (Database : in Master_Session; Table : in ADO.Schemas.Class_Mapping_Access) return Insert_Statement; -- Get the audit manager. function Get_Audit_Manager (Database : in Master_Session) return access Audits.Audit_Manager'Class; subtype Database_Connection is Drivers.Connections.Database_Connection; -- Internal operation to get access to the database connection. procedure Access_Connection (Database : in out Master_Session; Process : not null access procedure (Connection : in out Database_Connection'Class)); type Session_Record is limited private; type Session_Record_Access is access all Session_Record; private type Entity_Cache_Access is access ADO.Schemas.Entities.Entity_Cache; type Object_Factory is tagged record A : Integer; end record; type Object_Factory_Access is access all Object_Factory'Class; -- The <b>Session_Record</b> maintains the connection information to the database for -- the duration of the session. It also maintains a cache of application objects -- which is used when session objects are fetched (either through Load or a Find). -- The connection is released and the session record is deleted when the session -- is closed with <b>Close</b>. -- -- For the lazy loading support, each object is associated with a shared <b>Session_Proxy</b> -- object that allows to give access to the session record associated with the object. -- When a session is closed, the <b>Session_Proxy</b> is not deleted but it is simply -- unlinked from the session record. type Session_Record is limited record Counter : Util.Concurrent.Counters.Counter := Util.Concurrent.Counters.ONE; Database : ADO.Drivers.Connections.Ref.Ref; Proxy : ADO.Objects.Session_Proxy_Access; Cache : ADO.Objects.Cache.Object_Cache; Entities : Entity_Cache_Access; Values : ADO.Caches.Cache_Manager_Access; Queries : ADO.Queries.Query_Manager_Access; end record; type Session is new Ada.Finalization.Controlled with record Impl : Session_Record_Access := null; end record; overriding procedure Adjust (Object : in out Session); overriding procedure Finalize (Object : in out Session); type Factory_Access is access all ADO.Sequences.Factory; type Master_Session is new Session with record Sequences : Factory_Access; Audit : access ADO.Audits.Audit_Manager'Class; end record; procedure Check_Session (Database : in Session'Class; Message : in String := ""); pragma Inline (Check_Session); end ADO.Sessions;
Declare the Get_Audit_Manager function
Declare the Get_Audit_Manager function
Ada
apache-2.0
stcarrez/ada-ado
6e507378f4ba1e1a2ab4eced5b9b6ac420644df6
regtests/security-policies-tests.ads
regtests/security-policies-tests.ads
----------------------------------------------------------------------- -- 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.Strings; package Security.Policies.Tests is procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite); type Test is new Util.Tests.Test with null record; -- Test Add_Permission and Get_Permission_Index procedure Test_Add_Permission (T : in out Test); -- Test Create_Role and Get_Role_Name procedure Test_Create_Role (T : in out Test); -- Test Has_Permission procedure Test_Has_Permission (T : in out Test); -- Test reading policy files procedure Test_Read_Policy (T : in out Test); -- Test reading policy files and using the <role-permission> controller procedure Test_Role_Policy (T : in out Test); -- 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); type Test_Principal is new Principal with record Name : Util.Strings.String_Ref; Roles : Security.Policies.Roles.Role_Map := (others => False); end record; -- Returns true if the given permission is stored in the user principal. function Has_Role (User : in Test_Principal; Role : in Role_Type) return Boolean; -- Get the principal name. function Get_Name (From : in Test_Principal) return String; 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.Strings; with Security.Policies.Roles; package Security.Policies.Tests is procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite); type Test is new Util.Tests.Test with null record; -- Test Create_Role and Get_Role_Name procedure Test_Create_Role (T : in out Test); -- Test Has_Permission procedure Test_Has_Permission (T : in out Test); -- Test reading policy files procedure Test_Read_Policy (T : in out Test); -- Test reading policy files and using the <role-permission> controller procedure Test_Role_Policy (T : in out Test); -- 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); type Test_Principal is new Principal with record Name : Util.Strings.String_Ref; Roles : Security.Policies.Roles.Role_Map := (others => False); end record; -- 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; -- Get the principal name. function Get_Name (From : in Test_Principal) return String; end Security.Policies.Tests;
Fix compilation for Policies.Roles
Fix compilation for Policies.Roles
Ada
apache-2.0
Letractively/ada-security
3a396eee885174466cddb43462223c02180180e2
src/asf-server-web.adb
src/asf-server-web.adb
----------------------------------------------------------------------- -- asf.server -- ASF Server for AWS -- 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 AWS.Templates; with AWS.MIME; with AWS.Messages; with AWS.Services.Web_Block.Registry; with Ada.Strings.Fixed; with Ada.Exceptions; with EL.Beans; with ASF.Beans; with ASF.Applications.Views; with ASF.Components.Core; with ASF.Contexts.Faces; with ASF.Contexts.Writer.String; with EL.Objects; with EL.Contexts; with EL.Contexts.Default; with EL.Variables; with EL.Variables.Default; with Ada.Strings.Unbounded; with Util.Log.Loggers; with Ada.Containers.Vectors; package body ASF.Server.Web is use Util.Log; use ASF.Contexts; use Ada.Exceptions; use AWS.Templates; use ASF.Beans; use Ada.Strings.Unbounded; Log : constant Loggers.Logger := Loggers.Create ("ASF.Server.Web"); -- The logger function Reply_Page_500 (Request : in AWS.Status.Data; E : in Exception_Occurrence) return AWS.Response.Data; function Dispatch (App : Main.Application_Access; Page : String; Request : in AWS.Status.Data) return AWS.Response.Data; -- Binding to record the ASF applications and bind them to URI prefixes. type Binding is record Application : Main.Application_Access; Base_URI : access String; end record; type Binding_Array is array (Natural range <>) of Binding; type Binding_Array_Access is access all Binding_Array; Nb_Bindings : Natural := 0; Applications : Binding_Array_Access := null; type Bean_Object is record Bean : EL.Beans.Readonly_Bean_Access; Free : ASF.Beans.Free_Bean_Access; end record; package Bean_Vectors is new Ada.Containers.Vectors (Index_Type => Natural, Element_Type => Bean_Object); type Bean_Vector_Access is access all Bean_Vectors.Vector; -- ------------------------------ -- Default Resolver -- ------------------------------ type Web_ELResolver is new EL.Contexts.ELResolver with record Request : EL.Contexts.Default.Default_ELResolver_Access; Application : Main.Application_Access; Beans : Bean_Vector_Access; end record; overriding function Get_Value (Resolver : Web_ELResolver; Context : EL.Contexts.ELContext'Class; Base : access EL.Beans.Readonly_Bean'Class; Name : Unbounded_String) return EL.Objects.Object; overriding procedure Set_Value (Resolver : in Web_ELResolver; Context : in EL.Contexts.ELContext'Class; Base : access EL.Beans.Bean'Class; Name : in Unbounded_String; Value : in EL.Objects.Object); -- Get the value associated with a base object and a given property. overriding function Get_Value (Resolver : Web_ELResolver; Context : EL.Contexts.ELContext'Class; Base : access EL.Beans.Readonly_Bean'Class; Name : Unbounded_String) return EL.Objects.Object is use EL.Objects; Result : Object := Resolver.Request.Get_Value (Context, Base, Name); Bean : EL.Beans.Readonly_Bean_Access; Free : ASF.Beans.Free_Bean_Access; Scope : Scope_Type; begin if not EL.Objects.Is_Null (Result) then return Result; end if; Resolver.Application.Create (Name, Bean, Free, Scope); Resolver.Beans.Append (Bean_Object '(Bean, Free)); Result := To_Object (Bean); Resolver.Request.Register (Name, Result); return Result; end Get_Value; -- Set the value associated with a base object and a given property. overriding procedure Set_Value (Resolver : in Web_ELResolver; Context : in EL.Contexts.ELContext'Class; Base : access EL.Beans.Bean'Class; Name : in Unbounded_String; Value : in EL.Objects.Object) is begin Resolver.Request.Set_Value (Context, Base, Name, Value); end Set_Value; -- Register the application to serve requests procedure Register_Application (URI : in String; App : in Main.Application_Access) is Apps : constant Binding_Array_Access := new Binding_Array (1 .. Nb_Bindings + 1); begin if Applications /= null then Apps (1 .. Nb_Bindings) := Applications (1 .. Nb_Bindings); end if; Nb_Bindings := Nb_Bindings + 1; Apps (Apps'Last).Application := App; Apps (Apps'Last).Base_URI := new String '(URI); Applications := Apps; end Register_Application; function Dispatch (App : Main.Application_Access; Page : String; Request : in AWS.Status.Data) return AWS.Response.Data is use ASF; use ASF.Contexts.Faces; use ASF.Applications.Views; use EL.Contexts.Default; use EL.Variables; use EL.Variables.Default; use EL.Contexts; use EL.Objects; Writer : aliased Contexts.Writer.String.String_Writer; Context : aliased Faces_Context; View : Components.Core.UIViewRoot; ELContext : aliased EL.Contexts.Default.Default_Context; Variables : aliased Default_Variable_Mapper; Req_Resolver : aliased Default_ELResolver; Root_Resolver : aliased Web_ELResolver; Beans : aliased Bean_Vectors.Vector; -- Get the view handler Handler : constant access View_Handler'Class := App.Get_View_Handler; begin Root_Resolver.Application := App; Root_Resolver.Request := Req_Resolver'Unchecked_Access; Root_Resolver.Beans := Beans'Unchecked_Access; ELContext.Set_Resolver (Root_Resolver'Unchecked_Access); ELContext.Set_Variable_Mapper (Variables'Unchecked_Access); Context.Set_Response_Writer (Writer'Unchecked_Access); Context.Set_ELContext (ELContext'Unchecked_Access); Writer.Initialize ("text/xml", "UTF-8", 8192); Context.Set_Request (Request'Unrestricted_Access); Set_Current (Context'Unchecked_Access); Handler.Restore_View (Page, Context, View); Handler.Render_View (Context, View); Writer.Flush; declare C : Bean_Vectors.Cursor := Beans.First; begin while Bean_Vectors.Has_Element (C) loop declare Bean : Bean_Object := Bean_Vectors.Element (C); begin Bean.Free (Bean.Bean); end; Bean_Vectors.Next (C); end loop; end; return AWS.Response.Build (Content_Type => Writer.Get_Content_Type, UString_Message => Writer.Get_Response); end Dispatch; ---------------------- -- Main server callback ---------------------- function Server_Callback (Request : in AWS.Status.Data) return AWS.Response.Data is use Ada.Strings.Fixed; URI : constant String := AWS.Status.URI (Request); Slash_Pos : constant Natural := Index (URI, "/", URI'First + 1); Prefix_End : Natural; begin -- Find the module and action to invoke if Slash_Pos > 1 then Prefix_End := Slash_Pos - 1; else Prefix_End := URI'Last; end if; declare Prefix : constant String := URI (URI'First .. Prefix_End); Page : constant String := URI (Prefix_End + 1 .. URI'Last); begin for I in Applications.all'Range loop if Applications (I).Base_URI.all = Prefix then return Dispatch (Applications (I).Application, Page, Request); end if; end loop; end; return AWS.Response.Build ("text/html", "<p>Unknown application</p>"); exception when E : others => return Reply_Page_500 (Request, E); end Server_Callback; -- Return a 500 error function Reply_Page_500 (Request : in AWS.Status.Data; E : in Exception_Occurrence) return AWS.Response.Data is use type AWS.Messages.Status_Code; use AWS.Services; use AWS; Translations : Templates.Translate_Set; URI : constant String := AWS.Status.URI (Request); Name : constant String := Exception_Name (E); Message : constant String := Exception_Message (E); ContentType : constant String := Web_Block.Registry.Content_Type (URI); begin Templates.Insert (Translations, Templates.Assoc ("URI", URI)); Templates.Insert (Translations, Templates.Assoc ("EXCEPTION_NAME", Name)); Templates.Insert (Translations, Templates.Assoc ("EXCEPTION_MESSAGE", Message)); Log.Error ("Default_Callback exception for URI '{0}': {1}: {2}", URI, Name, Message); if ContentType = AWS.MIME.Text_HTML then return AWS.Response.Build (Content_Type => AWS.MIME.Text_HTML, Message_Body => String'(Templates.Parse ("errors/exception.thtml", Translations))); else return AWS.Response.Build (Content_Type => AWS.MIME.Text_XML, Message_Body => String'(Templates.Parse ("errors/exception.txml", Translations))); end if; end Reply_Page_500; end ASF.Server.Web;
----------------------------------------------------------------------- -- asf.server -- ASF Server for AWS -- 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 AWS.Templates; with AWS.MIME; with AWS.Messages; with AWS.Services.Web_Block.Registry; with Ada.Strings.Fixed; with Ada.Exceptions; with EL.Beans; with ASF.Beans; with ASF.Applications.Views; with ASF.Components.Core; with ASF.Contexts.Faces; with ASF.Contexts.Writer.String; with EL.Objects; with EL.Contexts; with EL.Contexts.Default; with EL.Variables; with EL.Variables.Default; with Ada.Strings.Unbounded; with Util.Log.Loggers; with Ada.Containers.Vectors; package body ASF.Server.Web is use Util.Log; use ASF.Contexts; use Ada.Exceptions; use AWS.Templates; use ASF.Beans; use Ada.Strings.Unbounded; Log : constant Loggers.Logger := Loggers.Create ("ASF.Server.Web"); -- The logger function Reply_Page_500 (Request : in AWS.Status.Data; E : in Exception_Occurrence) return AWS.Response.Data; function Dispatch (App : Main.Application_Access; Page : String; Request : in AWS.Status.Data) return AWS.Response.Data; -- Binding to record the ASF applications and bind them to URI prefixes. type Binding is record Application : Main.Application_Access; Base_URI : access String; end record; type Binding_Array is array (Natural range <>) of Binding; type Binding_Array_Access is access all Binding_Array; Nb_Bindings : Natural := 0; Applications : Binding_Array_Access := null; type Bean_Object is record Bean : EL.Beans.Readonly_Bean_Access; Free : ASF.Beans.Free_Bean_Access; end record; package Bean_Vectors is new Ada.Containers.Vectors (Index_Type => Natural, Element_Type => Bean_Object); type Bean_Vector_Access is access all Bean_Vectors.Vector; -- ------------------------------ -- Default Resolver -- ------------------------------ type Web_ELResolver is new EL.Contexts.ELResolver with record Request : EL.Contexts.Default.Default_ELResolver_Access; Application : Main.Application_Access; Beans : Bean_Vector_Access; end record; overriding function Get_Value (Resolver : Web_ELResolver; Context : EL.Contexts.ELContext'Class; Base : access EL.Beans.Readonly_Bean'Class; Name : Unbounded_String) return EL.Objects.Object; overriding procedure Set_Value (Resolver : in Web_ELResolver; Context : in EL.Contexts.ELContext'Class; Base : access EL.Beans.Bean'Class; Name : in Unbounded_String; Value : in EL.Objects.Object); -- Get the value associated with a base object and a given property. overriding function Get_Value (Resolver : Web_ELResolver; Context : EL.Contexts.ELContext'Class; Base : access EL.Beans.Readonly_Bean'Class; Name : Unbounded_String) return EL.Objects.Object is use EL.Objects; use EL.Beans; use EL.Variables; Result : Object := Resolver.Request.Get_Value (Context, Base, Name); Bean : EL.Beans.Readonly_Bean_Access; Free : ASF.Beans.Free_Bean_Access; Scope : Scope_Type; begin if not EL.Objects.Is_Null (Result) then return Result; end if; Resolver.Application.Create (Name, Bean, Free, Scope); if Bean = null then raise No_Variable with "Bean not found: '" & To_String (Name) & "'"; end if; Resolver.Beans.Append (Bean_Object '(Bean, Free)); Result := To_Object (Bean); Resolver.Request.Register (Name, Result); return Result; end Get_Value; -- Set the value associated with a base object and a given property. overriding procedure Set_Value (Resolver : in Web_ELResolver; Context : in EL.Contexts.ELContext'Class; Base : access EL.Beans.Bean'Class; Name : in Unbounded_String; Value : in EL.Objects.Object) is begin Resolver.Request.Set_Value (Context, Base, Name, Value); end Set_Value; -- Register the application to serve requests procedure Register_Application (URI : in String; App : in Main.Application_Access) is Apps : constant Binding_Array_Access := new Binding_Array (1 .. Nb_Bindings + 1); begin if Applications /= null then Apps (1 .. Nb_Bindings) := Applications (1 .. Nb_Bindings); end if; Nb_Bindings := Nb_Bindings + 1; Apps (Apps'Last).Application := App; Apps (Apps'Last).Base_URI := new String '(URI); Applications := Apps; end Register_Application; function Dispatch (App : Main.Application_Access; Page : String; Request : in AWS.Status.Data) return AWS.Response.Data is use ASF; use ASF.Contexts.Faces; use ASF.Applications.Views; use EL.Contexts.Default; use EL.Variables; use EL.Variables.Default; use EL.Contexts; use EL.Objects; use EL.Beans; Writer : aliased Contexts.Writer.String.String_Writer; Context : aliased Faces_Context; View : Components.Core.UIViewRoot; ELContext : aliased EL.Contexts.Default.Default_Context; Variables : aliased Default_Variable_Mapper; Req_Resolver : aliased Default_ELResolver; Root_Resolver : aliased Web_ELResolver; Beans : aliased Bean_Vectors.Vector; -- Get the view handler Handler : constant access View_Handler'Class := App.Get_View_Handler; begin Root_Resolver.Application := App; Root_Resolver.Request := Req_Resolver'Unchecked_Access; Root_Resolver.Beans := Beans'Unchecked_Access; ELContext.Set_Resolver (Root_Resolver'Unchecked_Access); ELContext.Set_Variable_Mapper (Variables'Unchecked_Access); Context.Set_Response_Writer (Writer'Unchecked_Access); Context.Set_ELContext (ELContext'Unchecked_Access); Writer.Initialize ("text/xml", "UTF-8", 8192); Context.Set_Request (Request'Unrestricted_Access); Set_Current (Context'Unchecked_Access); Handler.Restore_View (Page, Context, View); Handler.Render_View (Context, View); Writer.Flush; declare C : Bean_Vectors.Cursor := Beans.First; begin while Bean_Vectors.Has_Element (C) loop declare Bean : Bean_Object := Bean_Vectors.Element (C); begin if Bean.Bean /= null then Bean.Free (Bean.Bean); end if; end; Bean_Vectors.Next (C); end loop; end; return AWS.Response.Build (Content_Type => Writer.Get_Content_Type, UString_Message => Writer.Get_Response); end Dispatch; ---------------------- -- Main server callback ---------------------- function Server_Callback (Request : in AWS.Status.Data) return AWS.Response.Data is use Ada.Strings.Fixed; URI : constant String := AWS.Status.URI (Request); Slash_Pos : constant Natural := Index (URI, "/", URI'First + 1); Prefix_End : Natural; begin -- Find the module and action to invoke if Slash_Pos > 1 then Prefix_End := Slash_Pos - 1; else Prefix_End := URI'Last; end if; declare Prefix : constant String := URI (URI'First .. Prefix_End); Page : constant String := URI (Prefix_End + 1 .. URI'Last); begin for I in Applications.all'Range loop if Applications (I).Base_URI.all = Prefix then return Dispatch (Applications (I).Application, Page, Request); end if; end loop; end; return AWS.Response.Build ("text/html", "<p>Unknown application</p>"); exception when E : others => return Reply_Page_500 (Request, E); end Server_Callback; -- Return a 500 error function Reply_Page_500 (Request : in AWS.Status.Data; E : in Exception_Occurrence) return AWS.Response.Data is use type AWS.Messages.Status_Code; use AWS.Services; use AWS; Translations : Templates.Translate_Set; URI : constant String := AWS.Status.URI (Request); Name : constant String := Exception_Name (E); Message : constant String := Exception_Message (E); ContentType : constant String := Web_Block.Registry.Content_Type (URI); begin Templates.Insert (Translations, Templates.Assoc ("URI", URI)); Templates.Insert (Translations, Templates.Assoc ("EXCEPTION_NAME", Name)); Templates.Insert (Translations, Templates.Assoc ("EXCEPTION_MESSAGE", Message)); Log.Error ("Default_Callback exception for URI '{0}': {1}: {2}", URI, Name, Message); if ContentType = AWS.MIME.Text_HTML then return AWS.Response.Build (Content_Type => AWS.MIME.Text_HTML, Message_Body => String'(Templates.Parse ("errors/exception.thtml", Translations))); else return AWS.Response.Build (Content_Type => AWS.MIME.Text_XML, Message_Body => String'(Templates.Parse ("errors/exception.txml", Translations))); end if; end Reply_Page_500; end ASF.Server.Web;
Raise an exception if we cannot create a bean
Raise an exception if we cannot create a bean
Ada
apache-2.0
stcarrez/ada-asf,stcarrez/ada-asf,stcarrez/ada-asf
c099070e3459acfc01891f5ff30e8574c4570f5a
src/wiki-parsers.ads
src/wiki-parsers.ads
----------------------------------------------------------------------- -- wiki-parsers -- Wiki parser -- Copyright (C) 2011, 2015 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Strings.Wide_Wide_Unbounded; with Wiki.Documents; with Wiki.Attributes; -- == 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; -- Defines the possible wiki syntax supported by the parser. type Wiki_Syntax_Type is ( -- Google wiki syntax http://code.google.com/p/support/wiki/WikiSyntax SYNTAX_GOOGLE, -- Creole wiki syntax http://www.wikicreole.org/wiki/Creole1.0 SYNTAX_CREOLE, -- Dotclear syntax http://dotclear.org/documentation/2.0/usage/syntaxes SYNTAX_DOTCLEAR, -- PhpBB syntax http://wiki.phpbb.com/Help:Formatting SYNTAX_PHPBB, -- MediaWiki syntax http://www.mediawiki.org/wiki/Help:Formatting SYNTAX_MEDIA_WIKI, -- Markdown SYNTAX_MARKDOWN, -- A mix of the above SYNTAX_MIX); -- Parse the wiki text contained in <b>Text</b> according to the wiki syntax -- specified in <b>Syntax</b> and invoke the document reader procedures defined -- by <b>into</b>. procedure Parse (Into : in Wiki.Documents.Document_Reader_Access; Text : in Wide_Wide_String; Syntax : in Wiki_Syntax_Type := SYNTAX_MIX); private use Ada.Strings.Wide_Wide_Unbounded; HT : constant Wide_Wide_Character := Wide_Wide_Character'Val (16#09#); LF : constant Wide_Wide_Character := Wide_Wide_Character'Val (16#0A#); CR : constant Wide_Wide_Character := Wide_Wide_Character'Val (16#0D#); type Input is interface; type Input_Access is access all Input'Class; procedure Read_Char (From : in out Input; Token : out Wide_Wide_Character; Eof : out Boolean) is abstract; type Parser is limited record Pending : Wide_Wide_Character; Has_Pending : Boolean; Document : Wiki.Documents.Document_Reader_Access; Format : Wiki.Documents.Format_Map; Text : Ada.Strings.Wide_Wide_Unbounded.Unbounded_Wide_Wide_String; Token : Ada.Strings.Wide_Wide_Unbounded.Unbounded_Wide_Wide_String; 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; Header_Offset : Integer := 0; Quote_Level : Natural := 0; Escape_Char : Wide_Wide_Character; List_Level : Natural := 0; Reader : Input_Access := null; Attributes : Wiki.Attributes.Attribute_List_Type; 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); -- 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); procedure Start_Element (P : in out Parser; Name : in Ada.Strings.Wide_Wide_Unbounded.Unbounded_Wide_Wide_String; Attributes : in Wiki.Attributes.Attribute_List_Type); procedure End_Element (P : in out Parser; Name : in Ada.Strings.Wide_Wide_Unbounded.Unbounded_Wide_Wide_String); end Wiki.Parsers;
----------------------------------------------------------------------- -- wiki-parsers -- Wiki parser -- Copyright (C) 2011, 2015 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Strings.Wide_Wide_Unbounded; with Wiki.Documents; with Wiki.Attributes; -- == 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; -- Defines the possible wiki syntax supported by the parser. type Wiki_Syntax_Type is ( -- Google wiki syntax http://code.google.com/p/support/wiki/WikiSyntax SYNTAX_GOOGLE, -- Creole wiki syntax http://www.wikicreole.org/wiki/Creole1.0 SYNTAX_CREOLE, -- Dotclear syntax http://dotclear.org/documentation/2.0/usage/syntaxes SYNTAX_DOTCLEAR, -- PhpBB syntax http://wiki.phpbb.com/Help:Formatting SYNTAX_PHPBB, -- MediaWiki syntax http://www.mediawiki.org/wiki/Help:Formatting SYNTAX_MEDIA_WIKI, -- Markdown SYNTAX_MARKDOWN, -- A mix of the above SYNTAX_MIX); -- Parse the wiki text contained in <b>Text</b> according to the wiki syntax -- specified in <b>Syntax</b> and invoke the document reader procedures defined -- by <b>into</b>. procedure Parse (Into : in Wiki.Documents.Document_Reader_Access; Text : in Wide_Wide_String; Syntax : in Wiki_Syntax_Type := SYNTAX_MIX); private use Ada.Strings.Wide_Wide_Unbounded; HT : constant Wide_Wide_Character := Wide_Wide_Character'Val (16#09#); LF : constant Wide_Wide_Character := Wide_Wide_Character'Val (16#0A#); CR : constant Wide_Wide_Character := Wide_Wide_Character'Val (16#0D#); type Input is interface; type Input_Access is access all Input'Class; procedure Read_Char (From : in out Input; Token : out Wide_Wide_Character; Eof : out Boolean) is abstract; type Parser is limited record Pending : Wide_Wide_Character; Has_Pending : Boolean; Document : Wiki.Documents.Document_Reader_Access; Format : Wiki.Documents.Format_Map; Text : Ada.Strings.Wide_Wide_Unbounded.Unbounded_Wide_Wide_String; Token : Ada.Strings.Wide_Wide_Unbounded.Unbounded_Wide_Wide_String; 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; Header_Offset : Integer := 0; Quote_Level : Natural := 0; Escape_Char : Wide_Wide_Character; List_Level : Natural := 0; Reader : Input_Access := null; Attributes : Wiki.Attributes.Attribute_List_Type; 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); -- 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); procedure Start_Element (P : in out Parser; Name : in Unbounded_Wide_Wide_String; Attributes : in Wiki.Attributes.Attribute_List_Type); procedure End_Element (P : in out Parser; Name : in Ada.Strings.Wide_Wide_Unbounded.Unbounded_Wide_Wide_String); end Wiki.Parsers;
Declare the Skip_End_Of_Line procedure
Declare the Skip_End_Of_Line procedure
Ada
apache-2.0
stcarrez/ada-wiki,stcarrez/ada-wiki
d3061f1976fd5083fb73124a625eb1ec64f0f627
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 LF : constant Wide_Wide_Character := Wide_Wide_Character'Val (16#0A#); 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#); 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;
Add pragma Preelaborate
Add pragma Preelaborate
Ada
apache-2.0
stcarrez/ada-wiki,stcarrez/ada-wiki
9a970fbfba561c97950394853769e6287ade90ad
awa/plugins/awa-blogs/src/awa-blogs.ads
awa/plugins/awa-blogs/src/awa-blogs.ads
----------------------------------------------------------------------- -- awa-blogs -- Blogs module -- Copyright (C) 2011, 2014, 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. ----------------------------------------------------------------------- -- = Blogs Module = -- The `blogs` module is a small blog application which allows users to publish articles. -- A user may own several blogs, each blog having a name and its own base URI. Within a blog, -- the user may write articles and publish them. Once published, the articles are visible to -- anonymous users. -- -- The `blogs` module uses the [AWA_Tags] and [AWA_Comments] modules to allow to associate -- tags to a post and allow users to comment on the articles. -- -- @include awa-blogs-modules.ads -- -- @include awa-blogs-beans.ads -- @include-bean blogs.xml -- @include-bean blog-admin-post-list.xml -- @include-bean blog-post-list.xml -- @include-bean blog-comment-list.xml -- @include-bean blog-list.xml -- @include-bean blog-tags.xml -- -- == Queries == -- @include-query blog-admin-post-list.xml -- @include-query blog-post-list.xml -- @include-query blog-comment-list.xml -- @include-query blog-list.xml -- @include-query blog-tags.xml -- -- == Data model == -- [images/awa_blogs_model.png] -- package AWA.Blogs is pragma Pure; end AWA.Blogs;
----------------------------------------------------------------------- -- awa-blogs -- Blogs module -- Copyright (C) 2011, 2014, 2015, 2018, 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. ----------------------------------------------------------------------- -- = Blogs Module = -- The `blogs` module is a small blog application which allows users -- to publish articles. A user may own several blogs, each blog having -- a name and its own base URI. Within a blog, the user may write articles -- and publish them. Once published, the articles are visible to -- anonymous users. -- -- The `blogs` module uses several other modules: -- -- * the [Counters Module] to track page display counter to a blog post, -- * the [Tags Module] to associate one or several tags to a blog post, -- * the [Comments Module] to allow users to write comments on a blog post, -- * the [Images Module] to easily add images in blog post. -- -- @include awa-blogs-modules.ads -- @include awa-blogs-beans.ads -- @include-bean blogs.xml -- @include-bean blog-admin-post-list.xml -- @include-bean blog-post-list.xml -- @include-bean blog-comment-list.xml -- @include-bean blog-list.xml -- @include-bean blog-tags.xml -- -- == Queries == -- @include-query blog-admin-post-list.xml -- @include-query blog-post-list.xml -- @include-query blog-comment-list.xml -- @include-query blog-list.xml -- @include-query blog-tags.xml -- -- == Data model == -- [images/awa_blogs_model.png] -- package AWA.Blogs is pragma Pure; end AWA.Blogs;
Update the documentation
Update the documentation
Ada
apache-2.0
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
d16a960842b204037237526b51b765b199ea62f3
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 Ada.Strings.Wide_Wide_Unbounded; with Wiki.Documents; with Wiki.Attributes; -- == 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; -- Defines the possible wiki syntax supported by the parser. type Wiki_Syntax_Type is ( -- Google wiki syntax http://code.google.com/p/support/wiki/WikiSyntax SYNTAX_GOOGLE, -- Creole wiki syntax http://www.wikicreole.org/wiki/Creole1.0 SYNTAX_CREOLE, -- Dotclear syntax http://dotclear.org/documentation/2.0/usage/syntaxes SYNTAX_DOTCLEAR, -- PhpBB syntax http://wiki.phpbb.com/Help:Formatting SYNTAX_PHPBB, -- MediaWiki syntax http://www.mediawiki.org/wiki/Help:Formatting SYNTAX_MEDIA_WIKI, -- Markdown SYNTAX_MARKDOWN, -- A mix of the above SYNTAX_MIX, -- The input is plain possibly incorrect HTML. SYNTAX_HTML); -- Parse the wiki text contained in <b>Text</b> according to the wiki syntax -- specified in <b>Syntax</b> and invoke the document reader procedures defined -- by <b>into</b>. procedure Parse (Into : in Wiki.Documents.Document_Reader_Access; Text : in Wide_Wide_String; Syntax : in Wiki_Syntax_Type := SYNTAX_MIX); private use Ada.Strings.Wide_Wide_Unbounded; HT : constant Wide_Wide_Character := Wide_Wide_Character'Val (16#09#); LF : constant Wide_Wide_Character := Wide_Wide_Character'Val (16#0A#); CR : constant Wide_Wide_Character := Wide_Wide_Character'Val (16#0D#); type Input is interface; type Input_Access is access all Input'Class; procedure Read_Char (From : in out Input; Token : out Wide_Wide_Character; Eof : out Boolean) is abstract; type Parser is limited record Pending : Wide_Wide_Character; Has_Pending : Boolean; Document : Wiki.Documents.Document_Reader_Access; Format : Wiki.Documents.Format_Map; Text : Ada.Strings.Wide_Wide_Unbounded.Unbounded_Wide_Wide_String; Token : Ada.Strings.Wide_Wide_Unbounded.Unbounded_Wide_Wide_String; 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 : Input_Access := null; Attributes : Wiki.Attributes.Attribute_List_Type; 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); -- 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; Name : in Unbounded_Wide_Wide_String; Attributes : in Wiki.Attributes.Attribute_List_Type); procedure End_Element (P : in out Parser; Name : in Ada.Strings.Wide_Wide_Unbounded.Unbounded_Wide_Wide_String); 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 Ada.Strings.Wide_Wide_Unbounded; with Wiki.Documents; with Wiki.Attributes; -- == 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; -- Defines the possible wiki syntax supported by the parser. type Wiki_Syntax_Type is ( -- Google wiki syntax http://code.google.com/p/support/wiki/WikiSyntax SYNTAX_GOOGLE, -- Creole wiki syntax http://www.wikicreole.org/wiki/Creole1.0 SYNTAX_CREOLE, -- Dotclear syntax http://dotclear.org/documentation/2.0/usage/syntaxes SYNTAX_DOTCLEAR, -- PhpBB syntax http://wiki.phpbb.com/Help:Formatting SYNTAX_PHPBB, -- MediaWiki syntax http://www.mediawiki.org/wiki/Help:Formatting SYNTAX_MEDIA_WIKI, -- Markdown SYNTAX_MARKDOWN, -- A mix of the above SYNTAX_MIX, -- The input is plain possibly incorrect HTML. SYNTAX_HTML); -- Parse the wiki text contained in <b>Text</b> according to the wiki syntax -- specified in <b>Syntax</b> and invoke the document reader procedures defined -- by <b>into</b>. procedure Parse (Into : in Wiki.Documents.Document_Reader_Access; Text : in Wide_Wide_String; Syntax : in Wiki_Syntax_Type := SYNTAX_MIX); private use Ada.Strings.Wide_Wide_Unbounded; HT : constant Wide_Wide_Character := Wide_Wide_Character'Val (16#09#); LF : constant Wide_Wide_Character := Wide_Wide_Character'Val (16#0A#); CR : constant Wide_Wide_Character := Wide_Wide_Character'Val (16#0D#); type Input is interface; type Input_Access is access all Input'Class; procedure Read_Char (From : in out Input; Token : out Wide_Wide_Character; Eof : out Boolean) is abstract; type Parser is limited record Pending : Wide_Wide_Character; Has_Pending : Boolean; Document : Wiki.Documents.Document_Reader_Access; Format : Wiki.Documents.Format_Map; Text : Ada.Strings.Wide_Wide_Unbounded.Unbounded_Wide_Wide_String; Token : Ada.Strings.Wide_Wide_Unbounded.Unbounded_Wide_Wide_String; 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 : Input_Access := null; Attributes : Wiki.Attributes.Attribute_List_Type; 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; Name : in Unbounded_Wide_Wide_String; Attributes : in Wiki.Attributes.Attribute_List_Type); procedure End_Element (P : in out Parser; Name : in Ada.Strings.Wide_Wide_Unbounded.Unbounded_Wide_Wide_String); end Wiki.Parsers;
Declare Skip_Spaces procedure
Declare Skip_Spaces procedure
Ada
apache-2.0
stcarrez/ada-wiki,stcarrez/ada-wiki
7d23d797bb44a2c29e0912157248f19a656bbbea
src/wiki-parsers.ads
src/wiki-parsers.ads
----------------------------------------------------------------------- -- wiki-parsers -- Wiki parser -- Copyright (C) 2011, 2015, 2016, 2018 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with 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. The string is assumed to be in UTF-8 format. procedure Parse (Engine : in out Parser; Text : in String; 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.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 : aliased 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; In_Table : 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; Preformat_Column : Natural := 1; 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'Class; Token : out Wiki.Strings.WChar); pragma Inline (Peek); -- 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; -- Returns true if we are included from another wiki content. function Is_Included (P : in Parser) 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, 2018, 2020 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Wiki.Attributes; with Wiki.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. The string is assumed to be in UTF-8 format. procedure Parse (Engine : in out Parser; Text : in String; 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.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 : aliased 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; In_Table : 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; Preformat_Column : Natural := 1; Quote_Level : Natural := 0; Escape_Char : Wiki.Strings.WChar; Param_Char : Wiki.Strings.WChar; List_Level : Natural := 0; Previous_Tag : Html_Tag := UNKNOWN_TAG; 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'Class; Token : out Wiki.Strings.WChar); pragma Inline (Peek); -- 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; -- Returns true if we are included from another wiki content. function Is_Included (P : in Parser) 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;
Add Previous_Tag to handle closing some tags that are allowed to have not end tag such as img/br/hr/meta
Add Previous_Tag to handle closing some tags that are allowed to have not end tag such as img/br/hr/meta
Ada
apache-2.0
stcarrez/ada-wiki,stcarrez/ada-wiki
528de1c59b30d9845ed031f7ebb41856394d0060
src/sys/streams/util-streams-texts.adb
src/sys/streams/util-streams-texts.adb
----------------------------------------------------------------------- -- util-streams-texts -- Text stream utilities -- Copyright (C) 2010, 2011, 2012, 2016, 2017, 2019, 2020 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Interfaces; with Ada.IO_Exceptions; package body Util.Streams.Texts is use Ada.Streams; subtype Offset is Ada.Streams.Stream_Element_Offset; procedure Initialize (Stream : in out Print_Stream; To : access Output_Stream'Class) is begin Stream.Initialize (Output => To, Size => 4096); end Initialize; -- ------------------------------ -- Write a raw string on the stream. -- ------------------------------ procedure Write (Stream : in out Print_Stream; Item : in Ada.Strings.Unbounded.Unbounded_String) is Count : constant Natural := Ada.Strings.Unbounded.Length (Item); begin if Count > 0 then for I in 1 .. Count loop Stream.Write (Item => Ada.Strings.Unbounded.Element (Item, I)); end loop; end if; end Write; -- ------------------------------ -- Write a raw string on the stream. -- ------------------------------ procedure Write (Stream : in out Print_Stream; Item : in Ada.Strings.Wide_Wide_Unbounded.Unbounded_Wide_Wide_String) is Count : constant Natural := Ada.Strings.Wide_Wide_Unbounded.Length (Item); C : Wide_Wide_Character; begin if Count > 0 then for I in 1 .. Count loop C := Ada.Strings.Wide_Wide_Unbounded.Element (Item, I); Stream.Write_Wide (C); end loop; end if; end Write; -- ------------------------------ -- Write an integer on the stream. -- ------------------------------ procedure Write (Stream : in out Print_Stream; Item : in Integer) is S : constant String := Integer'Image (Item); begin if Item > 0 then Stream.Write (S (S'First + 1 .. S'Last)); else Stream.Write (S); end if; end Write; -- ------------------------------ -- Write an integer on the stream. -- ------------------------------ procedure Write (Stream : in out Print_Stream; Item : in Long_Long_Integer) is S : constant String := Long_Long_Integer'Image (Item); begin if Item > 0 then Stream.Write (S (S'First + 1 .. S'Last)); else Stream.Write (S); end if; end Write; -- ------------------------------ -- Write a date on the stream. -- ------------------------------ procedure Write (Stream : in out Print_Stream; Item : in Ada.Calendar.Time; Format : in GNAT.Calendar.Time_IO.Picture_String := GNAT.Calendar.Time_IO.ISO_Date) is begin Stream.Write (GNAT.Calendar.Time_IO.Image (Item, Format)); end Write; -- ------------------------------ -- Get the output stream content as a string. -- ------------------------------ function To_String (Stream : in Buffered.Output_Buffer_Stream'Class) return String is Size : constant Natural := Stream.Get_Size; Buffer : constant Streams.Buffered.Buffer_Access := Stream.Get_Buffer; Result : String (1 .. Size); begin for I in Result'Range loop Result (I) := Character'Val (Buffer (Stream_Element_Offset (I))); end loop; return Result; end To_String; -- ------------------------------ -- Write a character on the stream. -- ------------------------------ procedure Write_Char (Stream : in out Print_Stream'Class; Item : in Character) is begin Stream.Write (Item); end Write_Char; -- ------------------------------ -- Write a character on the stream. -- ------------------------------ procedure Write_Char (Stream : in out Print_Stream'Class; Item : in Wide_Wide_Character) is begin Stream.Write_Wide (Item); end Write_Char; -- ------------------------------ -- Initialize the reader to read the input from the input stream given in <b>From</b>. -- ------------------------------ procedure Initialize (Stream : in out Reader_Stream; From : access Input_Stream'Class) is begin Stream.Initialize (Input => From, Size => 4096); end Initialize; -- ------------------------------ -- Read an input line from the input stream. The line is terminated by ASCII.LF. -- When <b>Strip</b> is set, the line terminators (ASCII.CR, ASCII.LF) are removed. -- ------------------------------ procedure Read_Line (Stream : in out Reader_Stream; Into : out Ada.Strings.Unbounded.Unbounded_String; Strip : in Boolean := False) is C : Character; begin while not Stream.Is_Eof loop Stream.Read (C); if C = ASCII.LF then if not Strip then Ada.Strings.Unbounded.Append (Into, C); end if; return; elsif C /= ASCII.CR or not Strip then Ada.Strings.Unbounded.Append (Into, C); end if; end loop; exception when Ada.IO_Exceptions.Data_Error => return; end Read_Line; end Util.Streams.Texts;
----------------------------------------------------------------------- -- util-streams-texts -- Text stream utilities -- Copyright (C) 2010, 2011, 2012, 2016, 2017, 2019, 2020 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.IO_Exceptions; package body Util.Streams.Texts is use Ada.Streams; procedure Initialize (Stream : in out Print_Stream; To : access Output_Stream'Class) is begin Stream.Initialize (Output => To, Size => 4096); end Initialize; -- ------------------------------ -- Write a raw string on the stream. -- ------------------------------ procedure Write (Stream : in out Print_Stream; Item : in Ada.Strings.Unbounded.Unbounded_String) is Count : constant Natural := Ada.Strings.Unbounded.Length (Item); begin if Count > 0 then for I in 1 .. Count loop Stream.Write (Item => Ada.Strings.Unbounded.Element (Item, I)); end loop; end if; end Write; -- ------------------------------ -- Write a raw string on the stream. -- ------------------------------ procedure Write (Stream : in out Print_Stream; Item : in Ada.Strings.Wide_Wide_Unbounded.Unbounded_Wide_Wide_String) is Count : constant Natural := Ada.Strings.Wide_Wide_Unbounded.Length (Item); C : Wide_Wide_Character; begin if Count > 0 then for I in 1 .. Count loop C := Ada.Strings.Wide_Wide_Unbounded.Element (Item, I); Stream.Write_Wide (C); end loop; end if; end Write; -- ------------------------------ -- Write an integer on the stream. -- ------------------------------ procedure Write (Stream : in out Print_Stream; Item : in Integer) is S : constant String := Integer'Image (Item); begin if Item > 0 then Stream.Write (S (S'First + 1 .. S'Last)); else Stream.Write (S); end if; end Write; -- ------------------------------ -- Write an integer on the stream. -- ------------------------------ procedure Write (Stream : in out Print_Stream; Item : in Long_Long_Integer) is S : constant String := Long_Long_Integer'Image (Item); begin if Item > 0 then Stream.Write (S (S'First + 1 .. S'Last)); else Stream.Write (S); end if; end Write; -- ------------------------------ -- Write a date on the stream. -- ------------------------------ procedure Write (Stream : in out Print_Stream; Item : in Ada.Calendar.Time; Format : in GNAT.Calendar.Time_IO.Picture_String := GNAT.Calendar.Time_IO.ISO_Date) is begin Stream.Write (GNAT.Calendar.Time_IO.Image (Item, Format)); end Write; -- ------------------------------ -- Get the output stream content as a string. -- ------------------------------ function To_String (Stream : in Buffered.Output_Buffer_Stream'Class) return String is Size : constant Natural := Stream.Get_Size; Buffer : constant Streams.Buffered.Buffer_Access := Stream.Get_Buffer; Result : String (1 .. Size); begin for I in Result'Range loop Result (I) := Character'Val (Buffer (Stream_Element_Offset (I))); end loop; return Result; end To_String; -- ------------------------------ -- Write a character on the stream. -- ------------------------------ procedure Write_Char (Stream : in out Print_Stream'Class; Item : in Character) is begin Stream.Write (Item); end Write_Char; -- ------------------------------ -- Write a character on the stream. -- ------------------------------ procedure Write_Char (Stream : in out Print_Stream'Class; Item : in Wide_Wide_Character) is begin Stream.Write_Wide (Item); end Write_Char; -- ------------------------------ -- Initialize the reader to read the input from the input stream given in <b>From</b>. -- ------------------------------ procedure Initialize (Stream : in out Reader_Stream; From : access Input_Stream'Class) is begin Stream.Initialize (Input => From, Size => 4096); end Initialize; -- ------------------------------ -- Read an input line from the input stream. The line is terminated by ASCII.LF. -- When <b>Strip</b> is set, the line terminators (ASCII.CR, ASCII.LF) are removed. -- ------------------------------ procedure Read_Line (Stream : in out Reader_Stream; Into : out Ada.Strings.Unbounded.Unbounded_String; Strip : in Boolean := False) is C : Character; begin while not Stream.Is_Eof loop Stream.Read (C); if C = ASCII.LF then if not Strip then Ada.Strings.Unbounded.Append (Into, C); end if; return; elsif C /= ASCII.CR or not Strip then Ada.Strings.Unbounded.Append (Into, C); end if; end loop; exception when Ada.IO_Exceptions.Data_Error => return; end Read_Line; end Util.Streams.Texts;
Remove unused with Interfaces and Offset subtype declaration
Remove unused with Interfaces and Offset subtype declaration
Ada
apache-2.0
stcarrez/ada-util,stcarrez/ada-util
c140811ad7540d84ded6370bb7de143fc1598b47
ada/reader.adb
ada/reader.adb
with Ada.IO_Exceptions; with Ada.Characters.Latin_1; with Ada.Strings.Maps.Constants; with Ada.Strings.Unbounded; with Ada.Text_IO; with Opentoken.Recognizer.Character_Set; with Opentoken.Recognizer.Identifier; with Opentoken.Recognizer.Integer; with Opentoken.Recognizer.Keyword; with Opentoken.Recognizer.Line_Comment; with Opentoken.Recognizer.Real; with Opentoken.Recognizer.Separator; with Opentoken.Recognizer.Single_Character_Set; with Opentoken.Recognizer.String; with OpenToken.Text_Feeder.String; with Opentoken.Token.Enumerated.Analyzer; package body Reader is package ACL renames Ada.Characters.Latin_1; type Lexemes is (Int, Float_Tok, Sym, Nil, True_Tok, False_Tok, Exp_Tok, Splice_Unq, Str, Atom, Whitespace, Comment); package Lisp_Tokens is new Opentoken.Token.Enumerated (Lexemes); package Tokenizer is new Lisp_Tokens.Analyzer; Exp_Recognizer : constant Tokenizer.Recognizable_Token := Tokenizer.Get(Opentoken.Recognizer.Separator.Get ("**")); Splice_Unq_Recognizer : constant Tokenizer.Recognizable_Token := Tokenizer.Get(Opentoken.Recognizer.Separator.Get ("~@")); Nil_Recognizer : constant Tokenizer.Recognizable_Token := Tokenizer.Get(Opentoken.Recognizer.Keyword.Get ("nil")); True_Recognizer : constant Tokenizer.Recognizable_Token := Tokenizer.Get(Opentoken.Recognizer.Keyword.Get ("true")); False_Recognizer : constant Tokenizer.Recognizable_Token := Tokenizer.Get (Opentoken.Recognizer.Keyword.Get ("false")); ID_Recognizer : constant Tokenizer.Recognizable_Token := Tokenizer.Get(Opentoken.Recognizer.Identifier.Get); Int_Recognizer : constant Tokenizer.Recognizable_Token := Tokenizer.Get(Opentoken.Recognizer.Integer.Get); Float_Recognizer : constant Tokenizer.Recognizable_Token := Tokenizer.Get(Opentoken.Recognizer.Real.Get); -- Use the C style for escaped strings. String_Recognizer : constant Tokenizer.Recognizable_Token := Tokenizer.Get (Opentoken.Recognizer.String.Get (Escapeable => True, Double_Delimiter => False)); -- Atom definition Start_Chars : Ada.Strings.Maps.Character_Set := Ada.Strings.Maps.Constants.Letter_Set; Body_Chars : Ada.Strings.Maps.Character_Set := Ada.Strings.Maps."or" (Ada.Strings.Maps.Constants.Alphanumeric_Set, Ada.Strings.Maps.To_Set ('-')); Atom_Recognizer : constant Tokenizer.Recognizable_Token := Tokenizer.Get (Opentoken.Recognizer.Identifier.Get (Start_Chars, Body_Chars)); Lisp_Syms : constant Ada.Strings.Maps.Character_Set := Ada.Strings.Maps.To_Set ("[]{}()'`~^@+-*/"); Sym_Recognizer : constant Tokenizer.Recognizable_Token := Tokenizer.Get (Opentoken.Recognizer.Single_Character_Set.Get (Lisp_Syms)); Lisp_Whitespace : constant Ada.Strings.Maps.Character_Set := Ada.Strings.Maps.To_Set (ACL.HT & ACL.Space & ACL.Comma); Whitesp_Recognizer : constant Tokenizer.Recognizable_Token := Tokenizer.Get (Opentoken.Recognizer.Character_Set.Get (Lisp_Whitespace)); Comment_Recognizer : constant Tokenizer.Recognizable_Token := Tokenizer.Get(Opentoken.Recognizer.Line_Comment.Get (";")); Syntax : constant Tokenizer.Syntax := (Int => Int_Recognizer, Float_Tok => Float_Recognizer, Sym => Sym_Recognizer, Nil => Nil_Recognizer, True_Tok => True_Recognizer, False_Tok => False_Recognizer, Exp_Tok => Exp_Recognizer, Splice_Unq => Splice_Unq_Recognizer, Str => String_Recognizer, Atom => Atom_Recognizer, Whitespace => Whitesp_Recognizer, Comment => Comment_Recognizer); Input_Feeder : aliased OpenToken.Text_Feeder.String.Instance; Analyzer : Tokenizer.Instance := Tokenizer.Initialize (Syntax, Input_Feeder'access); function Get_Token_String return String is begin return Tokenizer.Lexeme (Analyzer); end Get_Token_String; function Get_Token_Char return Character is S : String := Tokenizer.Lexeme (Analyzer); begin return S(S'First); end Get_Token_Char; function Get_Token return Types.Mal_Type_Access is Res : Types.Mal_Type_Access; begin Tokenizer.Find_Next (Analyzer); case Tokenizer.ID (Analyzer) is when Int => Res := new Types.Mal_Type' (Sym_Type => Types.Int, Int_Val => Integer'Value (Get_Token_String)); when Float_Tok => Res := new Types.Mal_Type' (Sym_Type => Types.Floating, Float_Val => Float'Value (Get_Token_String)); when Sym => Res := new Types.Mal_Type' (Sym_Type => Types.Sym, Symbol => Get_Token_Char); when Nil => Res := new Types.Mal_Type' (Sym_Type => Types.Atom, The_Atom => Ada.Strings.Unbounded.To_Unbounded_String (Get_Token_String)); when True_Tok => Res := new Types.Mal_Type' (Sym_Type => Types.Atom, The_Atom => Ada.Strings.Unbounded.To_Unbounded_String (Get_Token_String)); when False_Tok => Res := new Types.Mal_Type' (Sym_Type => Types.Atom, The_Atom => Ada.Strings.Unbounded.To_Unbounded_String (Get_Token_String)); when Exp_Tok => Res := new Types.Mal_Type' (Sym_Type => Types.Atom, The_Atom => Ada.Strings.Unbounded.To_Unbounded_String (Get_Token_String)); when Splice_Unq => Res := new Types.Mal_Type' (Sym_Type => Types.Unitary, The_Function => Types.Splice_Unquote, The_Operand => null); when Str => Res := new Types.Mal_Type' (Sym_Type => Types.Str, The_String => Ada.Strings.Unbounded.To_Unbounded_String (Get_Token_String)); when Atom => Res := new Types.Mal_Type' (Sym_Type => Types.Atom, The_Atom => Ada.Strings.Unbounded.To_Unbounded_String (Get_Token_String)); when Whitespace | Comment => null; end case; return Res; end Get_Token; -- Parsing function Read_Form return Types.Mal_Type_Access; function Read_List (LT : Types.List_Types) return Types.Mal_Type_Access is use Types; List_MT, MTA : Mal_Type_Access; Close : Character := Types.Closing (LT); begin List_MT := new Mal_Type' (Sym_Type => List, List_Type => LT, The_List => Lists.Empty_List); loop MTA := Read_Form; exit when MTA = null or else MTA.all = (Sym_Type => Sym, Symbol => Close); Lists.Append (List_MT.The_List, MTA); end loop; return List_MT; end Read_List; function Read_Form return Types.Mal_Type_Access is use Types; MT : Types.Mal_Type_Access; begin MT := Get_Token; if MT = null then return null; end if; if MT.Sym_Type = Sym then if MT.Symbol = '(' then return Read_List (List_List); elsif MT.Symbol = '[' then return Read_List (Vector_List); elsif MT.Symbol = '{' then return Read_List (Hashed_List); elsif MT.Symbol = ACL.Apostrophe then return new Mal_Type' (Sym_Type => Unitary, The_Function => Quote, The_Operand => Read_Form); elsif MT.Symbol = ACL.Grave then return new Mal_Type' (Sym_Type => Unitary, The_Function => Quasiquote, The_Operand => Read_Form); elsif MT.Symbol = ACL.Tilde then return new Mal_Type' (Sym_Type => Unitary, The_Function => Unquote, The_Operand => Read_Form); else return MT; end if; elsif MT.Sym_Type = Unitary and then MT.The_Function = Splice_Unquote then return new Mal_Type' (Sym_Type => Unitary, The_Function => Splice_Unquote, The_Operand => Read_Form); else return MT; end if; end Read_Form; function Read_Str (S : String) return Types.Mal_Type_Access is begin Analyzer.Reset; Input_Feeder.Set (S); return Read_Form; exception when OPENTOKEN.SYNTAX_ERROR => Ada.Text_IO.Put_Line (Ada.Text_IO.Standard_Error, "Lexical error at char " & Integer'Image (Analyzer.Line)); raise Ada.IO_Exceptions.End_Error; end Read_Str; end Reader;
with Ada.IO_Exceptions; with Ada.Characters.Latin_1; with Ada.Strings.Maps.Constants; with Ada.Strings.Unbounded; with Ada.Text_IO; with Opentoken.Recognizer.Character_Set; with Opentoken.Recognizer.Identifier; with Opentoken.Recognizer.Integer; with Opentoken.Recognizer.Keyword; with Opentoken.Recognizer.Line_Comment; with Opentoken.Recognizer.Real; with Opentoken.Recognizer.Separator; with Opentoken.Recognizer.Single_Character_Set; with Opentoken.Recognizer.String; with OpenToken.Text_Feeder.String; with Opentoken.Token.Enumerated.Analyzer; package body Reader is package ACL renames Ada.Characters.Latin_1; type Lexemes is (Int, Float_Tok, Sym, Nil, True_Tok, False_Tok, Exp_Tok, Splice_Unq, Str, Atom, Whitespace, Comment); package Lisp_Tokens is new Opentoken.Token.Enumerated (Lexemes); package Tokenizer is new Lisp_Tokens.Analyzer; Exp_Recognizer : constant Tokenizer.Recognizable_Token := Tokenizer.Get(Opentoken.Recognizer.Separator.Get ("**")); Splice_Unq_Recognizer : constant Tokenizer.Recognizable_Token := Tokenizer.Get(Opentoken.Recognizer.Separator.Get ("~@")); Nil_Recognizer : constant Tokenizer.Recognizable_Token := Tokenizer.Get(Opentoken.Recognizer.Keyword.Get ("nil")); True_Recognizer : constant Tokenizer.Recognizable_Token := Tokenizer.Get(Opentoken.Recognizer.Keyword.Get ("true")); False_Recognizer : constant Tokenizer.Recognizable_Token := Tokenizer.Get (Opentoken.Recognizer.Keyword.Get ("false")); ID_Recognizer : constant Tokenizer.Recognizable_Token := Tokenizer.Get(Opentoken.Recognizer.Identifier.Get); Int_Recognizer : constant Tokenizer.Recognizable_Token := Tokenizer.Get(Opentoken.Recognizer.Integer.Get); Float_Recognizer : constant Tokenizer.Recognizable_Token := Tokenizer.Get(Opentoken.Recognizer.Real.Get); -- Use the C style for escaped strings. String_Recognizer : constant Tokenizer.Recognizable_Token := Tokenizer.Get (Opentoken.Recognizer.String.Get (Escapeable => True, Double_Delimiter => False)); -- Atom definition -- Note Start_Chars includes : for keywords. Start_Chars : Ada.Strings.Maps.Character_Set := Ada.Strings.Maps."or" (Ada.Strings.Maps.Constants.Letter_Set, Ada.Strings.Maps.To_Set (':')); Body_Chars : Ada.Strings.Maps.Character_Set := Ada.Strings.Maps."or" (Ada.Strings.Maps.Constants.Alphanumeric_Set, Ada.Strings.Maps.To_Set ('-')); Atom_Recognizer : constant Tokenizer.Recognizable_Token := Tokenizer.Get (Opentoken.Recognizer.Identifier.Get (Start_Chars, Body_Chars)); Lisp_Syms : constant Ada.Strings.Maps.Character_Set := Ada.Strings.Maps.To_Set ("[]{}()'`~^@+-*/"); Sym_Recognizer : constant Tokenizer.Recognizable_Token := Tokenizer.Get (Opentoken.Recognizer.Single_Character_Set.Get (Lisp_Syms)); Lisp_Whitespace : constant Ada.Strings.Maps.Character_Set := Ada.Strings.Maps.To_Set (ACL.HT & ACL.Space & ACL.Comma); Whitesp_Recognizer : constant Tokenizer.Recognizable_Token := Tokenizer.Get (Opentoken.Recognizer.Character_Set.Get (Lisp_Whitespace)); Comment_Recognizer : constant Tokenizer.Recognizable_Token := Tokenizer.Get(Opentoken.Recognizer.Line_Comment.Get (";")); Syntax : constant Tokenizer.Syntax := (Int => Int_Recognizer, Float_Tok => Float_Recognizer, Sym => Sym_Recognizer, Nil => Nil_Recognizer, True_Tok => True_Recognizer, False_Tok => False_Recognizer, Exp_Tok => Exp_Recognizer, Splice_Unq => Splice_Unq_Recognizer, Str => String_Recognizer, Atom => Atom_Recognizer, Whitespace => Whitesp_Recognizer, Comment => Comment_Recognizer); Input_Feeder : aliased OpenToken.Text_Feeder.String.Instance; Analyzer : Tokenizer.Instance := Tokenizer.Initialize (Syntax, Input_Feeder'access); function Get_Token_String return String is begin return Tokenizer.Lexeme (Analyzer); end Get_Token_String; function Get_Token_Char return Character is S : String := Tokenizer.Lexeme (Analyzer); begin return S(S'First); end Get_Token_Char; function Get_Token return Types.Mal_Type_Access is Res : Types.Mal_Type_Access; begin Tokenizer.Find_Next (Analyzer); case Tokenizer.ID (Analyzer) is when Int => Res := new Types.Mal_Type' (Sym_Type => Types.Int, Int_Val => Integer'Value (Get_Token_String)); when Float_Tok => Res := new Types.Mal_Type' (Sym_Type => Types.Floating, Float_Val => Float'Value (Get_Token_String)); when Sym => Res := new Types.Mal_Type' (Sym_Type => Types.Sym, Symbol => Get_Token_Char); when Nil => Res := new Types.Mal_Type' (Sym_Type => Types.Atom, The_Atom => Ada.Strings.Unbounded.To_Unbounded_String (Get_Token_String)); when True_Tok => Res := new Types.Mal_Type' (Sym_Type => Types.Atom, The_Atom => Ada.Strings.Unbounded.To_Unbounded_String (Get_Token_String)); when False_Tok => Res := new Types.Mal_Type' (Sym_Type => Types.Atom, The_Atom => Ada.Strings.Unbounded.To_Unbounded_String (Get_Token_String)); when Exp_Tok => Res := new Types.Mal_Type' (Sym_Type => Types.Atom, The_Atom => Ada.Strings.Unbounded.To_Unbounded_String (Get_Token_String)); when Splice_Unq => Res := new Types.Mal_Type' (Sym_Type => Types.Unitary, The_Function => Types.Splice_Unquote, The_Operand => null); when Str => Res := new Types.Mal_Type' (Sym_Type => Types.Str, The_String => Ada.Strings.Unbounded.To_Unbounded_String (Get_Token_String)); when Atom => Res := new Types.Mal_Type' (Sym_Type => Types.Atom, The_Atom => Ada.Strings.Unbounded.To_Unbounded_String (Get_Token_String)); when Whitespace | Comment => null; end case; return Res; end Get_Token; -- Parsing function Read_Form return Types.Mal_Type_Access; function Read_List (LT : Types.List_Types) return Types.Mal_Type_Access is use Types; List_MT, MTA : Mal_Type_Access; Close : Character := Types.Closing (LT); begin List_MT := new Mal_Type' (Sym_Type => List, List_Type => LT, The_List => Lists.Empty_List); loop MTA := Read_Form; exit when MTA = null or else MTA.all = (Sym_Type => Sym, Symbol => Close); Lists.Append (List_MT.The_List, MTA); end loop; return List_MT; end Read_List; function Read_Form return Types.Mal_Type_Access is use Types; MT : Types.Mal_Type_Access; begin MT := Get_Token; if MT = null then return null; end if; if MT.Sym_Type = Sym then if MT.Symbol = '(' then return Read_List (List_List); elsif MT.Symbol = '[' then return Read_List (Vector_List); elsif MT.Symbol = '{' then return Read_List (Hashed_List); elsif MT.Symbol = ACL.Apostrophe then return new Mal_Type' (Sym_Type => Unitary, The_Function => Quote, The_Operand => Read_Form); elsif MT.Symbol = ACL.Grave then return new Mal_Type' (Sym_Type => Unitary, The_Function => Quasiquote, The_Operand => Read_Form); elsif MT.Symbol = ACL.Tilde then return new Mal_Type' (Sym_Type => Unitary, The_Function => Unquote, The_Operand => Read_Form); else return MT; end if; elsif MT.Sym_Type = Unitary and then MT.The_Function = Splice_Unquote then return new Mal_Type' (Sym_Type => Unitary, The_Function => Splice_Unquote, The_Operand => Read_Form); else return MT; end if; end Read_Form; function Read_Str (S : String) return Types.Mal_Type_Access is begin Analyzer.Reset; Input_Feeder.Set (S); return Read_Form; exception when OPENTOKEN.SYNTAX_ERROR => Ada.Text_IO.Put_Line (Ada.Text_IO.Standard_Error, "Lexical error at char " & Integer'Image (Analyzer.Line)); raise Ada.IO_Exceptions.End_Error; end Read_Str; end Reader;
add keywords (well atoms beginning with :)
Ada: add keywords (well atoms beginning with :)
Ada
mpl-2.0
hterkelsen/mal,SawyerHood/mal,mpwillson/mal,foresterre/mal,0gajun/mal,DomBlack/mal,jwalsh/mal,foresterre/mal,mpwillson/mal,alantsev/mal,0gajun/mal,SawyerHood/mal,foresterre/mal,mpwillson/mal,mpwillson/mal,foresterre/mal,alantsev/mal,hterkelsen/mal,0gajun/mal,0gajun/mal,hterkelsen/mal,DomBlack/mal,SawyerHood/mal,hterkelsen/mal,jwalsh/mal,DomBlack/mal,jwalsh/mal,jwalsh/mal,SawyerHood/mal,0gajun/mal,mpwillson/mal,foresterre/mal,SawyerHood/mal,0gajun/mal,DomBlack/mal,0gajun/mal,jwalsh/mal,0gajun/mal,jwalsh/mal,joncol/mal,hterkelsen/mal,hterkelsen/mal,foresterre/mal,0gajun/mal,SawyerHood/mal,hterkelsen/mal,hterkelsen/mal,SawyerHood/mal,alantsev/mal,joncol/mal,mpwillson/mal,DomBlack/mal,DomBlack/mal,0gajun/mal,DomBlack/mal,jwalsh/mal,jwalsh/mal,alantsev/mal,foresterre/mal,hterkelsen/mal,jwalsh/mal,alantsev/mal,hterkelsen/mal,alantsev/mal,0gajun/mal,jwalsh/mal,alantsev/mal,DomBlack/mal,SawyerHood/mal,SawyerHood/mal,alantsev/mal,0gajun/mal,mpwillson/mal,foresterre/mal,0gajun/mal,alantsev/mal,alantsev/mal,alantsev/mal,foresterre/mal,DomBlack/mal,DomBlack/mal,foresterre/mal,foresterre/mal,DomBlack/mal,joncol/mal,jwalsh/mal,alantsev/mal,0gajun/mal,hterkelsen/mal,0gajun/mal,alantsev/mal,jwalsh/mal,DomBlack/mal,DomBlack/mal,foresterre/mal,0gajun/mal,foresterre/mal,foresterre/mal,jwalsh/mal,jwalsh/mal,DomBlack/mal,hterkelsen/mal,hterkelsen/mal,0gajun/mal,hterkelsen/mal,mpwillson/mal,SawyerHood/mal,hterkelsen/mal,mpwillson/mal,DomBlack/mal,DomBlack/mal,DomBlack/mal,mpwillson/mal,0gajun/mal,DomBlack/mal,mpwillson/mal,hterkelsen/mal,foresterre/mal,SawyerHood/mal,alantsev/mal,jwalsh/mal,mpwillson/mal,hterkelsen/mal,jwalsh/mal,foresterre/mal,SawyerHood/mal,alantsev/mal,hterkelsen/mal,mpwillson/mal,DomBlack/mal,SawyerHood/mal,0gajun/mal,alantsev/mal,hterkelsen/mal,mpwillson/mal,DomBlack/mal,SawyerHood/mal,SawyerHood/mal,SawyerHood/mal,foresterre/mal,alantsev/mal,SawyerHood/mal,DomBlack/mal,jwalsh/mal,SawyerHood/mal,0gajun/mal
537e16be9d802cf8b7704d663fb959444a2d37f2
matp/src/symbols/mat-symbols-targets.ads
matp/src/symbols/mat-symbols-targets.ads
----------------------------------------------------------------------- -- mat-symbols-targets - Symbol files management -- 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.Containers.Ordered_Maps; with Bfd.Symbols; with Bfd.Files; with Bfd.Constants; with Util.Refs; with MAT.Types; with MAT.Consoles; with MAT.Memory; package MAT.Symbols.Targets is -- The <tt>Region_Symbols</tt> holds the symbol table associated with the program or -- a shared library loaded by the program. The <tt>Region</tt> indicates -- the text segment address of the program or the loaded library. type Region_Symbols is new Util.Refs.Ref_Entity with record Region : MAT.Memory.Region_Info; Offset : MAT.Types.Target_Addr; File : Bfd.Files.File_Type; Symbols : Bfd.Symbols.Symbol_Table; end record; type Region_Symbols_Access is access all Region_Symbols; -- Load the symbol table for the associated region. procedure Open (Symbols : in out Region_Symbols; Path : in String); package Region_Symbols_Refs is new Util.Refs.References (Region_Symbols, Region_Symbols_Access); subtype Region_Symbols_Ref is Region_Symbols_Refs.Ref; type Symbol_Info is limited record File : Ada.Strings.Unbounded.Unbounded_String; Name : Ada.Strings.Unbounded.Unbounded_String; Line : Natural; Symbols : Region_Symbols_Ref; end record; -- The <tt>Symbols_Maps</tt> keeps a sorted list of symbol tables indexed -- by their mapping address. use type Region_Symbols_Refs.Ref; use type MAT.Types.Target_Addr; package Symbols_Maps is new Ada.Containers.Ordered_Maps (Key_Type => MAT.Types.Target_Addr, Element_Type => Region_Symbols_Ref); subtype Symbols_Map is Symbols_Maps.Map; subtype Symbols_Cursor is Symbols_Maps.Cursor; type Target_Symbols is new Util.Refs.Ref_Entity with record Path : Ada.Strings.Unbounded.Unbounded_String; Search_Path : Ada.Strings.Unbounded.Unbounded_String; Symbols : Bfd.Symbols.Symbol_Table; Libraries : Symbols_Maps.Map; Demangle : Bfd.Demangle_Flags := Bfd.Constants.DMGL_AUTO; Console : MAT.Consoles.Console_Access; end record; type Target_Symbols_Access is access all Target_Symbols; -- Open the binary and load the symbols from that file. procedure Open (Symbols : in out Target_Symbols; Path : in String); -- Load the symbols associated with a shared library described by the memory region. procedure Load_Symbols (Symbols : in out Target_Symbols; Region : in MAT.Memory.Region_Info; Offset_Addr : in MAT.Types.Target_Addr); -- Load the symbols associated with all the shared libraries described by -- the memory region map. procedure Load_Symbols (Symbols : in out Target_Symbols; Regions : in MAT.Memory.Region_Info_Map); -- Demangle the symbol. procedure Demangle (Symbols : in Target_Symbols; Symbol : in out Symbol_Info); -- Find the nearest source file and line for the given address. procedure Find_Nearest_Line (Symbols : in Target_Symbols; Addr : in MAT.Types.Target_Addr; Symbol : out Symbol_Info); -- Find the symbol in the symbol table and return the start and end address. procedure Find_Symbol_Range (Symbols : in Target_Symbols; Name : in String; From : out MAT.Types.Target_Addr; To : out MAT.Types.Target_Addr); package Target_Symbols_Refs is new Util.Refs.References (Target_Symbols, Target_Symbols_Access); subtype Target_Symbols_Ref is Target_Symbols_Refs.Ref; end MAT.Symbols.Targets;
----------------------------------------------------------------------- -- mat-symbols-targets - Symbol files management -- 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.Containers.Ordered_Maps; with Bfd.Symbols; with Bfd.Files; with Bfd.Constants; with Util.Refs; with MAT.Types; with MAT.Consoles; with MAT.Memory; package MAT.Symbols.Targets is -- The <tt>Region_Symbols</tt> holds the symbol table associated with the program or -- a shared library loaded by the program. The <tt>Region</tt> indicates -- the text segment address of the program or the loaded library. type Region_Symbols is new Util.Refs.Ref_Entity with record Region : MAT.Memory.Region_Info; Offset : MAT.Types.Target_Addr; File : Bfd.Files.File_Type; Symbols : Bfd.Symbols.Symbol_Table; end record; type Region_Symbols_Access is access all Region_Symbols; -- Load the symbol table for the associated region. procedure Open (Symbols : in out Region_Symbols; Path : in String; Search_Path : in String); package Region_Symbols_Refs is new Util.Refs.References (Region_Symbols, Region_Symbols_Access); subtype Region_Symbols_Ref is Region_Symbols_Refs.Ref; type Symbol_Info is limited record File : Ada.Strings.Unbounded.Unbounded_String; Name : Ada.Strings.Unbounded.Unbounded_String; Line : Natural; Symbols : Region_Symbols_Ref; end record; -- The <tt>Symbols_Maps</tt> keeps a sorted list of symbol tables indexed -- by their mapping address. use type Region_Symbols_Refs.Ref; use type MAT.Types.Target_Addr; package Symbols_Maps is new Ada.Containers.Ordered_Maps (Key_Type => MAT.Types.Target_Addr, Element_Type => Region_Symbols_Ref); subtype Symbols_Map is Symbols_Maps.Map; subtype Symbols_Cursor is Symbols_Maps.Cursor; type Target_Symbols is new Util.Refs.Ref_Entity with record Path : Ada.Strings.Unbounded.Unbounded_String; Search_Path : Ada.Strings.Unbounded.Unbounded_String; Symbols : Bfd.Symbols.Symbol_Table; Libraries : Symbols_Maps.Map; Demangle : Bfd.Demangle_Flags := Bfd.Constants.DMGL_AUTO; Console : MAT.Consoles.Console_Access; end record; type Target_Symbols_Access is access all Target_Symbols; -- Open the binary and load the symbols from that file. procedure Open (Symbols : in out Target_Symbols; Path : in String); -- Load the symbols associated with a shared library described by the memory region. procedure Load_Symbols (Symbols : in out Target_Symbols; Region : in MAT.Memory.Region_Info; Offset_Addr : in MAT.Types.Target_Addr); -- Load the symbols associated with all the shared libraries described by -- the memory region map. procedure Load_Symbols (Symbols : in out Target_Symbols; Regions : in MAT.Memory.Region_Info_Map); -- Demangle the symbol. procedure Demangle (Symbols : in Target_Symbols; Symbol : in out Symbol_Info); -- Find the nearest source file and line for the given address. procedure Find_Nearest_Line (Symbols : in Target_Symbols; Addr : in MAT.Types.Target_Addr; Symbol : out Symbol_Info); -- Find the symbol in the symbol table and return the start and end address. procedure Find_Symbol_Range (Symbols : in Target_Symbols; Name : in String; From : out MAT.Types.Target_Addr; To : out MAT.Types.Target_Addr); package Target_Symbols_Refs is new Util.Refs.References (Target_Symbols, Target_Symbols_Access); subtype Target_Symbols_Ref is Target_Symbols_Refs.Ref; end MAT.Symbols.Targets;
Add a Search_Path to the Open procedure
Add a Search_Path to the Open procedure
Ada
apache-2.0
stcarrez/mat,stcarrez/mat,stcarrez/mat
124d982d38602e00ec3e278d40fb3b8f83f52058
awa/plugins/awa-workspaces/src/awa-workspaces-beans.ads
awa/plugins/awa-workspaces/src/awa-workspaces-beans.ads
----------------------------------------------------------------------- -- awa-workspaces-beans -- Beans for 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 Ada.Strings.Unbounded; with Util.Beans.Basic; with Util.Beans.Objects; with Util.Beans.Methods; with AWA.Events; with AWA.Workspaces.Models; with AWA.Workspaces.Modules; package AWA.Workspaces.Beans is type Invitation_Bean is new AWA.Workspaces.Models.Invitation_Bean with record Module : AWA.Workspaces.Modules.Workspace_Module_Access := null; end record; type Invitation_Bean_Access is access all Invitation_Bean'Class; overriding procedure Load (Bean : in out Invitation_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String); overriding procedure Accept_Invitation (Bean : in out Invitation_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String); overriding procedure Send (Bean : in out Invitation_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String); -- Create the Invitation_Bean bean instance. function Create_Invitation_Bean (Module : in AWA.Workspaces.Modules.Workspace_Module_Access) return Util.Beans.Basic.Readonly_Bean_Access; type Workspaces_Bean is new Util.Beans.Basic.Bean and Util.Beans.Methods.Method_Bean with record Module : AWA.Workspaces.Modules.Workspace_Module_Access := null; Count : Natural := 0; end record; type Workspaces_Bean_Access is access all Workspaces_Bean'Class; -- Get the value identified by the name. overriding function Get_Value (From : in Workspaces_Bean; Name : in String) return Util.Beans.Objects.Object; -- Set the value identified by the name. overriding procedure Set_Value (From : in out Workspaces_Bean; Name : in String; Value : in Util.Beans.Objects.Object); -- This bean provides some methods that can be used in a Method_Expression overriding function Get_Method_Bindings (From : in Workspaces_Bean) return Util.Beans.Methods.Method_Binding_Array_Access; -- Event action called to create the workspace when the given event is posted. procedure Create (Bean : in out Workspaces_Bean; Event : in AWA.Events.Module_Event'Class); -- Example of action method. procedure Action (Bean : in out Workspaces_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String); -- Create the Workspaces_Bean bean instance. function Create_Workspaces_Bean (Module : in AWA.Workspaces.Modules.Workspace_Module_Access) return Util.Beans.Basic.Readonly_Bean_Access; type Member_List_Bean is new AWA.Workspaces.Models.Member_List_Bean with record Module : AWA.Workspaces.Modules.Workspace_Module_Access; -- The list of workspace members. Members : aliased AWA.Workspaces.Models.Member_Info_List_Bean; Members_Bean : Util.Beans.Basic.Readonly_Bean_Access; end record; type Member_List_Bean_Access is access all Member_List_Bean'Class; -- Get the value identified by the name. overriding function Get_Value (From : in Member_List_Bean; Name : in String) return Util.Beans.Objects.Object; -- Load the list of members. overriding procedure Load (Into : in out Member_List_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String); -- Create the Member_List_Bean bean instance. function Create_Member_List_Bean (Module : in AWA.Workspaces.Modules.Workspace_Module_Access) return Util.Beans.Basic.Readonly_Bean_Access; end AWA.Workspaces.Beans;
----------------------------------------------------------------------- -- awa-workspaces-beans -- Beans for 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 Ada.Strings.Unbounded; with Util.Beans.Basic; with Util.Beans.Objects; with Util.Beans.Methods; with AWA.Events; with AWA.Users.Models; with AWA.Workspaces.Models; with AWA.Workspaces.Modules; package AWA.Workspaces.Beans is type Invitation_Bean is new AWA.Workspaces.Models.Invitation_Bean with record Module : AWA.Workspaces.Modules.Workspace_Module_Access := null; Inviter : AWA.Users.Models.User_Ref; end record; type Invitation_Bean_Access is access all Invitation_Bean'Class; -- Get the value identified by the name. overriding function Get_Value (From : in Invitation_Bean; Name : in String) return Util.Beans.Objects.Object; overriding procedure Load (Bean : in out Invitation_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String); overriding procedure Accept_Invitation (Bean : in out Invitation_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String); overriding procedure Send (Bean : in out Invitation_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String); -- Create the Invitation_Bean bean instance. function Create_Invitation_Bean (Module : in AWA.Workspaces.Modules.Workspace_Module_Access) return Util.Beans.Basic.Readonly_Bean_Access; type Workspaces_Bean is new Util.Beans.Basic.Bean and Util.Beans.Methods.Method_Bean with record Module : AWA.Workspaces.Modules.Workspace_Module_Access := null; Count : Natural := 0; end record; type Workspaces_Bean_Access is access all Workspaces_Bean'Class; -- Get the value identified by the name. overriding function Get_Value (From : in Workspaces_Bean; Name : in String) return Util.Beans.Objects.Object; -- Set the value identified by the name. overriding procedure Set_Value (From : in out Workspaces_Bean; Name : in String; Value : in Util.Beans.Objects.Object); -- This bean provides some methods that can be used in a Method_Expression overriding function Get_Method_Bindings (From : in Workspaces_Bean) return Util.Beans.Methods.Method_Binding_Array_Access; -- Event action called to create the workspace when the given event is posted. procedure Create (Bean : in out Workspaces_Bean; Event : in AWA.Events.Module_Event'Class); -- Example of action method. procedure Action (Bean : in out Workspaces_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String); -- Create the Workspaces_Bean bean instance. function Create_Workspaces_Bean (Module : in AWA.Workspaces.Modules.Workspace_Module_Access) return Util.Beans.Basic.Readonly_Bean_Access; type Member_List_Bean is new AWA.Workspaces.Models.Member_List_Bean with record Module : AWA.Workspaces.Modules.Workspace_Module_Access; -- The list of workspace members. Members : aliased AWA.Workspaces.Models.Member_Info_List_Bean; Members_Bean : Util.Beans.Basic.Readonly_Bean_Access; end record; type Member_List_Bean_Access is access all Member_List_Bean'Class; -- Get the value identified by the name. overriding function Get_Value (From : in Member_List_Bean; Name : in String) return Util.Beans.Objects.Object; -- Load the list of members. overriding procedure Load (Into : in out Member_List_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String); -- Create the Member_List_Bean bean instance. function Create_Member_List_Bean (Module : in AWA.Workspaces.Modules.Workspace_Module_Access) return Util.Beans.Basic.Readonly_Bean_Access; end AWA.Workspaces.Beans;
Declare the Get_Value function and add the inviter information in the Invitation_Bean record
Declare the Get_Value function and add the inviter information in the Invitation_Bean record
Ada
apache-2.0
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
c3f376adfaf64ecbbc719babea765ebc0348e2fd
awa/plugins/awa-workspaces/src/awa-workspaces-beans.ads
awa/plugins/awa-workspaces/src/awa-workspaces-beans.ads
----------------------------------------------------------------------- -- awa-workspaces-beans -- Beans for 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 Ada.Strings.Unbounded; with Util.Beans.Basic; with Util.Beans.Objects; with Util.Beans.Methods; with AWA.Events; with AWA.Users.Models; with AWA.Workspaces.Models; with AWA.Workspaces.Modules; package AWA.Workspaces.Beans is type Member_Bean is new AWA.Workspaces.Models.Member_Bean with record Module : AWA.Workspaces.Modules.Workspace_Module_Access := null; end record; type Member_Bean_Access is access all Member_Bean'Class; -- Get the value identified by the name. overriding function Get_Value (From : in Member_Bean; Name : in String) return Util.Beans.Objects.Object; -- Set the value identified by the name overriding procedure Set_Value (Item : in out Member_Bean; Name : in String; Value : in Util.Beans.Objects.Object); overriding procedure Load (Bean : in out Member_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String); overriding procedure Delete (Bean : in out Member_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String); -- Create the Member_Bean bean instance. function Create_Member_Bean (Module : in AWA.Workspaces.Modules.Workspace_Module_Access) return Util.Beans.Basic.Readonly_Bean_Access; type Invitation_Bean is new AWA.Workspaces.Models.Invitation_Bean with record Module : AWA.Workspaces.Modules.Workspace_Module_Access := null; Inviter : AWA.Users.Models.User_Ref; end record; type Invitation_Bean_Access is access all Invitation_Bean'Class; -- Get the value identified by the name. overriding function Get_Value (From : in Invitation_Bean; Name : in String) return Util.Beans.Objects.Object; overriding procedure Load (Bean : in out Invitation_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String); overriding procedure Accept_Invitation (Bean : in out Invitation_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String); overriding procedure Send (Bean : in out Invitation_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String); -- Create the Invitation_Bean bean instance. function Create_Invitation_Bean (Module : in AWA.Workspaces.Modules.Workspace_Module_Access) return Util.Beans.Basic.Readonly_Bean_Access; type Workspaces_Bean is new Util.Beans.Basic.Bean and Util.Beans.Methods.Method_Bean with record Module : AWA.Workspaces.Modules.Workspace_Module_Access := null; Count : Natural := 0; end record; type Workspaces_Bean_Access is access all Workspaces_Bean'Class; -- Get the value identified by the name. overriding function Get_Value (From : in Workspaces_Bean; Name : in String) return Util.Beans.Objects.Object; -- Set the value identified by the name. overriding procedure Set_Value (From : in out Workspaces_Bean; Name : in String; Value : in Util.Beans.Objects.Object); -- This bean provides some methods that can be used in a Method_Expression overriding function Get_Method_Bindings (From : in Workspaces_Bean) return Util.Beans.Methods.Method_Binding_Array_Access; -- Event action called to create the workspace when the given event is posted. procedure Create (Bean : in out Workspaces_Bean; Event : in AWA.Events.Module_Event'Class); -- Example of action method. procedure Action (Bean : in out Workspaces_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String); -- Create the Workspaces_Bean bean instance. function Create_Workspaces_Bean (Module : in AWA.Workspaces.Modules.Workspace_Module_Access) return Util.Beans.Basic.Readonly_Bean_Access; type Member_List_Bean is new AWA.Workspaces.Models.Member_List_Bean with record Module : AWA.Workspaces.Modules.Workspace_Module_Access; -- The list of workspace members. Members : aliased AWA.Workspaces.Models.Member_Info_List_Bean; Members_Bean : Util.Beans.Basic.Readonly_Bean_Access; end record; type Member_List_Bean_Access is access all Member_List_Bean'Class; -- Get the value identified by the name. overriding function Get_Value (From : in Member_List_Bean; Name : in String) return Util.Beans.Objects.Object; -- Load the list of members. overriding procedure Load (Into : in out Member_List_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String); -- Create the Member_List_Bean bean instance. function Create_Member_List_Bean (Module : in AWA.Workspaces.Modules.Workspace_Module_Access) return Util.Beans.Basic.Readonly_Bean_Access; end AWA.Workspaces.Beans;
----------------------------------------------------------------------- -- awa-workspaces-beans -- Beans for 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 Ada.Strings.Unbounded; with Util.Beans.Basic; with Util.Beans.Objects; with Util.Beans.Methods; with AWA.Events; with AWA.Users.Models; with AWA.Workspaces.Models; with AWA.Workspaces.Modules; package AWA.Workspaces.Beans is type Member_Bean is new AWA.Workspaces.Models.Member_Bean with record Module : AWA.Workspaces.Modules.Workspace_Module_Access := null; end record; type Member_Bean_Access is access all Member_Bean'Class; -- Get the value identified by the name. overriding function Get_Value (From : in Member_Bean; Name : in String) return Util.Beans.Objects.Object; -- Set the value identified by the name overriding procedure Set_Value (Item : in out Member_Bean; Name : in String; Value : in Util.Beans.Objects.Object); overriding procedure Load (Bean : in out Member_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String); overriding procedure Delete (Bean : in out Member_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String); -- Create the Member_Bean bean instance. function Create_Member_Bean (Module : in AWA.Workspaces.Modules.Workspace_Module_Access) return Util.Beans.Basic.Readonly_Bean_Access; type Invitation_Bean is new AWA.Workspaces.Models.Invitation_Bean with record Module : AWA.Workspaces.Modules.Workspace_Module_Access := null; Inviter : AWA.Users.Models.User_Ref; end record; type Invitation_Bean_Access is access all Invitation_Bean'Class; -- Get the value identified by the name. overriding function Get_Value (From : in Invitation_Bean; Name : in String) return Util.Beans.Objects.Object; overriding procedure Load (Bean : in out Invitation_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String); overriding procedure Accept_Invitation (Bean : in out Invitation_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String); overriding procedure Send (Bean : in out Invitation_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String); -- Create the Invitation_Bean bean instance. function Create_Invitation_Bean (Module : in AWA.Workspaces.Modules.Workspace_Module_Access) return Util.Beans.Basic.Readonly_Bean_Access; type Workspaces_Bean is new Util.Beans.Basic.Bean and Util.Beans.Methods.Method_Bean with record Module : AWA.Workspaces.Modules.Workspace_Module_Access := null; Count : Natural := 0; end record; type Workspaces_Bean_Access is access all Workspaces_Bean'Class; -- Get the value identified by the name. overriding function Get_Value (From : in Workspaces_Bean; Name : in String) return Util.Beans.Objects.Object; -- Set the value identified by the name. overriding procedure Set_Value (From : in out Workspaces_Bean; Name : in String; Value : in Util.Beans.Objects.Object); -- This bean provides some methods that can be used in a Method_Expression overriding function Get_Method_Bindings (From : in Workspaces_Bean) return Util.Beans.Methods.Method_Binding_Array_Access; -- Event action called to create the workspace when the given event is posted. procedure Create (Bean : in out Workspaces_Bean; Event : in AWA.Events.Module_Event'Class); -- Create the Workspaces_Bean bean instance. function Create_Workspaces_Bean (Module : in AWA.Workspaces.Modules.Workspace_Module_Access) return Util.Beans.Basic.Readonly_Bean_Access; type Member_List_Bean is new AWA.Workspaces.Models.Member_List_Bean with record Module : AWA.Workspaces.Modules.Workspace_Module_Access; -- The list of workspace members. Members : aliased AWA.Workspaces.Models.Member_Info_List_Bean; Members_Bean : Util.Beans.Basic.Readonly_Bean_Access; end record; type Member_List_Bean_Access is access all Member_List_Bean'Class; -- Get the value identified by the name. overriding function Get_Value (From : in Member_List_Bean; Name : in String) return Util.Beans.Objects.Object; -- Load the list of members. overriding procedure Load (Into : in out Member_List_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String); -- Create the Member_List_Bean bean instance. function Create_Member_List_Bean (Module : in AWA.Workspaces.Modules.Workspace_Module_Access) return Util.Beans.Basic.Readonly_Bean_Access; end AWA.Workspaces.Beans;
Remove the Action procedure that is not used
Remove the Action procedure that is not used
Ada
apache-2.0
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
ddd8aa2de901330104d5fa8fcc1e24f79c40e89f
src/asf-views-facelets.ads
src/asf-views-facelets.ads
----------------------------------------------------------------------- -- asf-views-facelets -- Facelets representation and management -- 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 Ada.Calendar; with Ada.Strings.Unbounded; with Ada.Containers.Indefinite_Hashed_Maps; with Ada.Strings.Unbounded.Hash; with ASF.Views.Nodes; with ASF.Contexts.Facelets; with ASF.Factory; with ASF.Components; with Util.Strings; with Ada.Finalization; -- The <b>ASF.Views.Facelets</b> package contains the facelet factory -- responsible for getting the facelet tree from a facelet name. -- The facelets (or *.xhtml) files are loaded by the reader to form -- a tag node tree which is cached by the factory. The facelet factory -- is shared by multiple requests and threads. package ASF.Views.Facelets is type Facelet is private; type Facelet_Access is access all Facelet; -- Returns True if the facelet is null/empty. function Is_Null (F : Facelet) return Boolean; -- ------------------------------ -- Facelet factory -- ------------------------------ -- The facelet factory allows to retrieve the node tree to build the -- component tree. The node tree can be shared by several component trees. -- The node tree is initialized from the <b>XHTML</b> view file. It is put -- in a cache to avoid loading and parsing the file several times. type Facelet_Factory is limited private; -- Get the facelet identified by the given name. If the facelet is already -- loaded, the cached value is returned. The facelet file is searched in -- a set of directories configured in the facelet factory. procedure Find_Facelet (Factory : in out Facelet_Factory; Name : in String; Context : in ASF.Contexts.Facelets.Facelet_Context'Class; Result : out Facelet); -- Create the component tree from the facelet view. procedure Build_View (View : in Facelet; Context : in out ASF.Contexts.Facelets.Facelet_Context'Class; Root : in ASF.Components.UIComponent_Access); -- Initialize the facelet factory. -- Set the search directories for facelet files. -- Set the ignore white space configuration when reading XHTML files. -- Set the ignore empty lines configuration when reading XHTML files. -- Set the escape unknown tags configuration when reading XHTML files. procedure Initialize (Factory : in out Facelet_Factory; Paths : in String; Ignore_White_Spaces : in Boolean; Ignore_Empty_Lines : in Boolean; Escape_Unknown_Tags : in Boolean); -- Find the facelet file in one of the facelet directories. -- Returns the path to be used for reading the facelet file. function Find_Facelet_Path (Factory : Facelet_Factory; Name : String) return String; -- Register the component factory bindings in the facelet factory. procedure Register (Factory : in out Facelet_Factory; Bindings : in ASF.Factory.Factory_Bindings_Access); -- Register a module and directory where the module files are stored. procedure Register_Module (Factory : in out Facelet_Factory; Name : in String; Paths : in String); -- Clear the facelet cache procedure Clear_Cache (Factory : in out Facelet_Factory); private use Ada.Strings.Unbounded; type Facelet is record Root : ASF.Views.Nodes.Tag_Node_Access; Path : Unbounded_String; File : Util.Strings.String_Access; Modify_Time : Ada.Calendar.Time; end record; -- Tag library map indexed on the library namespace. package Facelet_Maps is new Ada.Containers.Indefinite_Hashed_Maps (Key_Type => Unbounded_String, Element_Type => Facelet, Hash => Ada.Strings.Unbounded.Hash, Equivalent_Keys => "="); use Facelet_Maps; -- Lock for accessing the shared cache protected type RW_Lock is entry Read; procedure Release_Read; entry Write; procedure Release_Write; private Readable : Boolean := True; Reader_Count : Natural := 0; end RW_Lock; type Facelet_Factory is new Ada.Finalization.Limited_Controlled with record Paths : Unbounded_String := To_Unbounded_String (""); Lock : RW_Lock; Map : Facelet_Maps.Map; Path_Map : Util.Strings.String_Map.Map; -- The component factory Factory : aliased ASF.Factory.Component_Factory; -- Whether the unknown tags are escaped using XML escape rules. Escape_Unknown_Tags : Boolean := True; -- Whether white spaces can be ignored. Ignore_White_Spaces : Boolean := True; -- Whether empty lines should be ignored (when white spaces are kept). Ignore_Empty_Lines : Boolean := True; end record; -- Free the storage held by the factory cache. overriding procedure Finalize (Factory : in out Facelet_Factory); end ASF.Views.Facelets;
----------------------------------------------------------------------- -- asf-views-facelets -- Facelets representation and management -- 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 Ada.Calendar; with Ada.Strings.Unbounded; with Ada.Containers.Indefinite_Hashed_Maps; with Ada.Strings.Unbounded.Hash; with ASF.Views.Nodes; with ASF.Contexts.Facelets; with ASF.Factory; with ASF.Components; with Util.Strings; with Ada.Finalization; -- The <b>ASF.Views.Facelets</b> package contains the facelet factory -- responsible for getting the facelet tree from a facelet name. -- The facelets (or *.xhtml) files are loaded by the reader to form -- a tag node tree which is cached by the factory. The facelet factory -- is shared by multiple requests and threads. package ASF.Views.Facelets is type Facelet is private; type Facelet_Access is access all Facelet; -- Returns True if the facelet is null/empty. function Is_Null (F : Facelet) return Boolean; -- ------------------------------ -- Facelet factory -- ------------------------------ -- The facelet factory allows to retrieve the node tree to build the -- component tree. The node tree can be shared by several component trees. -- The node tree is initialized from the <b>XHTML</b> view file. It is put -- in a cache to avoid loading and parsing the file several times. type Facelet_Factory is limited private; -- Get the facelet identified by the given name. If the facelet is already -- loaded, the cached value is returned. The facelet file is searched in -- a set of directories configured in the facelet factory. procedure Find_Facelet (Factory : in out Facelet_Factory; Name : in String; Context : in ASF.Contexts.Facelets.Facelet_Context'Class; Result : out Facelet); -- Create the component tree from the facelet view. procedure Build_View (View : in Facelet; Context : in out ASF.Contexts.Facelets.Facelet_Context'Class; Root : in ASF.Components.UIComponent_Access); -- Initialize the facelet factory. -- Set the search directories for facelet files. -- Set the ignore white space configuration when reading XHTML files. -- Set the ignore empty lines configuration when reading XHTML files. -- Set the escape unknown tags configuration when reading XHTML files. procedure Initialize (Factory : in out Facelet_Factory; Paths : in String; Ignore_White_Spaces : in Boolean; Ignore_Empty_Lines : in Boolean; Escape_Unknown_Tags : in Boolean); -- Find the facelet file in one of the facelet directories. -- Returns the path to be used for reading the facelet file. function Find_Facelet_Path (Factory : Facelet_Factory; Name : String) return String; -- Register the component factory bindings in the facelet factory. procedure Register (Factory : in out Facelet_Factory; Bindings : in ASF.Factory.Factory_Bindings_Access); -- Register a module and directory where the module files are stored. procedure Register_Module (Factory : in out Facelet_Factory; Name : in String; Paths : in String); -- Clear the facelet cache procedure Clear_Cache (Factory : in out Facelet_Factory); private use Ada.Strings.Unbounded; type Facelet is record Root : ASF.Views.Nodes.Tag_Node_Access; Path : Unbounded_String; File : String_Access; Modify_Time : Ada.Calendar.Time; end record; -- Tag library map indexed on the library namespace. package Facelet_Maps is new Ada.Containers.Indefinite_Hashed_Maps (Key_Type => Unbounded_String, Element_Type => Facelet, Hash => Ada.Strings.Unbounded.Hash, Equivalent_Keys => "="); use Facelet_Maps; -- Lock for accessing the shared cache protected type RW_Lock is entry Read; procedure Release_Read; entry Write; procedure Release_Write; private Readable : Boolean := True; Reader_Count : Natural := 0; end RW_Lock; type Facelet_Factory is new Ada.Finalization.Limited_Controlled with record Paths : Unbounded_String := To_Unbounded_String (""); Lock : RW_Lock; Map : Facelet_Maps.Map; Path_Map : Util.Strings.String_Map.Map; -- The component factory Factory : aliased ASF.Factory.Component_Factory; -- Whether the unknown tags are escaped using XML escape rules. Escape_Unknown_Tags : Boolean := True; -- Whether white spaces can be ignored. Ignore_White_Spaces : Boolean := True; -- Whether empty lines should be ignored (when white spaces are kept). Ignore_Empty_Lines : Boolean := True; end record; -- Free the storage held by the factory cache. overriding procedure Finalize (Factory : in out Facelet_Factory); end ASF.Views.Facelets;
Use Ada String_Access
Use Ada String_Access
Ada
apache-2.0
Letractively/ada-asf,Letractively/ada-asf,Letractively/ada-asf
035b413422a436f0ea116faa02d8049ab63c5532
mat/src/mat-readers-marshaller.adb
mat/src/mat-readers-marshaller.adb
----------------------------------------------------------------------- -- Ipc -- Ipc channel between profiler tool and application -- -- Copyright (C) 2014 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Interfaces; with System; use System; with System.Address_To_Access_Conversions; with System.Storage_Elements; with Util.Log.Loggers; with Interfaces; use Interfaces; package body MAT.Readers.Marshaller is use System.Storage_Elements; -- The logger Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("MAT.Readers.Marshaller"); package Uint8_Access is new System.Address_To_Access_Conversions (MAT.Types.Uint8); package Uint32_Access is new System.Address_To_Access_Conversions (MAT.Types.Uint32); function Get_Raw_Uint32 (Buf : System.Address) return MAT.Types.Uint32 is use Uint32_Access; P : constant Object_Pointer := To_Pointer (Buf); begin return P.all; end Get_Raw_Uint32; -- ------------------------------ -- Get an 8-bit value from the buffer. -- ------------------------------ function Get_Uint8 (Buffer : in Buffer_Ptr) return MAT.Types.Uint8 is use Uint8_Access; P : constant Object_Pointer := To_Pointer (Buffer.Current); begin if Buffer.Size = 0 then Log.Error ("Not enough data to get a uint8"); raise Buffer_Underflow_Error; end if; Buffer.Size := Buffer.Size - 1; Buffer.Current := Buffer.Current + Storage_Offset (1); return P.all; end Get_Uint8; -- ------------------------------ -- Get a 16-bit value either from big-endian or little endian. -- ------------------------------ function Get_Uint16 (Buffer : in Buffer_Ptr) return MAT.Types.Uint16 is use Uint8_Access; High : Object_Pointer; Low : Object_Pointer; begin if Buffer.Size <= 1 then Log.Error ("Not enough data to get a uint16"); raise Buffer_Underflow_Error; end if; if Buffer.Endian = LITTLE_ENDIAN then Low := To_Pointer (Buffer.Current); High := To_Pointer (Buffer.Current + Storage_Offset (1)); else High := To_Pointer (Buffer.Current); Low := To_Pointer (Buffer.Current + Storage_Offset (1)); end if; Buffer.Size := Buffer.Size - 2; Buffer.Current := Buffer.Current + Storage_Offset (2); return MAT.Types.Uint16 (High.all) * 256 + MAT.Types.Uint16 (Low.all); end Get_Uint16; -- ------------------------------ -- Get a 32-bit value either from big-endian or little endian. -- ------------------------------ function Get_Uint32 (Buffer : in Buffer_Ptr) return MAT.Types.Uint32 is use Uint32_Access; Low, High : MAT.Types.Uint16; begin if Buffer.Size < 4 then Log.Error ("Not enough data to get a uint32"); raise Buffer_Underflow_Error; end if; if Buffer.Endian = LITTLE_ENDIAN then Low := Get_Uint16 (Buffer); High := Get_Uint16 (Buffer); else High := Get_Uint16 (Buffer); Low := Get_Uint16 (Buffer); end if; return Interfaces.Shift_Left (MAT.Types.Uint32 (High), 16) + MAT.Types.Uint32 (Low); end Get_Uint32; function Get_Uint64 (Buffer : in Buffer_Ptr) return MAT.Types.Uint64 is Val : constant MAT.Types.Uint64 := MAT.Types.Uint64 (Get_Uint32 (Buffer)); begin return Val + MAT.Types.Uint64 (Get_Uint32 (Buffer)) * 2**32; end Get_Uint64; function Get_Target_Value (Msg : in Buffer_Ptr; Kind : in MAT.Events.Attribute_Type) return Target_Type is begin case Kind is when MAT.Events.T_UINT8 => return Target_Type (Get_Uint8 (Msg)); when MAT.Events.T_UINT16 => return Target_Type (Get_Uint16 (Msg)); when MAT.Events.T_UINT32 => return Target_Type (Get_Uint32 (Msg)); when MAT.Events.T_UINT64 => return Target_Type (Get_Uint64 (Msg)); when others => Log.Error ("Invalid attribute type {0}", MAT.Events.Attribute_Type'Image (Kind)); return 0; end case; end Get_Target_Value; -- ------------------------------ -- Extract a string from the buffer. The string starts with a byte that -- indicates the string length. -- ------------------------------ function Get_String (Buffer : in Buffer_Ptr) return String is Len : constant MAT.Types.Uint8 := Get_Uint8 (Buffer); Result : String (1 .. Natural (Len)); begin for I in Result'Range loop Result (I) := Character'Val (Get_Uint8 (Buffer)); end loop; return Result; end Get_String; -- ------------------------------ -- Extract a string from the buffer. The string starts with a byte that -- indicates the string length. -- ------------------------------ function Get_String (Msg : in Buffer_Ptr) return Ada.Strings.Unbounded.Unbounded_String is begin return Ada.Strings.Unbounded.To_Unbounded_String (Get_String (Msg)); end Get_String; -- ------------------------------ -- Skip the given number of bytes from the message. -- ------------------------------ procedure Skip (Buffer : in Buffer_Ptr; Size : in Natural) is begin Buffer.Size := Buffer.Size - Size; Buffer.Current := Buffer.Current + Storage_Offset (Size); end Skip; function Get_Target_Size (Msg : in Buffer_Ptr; Kind : in MAT.Events.Attribute_Type) return MAT.Types.Target_Size is function Get_Value is new Get_Target_Value (MAT.Types.Target_Size); begin return Get_Value (Msg, Kind); end Get_Target_Size; function Get_Target_Addr (Msg : in Buffer_Ptr; Kind : in MAT.Events.Attribute_Type) return MAT.Types.Target_Addr is function Get_Value is new Get_Target_Value (MAT.Types.Target_Addr); begin return Get_Value (Msg, Kind); end Get_Target_Addr; function Get_Target_Uint32 (Msg : in Buffer_Ptr; Kind : in MAT.Events.Attribute_Type) return MAT.Types.Uint32 is function Get_Value is new Get_Target_Value (MAT.Types.Target_Addr); begin return Get_Value (Msg, Kind); end Get_Target_Uint32; end MAT.Readers.Marshaller;
----------------------------------------------------------------------- -- Ipc -- Ipc channel between profiler tool and application -- -- Copyright (C) 2014 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Interfaces; with System; use System; with System.Address_To_Access_Conversions; with System.Storage_Elements; with Util.Log.Loggers; with Interfaces; use Interfaces; package body MAT.Readers.Marshaller is use System.Storage_Elements; -- The logger Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("MAT.Readers.Marshaller"); package Uint8_Access is new System.Address_To_Access_Conversions (MAT.Types.Uint8); package Uint32_Access is new System.Address_To_Access_Conversions (MAT.Types.Uint32); function Get_Raw_Uint32 (Buf : System.Address) return MAT.Types.Uint32 is use Uint32_Access; P : constant Object_Pointer := To_Pointer (Buf); begin return P.all; end Get_Raw_Uint32; -- ------------------------------ -- Get an 8-bit value from the buffer. -- ------------------------------ function Get_Uint8 (Buffer : in Buffer_Ptr) return MAT.Types.Uint8 is use Uint8_Access; P : constant Object_Pointer := To_Pointer (Buffer.Current); begin if Buffer.Size = 0 then Log.Error ("Not enough data to get a uint8"); raise Buffer_Underflow_Error; end if; Buffer.Size := Buffer.Size - 1; Buffer.Current := Buffer.Current + Storage_Offset (1); return P.all; end Get_Uint8; -- ------------------------------ -- Get a 16-bit value either from big-endian or little endian. -- ------------------------------ function Get_Uint16 (Buffer : in Buffer_Ptr) return MAT.Types.Uint16 is use Uint8_Access; High : Object_Pointer; Low : Object_Pointer; begin if Buffer.Size <= 1 then Log.Error ("Not enough data to get a uint16"); raise Buffer_Underflow_Error; end if; if Buffer.Endian = LITTLE_ENDIAN then Low := To_Pointer (Buffer.Current); High := To_Pointer (Buffer.Current + Storage_Offset (1)); else High := To_Pointer (Buffer.Current); Low := To_Pointer (Buffer.Current + Storage_Offset (1)); end if; Buffer.Size := Buffer.Size - 2; Buffer.Current := Buffer.Current + Storage_Offset (2); return MAT.Types.Uint16 (High.all) * 256 + MAT.Types.Uint16 (Low.all); end Get_Uint16; -- ------------------------------ -- Get a 32-bit value either from big-endian or little endian. -- ------------------------------ function Get_Uint32 (Buffer : in Buffer_Ptr) return MAT.Types.Uint32 is use Uint32_Access; Low, High : MAT.Types.Uint16; begin if Buffer.Size < 4 then Log.Error ("Not enough data to get a uint32"); raise Buffer_Underflow_Error; end if; if Buffer.Endian = LITTLE_ENDIAN then Low := Get_Uint16 (Buffer); High := Get_Uint16 (Buffer); else High := Get_Uint16 (Buffer); Low := Get_Uint16 (Buffer); end if; return Interfaces.Shift_Left (MAT.Types.Uint32 (High), 16) + MAT.Types.Uint32 (Low); end Get_Uint32; -- ------------------------------ -- Get a 64-bit value either from big-endian or little endian. -- ------------------------------ function Get_Uint64 (Buffer : in Buffer_Ptr) return MAT.Types.Uint64 is Low : MAT.Types.Uint32; High : MAT.Types.Uint32; begin if Buffer.Endian = LITTLE_ENDIAN then Low := Get_Uint32 (Buffer); High := Get_Uint32 (Buffer); else High := Get_Uint32 (Buffer); Low := Get_Uint32 (Buffer); end if; return Interfaces.Shift_Left (MAT.Types.Uint64 (High), 32) + MAT.Types.Uint64 (Low); end Get_Uint64; function Get_Target_Value (Msg : in Buffer_Ptr; Kind : in MAT.Events.Attribute_Type) return Target_Type is begin case Kind is when MAT.Events.T_UINT8 => return Target_Type (Get_Uint8 (Msg)); when MAT.Events.T_UINT16 => return Target_Type (Get_Uint16 (Msg)); when MAT.Events.T_UINT32 => return Target_Type (Get_Uint32 (Msg)); when MAT.Events.T_UINT64 => return Target_Type (Get_Uint64 (Msg)); when others => Log.Error ("Invalid attribute type {0}", MAT.Events.Attribute_Type'Image (Kind)); return 0; end case; end Get_Target_Value; -- ------------------------------ -- Extract a string from the buffer. The string starts with a byte that -- indicates the string length. -- ------------------------------ function Get_String (Buffer : in Buffer_Ptr) return String is Len : constant MAT.Types.Uint8 := Get_Uint8 (Buffer); Result : String (1 .. Natural (Len)); begin for I in Result'Range loop Result (I) := Character'Val (Get_Uint8 (Buffer)); end loop; return Result; end Get_String; -- ------------------------------ -- Extract a string from the buffer. The string starts with a byte that -- indicates the string length. -- ------------------------------ function Get_String (Msg : in Buffer_Ptr) return Ada.Strings.Unbounded.Unbounded_String is begin return Ada.Strings.Unbounded.To_Unbounded_String (Get_String (Msg)); end Get_String; -- ------------------------------ -- Skip the given number of bytes from the message. -- ------------------------------ procedure Skip (Buffer : in Buffer_Ptr; Size : in Natural) is begin Buffer.Size := Buffer.Size - Size; Buffer.Current := Buffer.Current + Storage_Offset (Size); end Skip; function Get_Target_Size (Msg : in Buffer_Ptr; Kind : in MAT.Events.Attribute_Type) return MAT.Types.Target_Size is function Get_Value is new Get_Target_Value (MAT.Types.Target_Size); begin return Get_Value (Msg, Kind); end Get_Target_Size; function Get_Target_Addr (Msg : in Buffer_Ptr; Kind : in MAT.Events.Attribute_Type) return MAT.Types.Target_Addr is function Get_Value is new Get_Target_Value (MAT.Types.Target_Addr); begin return Get_Value (Msg, Kind); end Get_Target_Addr; function Get_Target_Uint32 (Msg : in Buffer_Ptr; Kind : in MAT.Events.Attribute_Type) return MAT.Types.Uint32 is function Get_Value is new Get_Target_Value (MAT.Types.Target_Addr); begin return Get_Value (Msg, Kind); end Get_Target_Uint32; end MAT.Readers.Marshaller;
Fix Get_Uint64 to support big and little endian formats
Fix Get_Uint64 to support big and little endian formats
Ada
apache-2.0
stcarrez/mat,stcarrez/mat,stcarrez/mat
4138a351d779ee99524d347448c665c120630812
awa/plugins/awa-comments/src/awa-comments-services.adb
awa/plugins/awa-comments/src/awa-comments-services.adb
----------------------------------------------------------------------- -- awa-comments-logic -- Comments management -- Copyright (C) 2009, 2010, 2011 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with AWA.Services.Contexts; with ADO.Sessions; with ADO.Sessions.Entities; with Ada.Calendar; with Util.Log.Loggers; package body AWA.Comments.Services is use Util.Log; use ADO.Sessions; use AWA.Services; Log : constant Loggers.Logger := Loggers.Create ("AWA.Comments.Services"); -- ------------------------------ -- Create a comment associated with the given database entity. -- The user must have permission to add comments on the given entity. -- ------------------------------ procedure Create_Comment (Model : in Comment_Service; Entity : in ADO.Objects.Object_Key; Message : in String; User : in AWA.Users.Models.User_Ref'Class; Result : out 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); Comment : Comment_Ref; Entity_Id : constant ADO.Identifier := ADO.Objects.Get_Value (Entity); begin Log.Info ("Create comment for user {0}", String'(User.Get_Name)); -- -- select from asset inner join acl -- on asset.collection_id = acl.entity_id and acl.entity_type = :entity_type -- where asset.id = :entity_id and acl.user_id = :user_id -- AWA.Permissions.Module.Check (Entity => Entity, Permission => CREATE_COMMENT); Ctx.Start; Comment.Set_Message (Message); Comment.Set_Entity_Id (Entity_Id); Comment.Set_Entity_Type (ADO.Sessions.Entities.Find_Entity_Type (DB, Entity)); Comment.Set_User (User); Comment.Set_Date (Ada.Calendar.Clock); Comment.Save (DB); Ctx.Commit; Result := Comment.Get_Id; Log.Info ("Comment {0} created", ADO.Identifier'Image (Result)); end Create_Comment; procedure Find_Comment (Model : in Comment_Service; Id : in ADO.Identifier; Comment : in out Comment_Ref'Class) is begin null; end Find_Comment; -- ------------------------------ -- Delete the comment identified by the given identifier. -- ------------------------------ procedure Delete_Comment (Model : in Comment_Service; 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); Comment : Comment_Ref; begin Log.Info ("Delete comment {0}", ADO.Identifier'Image (Id)); -- AWA.Permissions.Module.Check (Entity => Entity, Permission => CREATE_COMMENT); Ctx.Start; Comment.Set_Id (Id); Comment.Delete (DB); Ctx.Commit; end Delete_Comment; end AWA.Comments.Services;
----------------------------------------------------------------------- -- awa-comments-logic -- Comments management -- 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 AWA.Services.Contexts; with ADO.Sessions; with ADO.Sessions.Entities; with Ada.Calendar; with Util.Log.Loggers; package body AWA.Comments.Services is use Util.Log; use ADO.Sessions; use AWA.Services; Log : constant Loggers.Logger := Loggers.Create ("AWA.Comments.Services"); -- ------------------------------ -- Create a comment associated with the given database entity. -- The user must have permission to add comments on the given entity. -- ------------------------------ procedure Create_Comment (Model : in Comment_Service; Entity : in ADO.Objects.Object_Key; Message : in String; User : in AWA.Users.Models.User_Ref'Class; Result : out 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); Comment : Comment_Ref; Entity_Id : constant ADO.Identifier := ADO.Objects.Get_Value (Entity); begin Log.Info ("Create comment for user {0}", String'(User.Get_Name)); -- -- select from asset inner join acl -- on asset.collection_id = acl.entity_id and acl.entity_type = :entity_type -- where asset.id = :entity_id and acl.user_id = :user_id -- AWA.Permissions.Module.Check (Entity => Entity, Permission => CREATE_COMMENT); Ctx.Start; Comment.Set_Message (Message); Comment.Set_Entity_Id (Entity_Id); Comment.Set_Entity_Type (ADO.Sessions.Entities.Find_Entity_Type (DB, Entity)); Comment.Set_Author (User); Comment.Set_Date (Ada.Calendar.Clock); Comment.Save (DB); Ctx.Commit; Result := Comment.Get_Id; Log.Info ("Comment {0} created", ADO.Identifier'Image (Result)); end Create_Comment; procedure Find_Comment (Model : in Comment_Service; Id : in ADO.Identifier; Comment : in out Comment_Ref'Class) is begin null; end Find_Comment; -- ------------------------------ -- Delete the comment identified by the given identifier. -- ------------------------------ procedure Delete_Comment (Model : in Comment_Service; 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); Comment : Comment_Ref; begin Log.Info ("Delete comment {0}", ADO.Identifier'Image (Id)); -- AWA.Permissions.Module.Check (Entity => Entity, Permission => CREATE_COMMENT); Ctx.Start; Comment.Set_Id (Id); Comment.Delete (DB); Ctx.Commit; end Delete_Comment; end AWA.Comments.Services;
Update the implementation according to the UML model
Update the implementation according to the UML model
Ada
apache-2.0
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
a391e849fbe3e92e85381031ba8d3db00751c326
awa/plugins/awa-blogs/src/awa-blogs-beans.ads
awa/plugins/awa-blogs/src/awa-blogs-beans.ads
----------------------------------------------------------------------- -- awa-blogs-beans -- Beans for blog module -- Copyright (C) 2011, 2012, 2013, 2014, 2015 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Strings.Unbounded; with Util.Beans.Basic; with Util.Beans.Objects; with ADO; with ADO.Objects; with AWA.Blogs.Modules; with AWA.Blogs.Models; with AWA.Tags.Beans; with AWA.Counters.Beans; -- == Blog Beans == -- Several bean types are provided to represent and manage the blogs and their posts. -- The blog module registers the bean constructors when it is initialized. -- To use them, one must declare a bean definition in the application XML configuration. package AWA.Blogs.Beans is -- Attributes exposed by <b>Post_Bean</b> BLOG_ID_ATTR : constant String := "blogId"; POST_ID_ATTR : constant String := "id"; POST_UID_ATTR : constant String := "uid"; POST_TITLE_ATTR : constant String := "title"; POST_TEXT_ATTR : constant String := "text"; POST_URI_ATTR : constant String := "uri"; POST_STATUS_ATTR : constant String := "status"; POST_USERNAME_ATTR : constant String := "username"; POST_TAG_ATTR : constant String := "tags"; POST_ALLOW_COMMENTS_ATTR : constant String := "allow_comments"; COUNTER_ATTR : constant String := "counter"; -- ------------------------------ -- Blog Bean -- ------------------------------ -- The <b>Blog_Bean</b> holds the information about the current blog. -- It allows to create the blog as well as update its primary title. type Blog_Bean is new AWA.Blogs.Models.Blog_Bean with record Module : AWA.Blogs.Modules.Blog_Module_Access := null; end record; type Blog_Bean_Access is access all Blog_Bean'Class; -- Get the value identified by the name. overriding function Get_Value (From : in Blog_Bean; Name : in String) return Util.Beans.Objects.Object; -- Create a new blog. overriding procedure Create (Bean : in out Blog_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String); -- Create the Blog_Bean bean instance. function Create_Blog_Bean (Module : in AWA.Blogs.Modules.Blog_Module_Access) return Util.Beans.Basic.Readonly_Bean_Access; -- ------------------------------ -- Post Bean -- ------------------------------ -- The <b>Post_Bean</b> is used to create or update a post associated with a blog. type Post_Bean is new AWA.Blogs.Models.Post_Bean with record Module : AWA.Blogs.Modules.Blog_Module_Access := null; Blog_Id : ADO.Identifier; -- List of tags associated with the post. Tags : aliased AWA.Tags.Beans.Tag_List_Bean; Tags_Bean : Util.Beans.Basic.Readonly_Bean_Access; -- The read post counter associated with the post. Counter : aliased AWA.Counters.Beans.Counter_Bean (Of_Type => ADO.Objects.KEY_INTEGER, Of_Class => Models.POST_TABLE); Counter_Bean : Util.Beans.Basic.Readonly_Bean_Access; end record; type Post_Bean_Access is access all Post_Bean'Class; -- Get the value identified by the name. overriding function Get_Value (From : in Post_Bean; Name : in String) return Util.Beans.Objects.Object; -- Set the value identified by the name. overriding procedure Set_Value (From : in out Post_Bean; Name : in String; Value : in Util.Beans.Objects.Object); -- Load the post. procedure Load_Post (Post : in out Post_Bean; Id : in ADO.Identifier); -- Create or save the post. overriding procedure Save (Bean : in out Post_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String); -- Delete a post. overriding procedure Delete (Bean : in out Post_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String); -- Load the post. overriding procedure Load (Bean : in out Post_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String); -- Create the Post_Bean bean instance. function Create_Post_Bean (Module : in AWA.Blogs.Modules.Blog_Module_Access) return Util.Beans.Basic.Readonly_Bean_Access; -- ------------------------------ -- Post List Bean -- ------------------------------ -- The <b>Post_List_Bean</b> gives a list of visible posts to be displayed to users. -- The list can be filtered by a given tag. The list pagination is supported. type Post_List_Bean is new AWA.Blogs.Models.Post_List_Bean with record Posts : aliased AWA.Blogs.Models.Post_Info_List_Bean; Service : Modules.Blog_Module_Access := null; Tags : AWA.Tags.Beans.Entity_Tag_Map; Posts_Bean : AWA.Blogs.Models.Post_Info_List_Bean_Access; -- The read post counter associated with the post. Counter : aliased AWA.Counters.Beans.Counter_Bean (Of_Type => ADO.Objects.KEY_INTEGER, Of_Class => Models.POST_TABLE); Counter_Bean : AWA.Counters.Beans.Counter_Bean_Access; end record; type Post_List_Bean_Access is access all Post_List_Bean'Class; -- Get the value identified by the name. overriding function Get_Value (From : in Post_List_Bean; Name : in String) return Util.Beans.Objects.Object; -- Set the value identified by the name. overriding procedure Set_Value (From : in out Post_List_Bean; Name : in String; Value : in Util.Beans.Objects.Object); overriding procedure Load (From : in out Post_List_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String); -- Load the list of posts. If a tag was set, filter the list of posts with the tag. procedure Load_List (Into : in out Post_List_Bean); -- Create the Post_List_Bean bean instance. function Create_Post_List_Bean (Module : in AWA.Blogs.Modules.Blog_Module_Access) return Util.Beans.Basic.Readonly_Bean_Access; -- Get a select item list which contains a list of post status. function Create_Status_List (Module : in AWA.Blogs.Modules.Blog_Module_Access) return Util.Beans.Basic.Readonly_Bean_Access; type Init_Flag is (INIT_BLOG_LIST, INIT_POST_LIST, INIT_COMMENT_LIST); type Init_Map is array (Init_Flag) of Boolean; -- ------------------------------ -- Admin List Bean -- ------------------------------ -- The <b>Blog_Admin_Bean</b> is used for the administration of a blog. It gives the -- list of posts that are created, published or not. type Blog_Admin_Bean is new Util.Beans.Basic.Bean with record Module : AWA.Blogs.Modules.Blog_Module_Access := null; -- The blog identifier. Blog_Id : ADO.Identifier := ADO.NO_IDENTIFIER; -- List of blogs. Blog_List : aliased AWA.Blogs.Models.Blog_Info_List_Bean; Blog_List_Bean : AWA.Blogs.Models.Blog_Info_List_Bean_Access; -- List of posts. Post_List : aliased AWA.Blogs.Models.Admin_Post_Info_List_Bean; Post_List_Bean : AWA.Blogs.Models.Admin_Post_Info_List_Bean_Access; -- List of comments. Comment_List : aliased AWA.Blogs.Models.Comment_Info_List_Bean; Comment_List_Bean : AWA.Blogs.Models.Comment_Info_List_Bean_Access; -- Initialization flags. Init_Flags : aliased Init_Map := (others => False); Flags : access Init_Map; end record; type Blog_Admin_Bean_Access is access all Blog_Admin_Bean; -- Get the blog identifier. function Get_Blog_Id (List : in Blog_Admin_Bean) return ADO.Identifier; -- Load the posts associated with the current blog. procedure Load_Posts (List : in Blog_Admin_Bean); -- Load the comments associated with the current blog. procedure Load_Comments (List : in Blog_Admin_Bean); overriding function Get_Value (List : in Blog_Admin_Bean; Name : in String) return Util.Beans.Objects.Object; -- Set the value identified by the name. overriding procedure Set_Value (From : in out Blog_Admin_Bean; Name : in String; Value : in Util.Beans.Objects.Object); -- Load the list of blogs. procedure Load_Blogs (List : in Blog_Admin_Bean); -- Create the Blog_Admin_Bean bean instance. function Create_Blog_Admin_Bean (Module : in AWA.Blogs.Modules.Blog_Module_Access) return Util.Beans.Basic.Readonly_Bean_Access; end AWA.Blogs.Beans;
----------------------------------------------------------------------- -- awa-blogs-beans -- Beans for blog module -- Copyright (C) 2011, 2012, 2013, 2014, 2015, 2016 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Strings.Unbounded; with Util.Beans.Basic; with Util.Beans.Objects; with ADO; with ADO.Objects; with AWA.Blogs.Modules; with AWA.Blogs.Models; with AWA.Tags.Beans; with AWA.Counters.Beans; -- == Blog Beans == -- Several bean types are provided to represent and manage the blogs and their posts. -- The blog module registers the bean constructors when it is initialized. -- To use them, one must declare a bean definition in the application XML configuration. package AWA.Blogs.Beans is -- Attributes exposed by <b>Post_Bean</b> BLOG_ID_ATTR : constant String := "blogId"; POST_ID_ATTR : constant String := "id"; POST_UID_ATTR : constant String := "uid"; POST_TITLE_ATTR : constant String := "title"; POST_TEXT_ATTR : constant String := "text"; POST_URI_ATTR : constant String := "uri"; POST_STATUS_ATTR : constant String := "status"; POST_USERNAME_ATTR : constant String := "username"; POST_TAG_ATTR : constant String := "tags"; POST_ALLOW_COMMENTS_ATTR : constant String := "allow_comments"; COUNTER_ATTR : constant String := "counter"; -- ------------------------------ -- Blog Bean -- ------------------------------ -- The <b>Blog_Bean</b> holds the information about the current blog. -- It allows to create the blog as well as update its primary title. type Blog_Bean is new AWA.Blogs.Models.Blog_Bean with record Module : AWA.Blogs.Modules.Blog_Module_Access := null; end record; type Blog_Bean_Access is access all Blog_Bean'Class; -- Get the value identified by the name. overriding function Get_Value (From : in Blog_Bean; Name : in String) return Util.Beans.Objects.Object; -- Create a new blog. overriding procedure Create (Bean : in out Blog_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String); -- Create the Blog_Bean bean instance. function Create_Blog_Bean (Module : in AWA.Blogs.Modules.Blog_Module_Access) return Util.Beans.Basic.Readonly_Bean_Access; -- ------------------------------ -- Post Bean -- ------------------------------ -- The <b>Post_Bean</b> is used to create or update a post associated with a blog. type Post_Bean is new AWA.Blogs.Models.Post_Bean with record Module : AWA.Blogs.Modules.Blog_Module_Access := null; Blog_Id : ADO.Identifier; -- List of tags associated with the post. Tags : aliased AWA.Tags.Beans.Tag_List_Bean; Tags_Bean : Util.Beans.Basic.Readonly_Bean_Access; -- The read post counter associated with the post. Counter : aliased AWA.Counters.Beans.Counter_Bean (Of_Type => ADO.Objects.KEY_INTEGER, Of_Class => Models.POST_TABLE); Counter_Bean : Util.Beans.Basic.Readonly_Bean_Access; end record; type Post_Bean_Access is access all Post_Bean'Class; -- Get the value identified by the name. overriding function Get_Value (From : in Post_Bean; Name : in String) return Util.Beans.Objects.Object; -- Set the value identified by the name. overriding procedure Set_Value (From : in out Post_Bean; Name : in String; Value : in Util.Beans.Objects.Object); -- Load the post. procedure Load_Post (Post : in out Post_Bean; Id : in ADO.Identifier); -- Create or save the post. overriding procedure Save (Bean : in out Post_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String); -- Delete a post. overriding procedure Delete (Bean : in out Post_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String); -- Load the post. overriding procedure Load (Bean : in out Post_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String); -- Create the Post_Bean bean instance. function Create_Post_Bean (Module : in AWA.Blogs.Modules.Blog_Module_Access) return Util.Beans.Basic.Readonly_Bean_Access; -- ------------------------------ -- Post List Bean -- ------------------------------ -- The <b>Post_List_Bean</b> gives a list of visible posts to be displayed to users. -- The list can be filtered by a given tag. The list pagination is supported. type Post_List_Bean is new AWA.Blogs.Models.Post_List_Bean with record Posts : aliased AWA.Blogs.Models.Post_Info_List_Bean; Service : Modules.Blog_Module_Access := null; Tags : AWA.Tags.Beans.Entity_Tag_Map; Posts_Bean : AWA.Blogs.Models.Post_Info_List_Bean_Access; -- The read post counter associated with the post. Counter : aliased AWA.Counters.Beans.Counter_Bean (Of_Type => ADO.Objects.KEY_INTEGER, Of_Class => Models.POST_TABLE); Counter_Bean : AWA.Counters.Beans.Counter_Bean_Access; end record; type Post_List_Bean_Access is access all Post_List_Bean'Class; -- Get the value identified by the name. overriding function Get_Value (From : in Post_List_Bean; Name : in String) return Util.Beans.Objects.Object; -- Set the value identified by the name. overriding procedure Set_Value (From : in out Post_List_Bean; Name : in String; Value : in Util.Beans.Objects.Object); overriding procedure Load (From : in out Post_List_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String); -- Load the list of posts. If a tag was set, filter the list of posts with the tag. procedure Load_List (Into : in out Post_List_Bean); -- Create the Post_List_Bean bean instance. function Create_Post_List_Bean (Module : in AWA.Blogs.Modules.Blog_Module_Access) return Util.Beans.Basic.Readonly_Bean_Access; -- Get a select item list which contains a list of post status. function Create_Status_List (Module : in AWA.Blogs.Modules.Blog_Module_Access) return Util.Beans.Basic.Readonly_Bean_Access; type Init_Flag is (INIT_BLOG_LIST, INIT_POST_LIST, INIT_COMMENT_LIST); type Init_Map is array (Init_Flag) of Boolean; -- ------------------------------ -- Admin List Bean -- ------------------------------ -- The <b>Blog_Admin_Bean</b> is used for the administration of a blog. It gives the -- list of posts that are created, published or not. type Blog_Admin_Bean is new Util.Beans.Basic.Bean with record Module : AWA.Blogs.Modules.Blog_Module_Access := null; -- The blog identifier. Blog_Id : ADO.Identifier := ADO.NO_IDENTIFIER; -- List of blogs. Blog_List : aliased AWA.Blogs.Models.Blog_Info_List_Bean; Blog_List_Bean : AWA.Blogs.Models.Blog_Info_List_Bean_Access; -- List of posts. Post_List : aliased AWA.Blogs.Models.Admin_Post_Info_List_Bean; Post_List_Bean : AWA.Blogs.Models.Admin_Post_Info_List_Bean_Access; -- List of comments. Comment_List : aliased AWA.Blogs.Models.Comment_Info_List_Bean; Comment_List_Bean : AWA.Blogs.Models.Comment_Info_List_Bean_Access; -- Initialization flags. Init_Flags : aliased Init_Map := (others => False); Flags : access Init_Map; end record; type Blog_Admin_Bean_Access is access all Blog_Admin_Bean; -- Get the blog identifier. function Get_Blog_Id (List : in Blog_Admin_Bean) return ADO.Identifier; -- Load the posts associated with the current blog. procedure Load_Posts (List : in Blog_Admin_Bean); -- Load the comments associated with the current blog. procedure Load_Comments (List : in Blog_Admin_Bean); overriding function Get_Value (List : in Blog_Admin_Bean; Name : in String) return Util.Beans.Objects.Object; -- Set the value identified by the name. overriding procedure Set_Value (From : in out Blog_Admin_Bean; Name : in String; Value : in Util.Beans.Objects.Object); -- Load the list of blogs. procedure Load_Blogs (List : in Blog_Admin_Bean); -- Create the Blog_Admin_Bean bean instance. function Create_Blog_Admin_Bean (Module : in AWA.Blogs.Modules.Blog_Module_Access) return Util.Beans.Basic.Readonly_Bean_Access; -- ------------------------------ -- Blog Statistics Bean -- ------------------------------ -- The <b>Blog_Stat_Bean</b> is used to report various statistics about the blog or some post. type Blog_Stat_Bean is new AWA.Blogs.Models.Stat_List_Bean with record Module : AWA.Blogs.Modules.Blog_Module_Access := null; Stats : aliased AWA.Blogs.Models.Month_Stat_Info_List_Bean; Stats_Bean : AWA.Blogs.Models.Month_Stat_Info_List_Bean_Access; end record; type Blog_Stat_Bean_Access is access all Blog_Stat_Bean; overriding function Get_Value (List : in Blog_Stat_Bean; Name : in String) return Util.Beans.Objects.Object; -- Set the value identified by the name. overriding procedure Set_Value (From : in out Blog_Stat_Bean; Name : in String; Value : in Util.Beans.Objects.Object); -- Load the statistics information. overriding procedure Load (List : in out Blog_Stat_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String); -- Create the Blog_Stat_Bean bean instance. function Create_Blog_Stat_Bean (Module : in AWA.Blogs.Modules.Blog_Module_Access) return Util.Beans.Basic.Readonly_Bean_Access; end AWA.Blogs.Beans;
Declare the Blog_Stat_Bean type with Get_Value, Set_Value, Load operation
Declare the Blog_Stat_Bean type with Get_Value, Set_Value, Load operation
Ada
apache-2.0
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
47aba57a4b6f7a2f230080fe434ed546df79baa2
regtests/security-random-tests.ads
regtests/security-random-tests.ads
----------------------------------------------------------------------- -- security-random-tests - Tests for random package -- Copyright (C) 2017 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Tests; package Security.Random.Tests is procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite); type Test is new Util.Tests.Test with null record; procedure Test_Generate (T : in out Test); end Security.Random.Tests;
----------------------------------------------------------------------- -- security-random-tests - Tests for random package -- Copyright (C) 2017, 2022 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Tests; package Security.Random.Tests is procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite); type Test is new Util.Tests.Test with null record; procedure Test_Generate (T : in out Test); procedure Test_Generate_String (T : in out Test); end Security.Random.Tests;
Declare Test_Generate_String procedure
Declare Test_Generate_String procedure
Ada
apache-2.0
stcarrez/ada-security
908188c4f0383c63f2cef20906b432345daf82f2
tools/druss-commands-devices.adb
tools/druss-commands-devices.adb
----------------------------------------------------------------------- -- druss-commands-devices -- Print information about the devices -- 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.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; 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 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_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 Command_Type; Name : in String; Args : in Argument_List'Class; Context : in out Context_Type) is pragma Unreferenced (Name); begin Command.Do_List (Args, Context); 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, "devices: Print information about the devices"); Console.Notice (N_HELP, "Usage: devices [options]"); Console.Notice (N_HELP, ""); end Help; end Druss.Commands.Devices;
----------------------------------------------------------------------- -- druss-commands-devices -- Print information about the devices -- 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.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 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_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); 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, "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;
Add a device selector to the do_List command List only the active, inactive or all the devices
Add a device selector to the do_List command List only the active, inactive or all the devices
Ada
apache-2.0
stcarrez/bbox-ada-api
0cf051566760d4106330630731097b4cf1de895d
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; -- ------------------------------ -- 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; -- ------------------------------ -- Find the position of the given character in the string starting at the given position. -- ------------------------------ function Index (Text : in Wiki.Strings.Wstring; Item : in Wiki.Strings.Wchar; From : in Positive) return Natural is Pos : Natural := From; begin while Pos <= Text'Last loop if Text (Pos) = Item then return Pos; end if; Pos := Pos + 1; end loop; return 0; end Index; 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_Or_Newline (Text (Pos)) loop Pos := Pos - 1; end loop; return Pos; end Trim_Spaces; -- ------------------------------ -- Find the position of the given character in the string starting at the given position. -- ------------------------------ function Index (Text : in Wiki.Strings.WString; Item : in Wiki.Strings.WChar; From : in Positive) return Natural is Pos : Natural := From; begin while Pos <= Text'Last loop if Text (Pos) = Item then return Pos; end if; Pos := Pos + 1; end loop; return 0; end Index; end Wiki.Helpers;
Fix to also trim newlines
Fix to also trim newlines
Ada
apache-2.0
stcarrez/ada-wiki,stcarrez/ada-wiki