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
9da8b4cd10df635cf0c6d412385ccbcea2d826e0
mat/src/gtk/mat-callbacks.adb
mat/src/gtk/mat-callbacks.adb
----------------------------------------------------------------------- -- mat-callbacks - Callbacks for Gtk -- 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 Glib.Main; with Gtk.Main; with Gtk.Widget; with Gtk.Label; with Util.Log.Loggers; package body MAT.Callbacks is -- The logger Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("MAT.Callbacks"); type Info is record Builder : access Gtkada.Builder.Gtkada_Builder_Record'Class; end record; package Timer_Callback is new Glib.Main.Generic_Sources (Info); Timer : Glib.Main.G_Source_Id; MemTotal : Natural := 1; function Refresh_Timeout (Data : in Info) return Boolean is Mem : constant Gtk.Label.Gtk_Label := Gtk.Label.Gtk_Label (Data.Builder.Get_Object ("memory_info")); begin Log.Info ("Timeout callback"); MemTotal := MemTotal + 10; Mem.Set_Label ("Memory " & Natural'Image (MemTotal)); return True; end Refresh_Timeout; -- ------------------------------ -- Initialize and register the callbacks. -- ------------------------------ procedure Initialize (Builder : in Gtkada.Builder.Gtkada_Builder) is Data : Info; begin Builder.Register_Handler (Handler_Name => "quit", Handler => MAT.Callbacks.On_Menu_Quit'Access); Builder.Register_Handler (Handler_Name => "about", Handler => MAT.Callbacks.On_Menu_About'Access); Builder.Register_Handler (Handler_Name => "close-about", Handler => MAT.Callbacks.On_Close_About'Access); Data.Builder := Builder; Timer := Timer_Callback.Timeout_Add (1000, Refresh_Timeout'Access, Data); end Initialize; -- ------------------------------ -- Callback executed when the "quit" action is executed from the menu. -- ------------------------------ procedure On_Menu_Quit (Object : access Gtkada.Builder.Gtkada_Builder_Record'Class) is begin Gtk.Main.Main_Quit; end On_Menu_Quit; -- ------------------------------ -- Callback executed when the "about" action is executed from the menu. -- ------------------------------ procedure On_Menu_About (Object : access Gtkada.Builder.Gtkada_Builder_Record'Class) is About : constant Gtk.Widget.Gtk_Widget := Gtk.Widget.Gtk_Widget (Object.Get_Object ("about")); begin About.Show; end On_Menu_About; -- ------------------------------ -- Callback executed when the "close-about" action is executed from the about box. -- ------------------------------ procedure On_Close_About (Object : access Gtkada.Builder.Gtkada_Builder_Record'Class) is About : constant Gtk.Widget.Gtk_Widget := Gtk.Widget.Gtk_Widget (Object.Get_Object ("about")); begin About.Hide; end On_Close_About; end MAT.Callbacks;
----------------------------------------------------------------------- -- mat-callbacks - Callbacks for Gtk -- 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 Glib.Main; with Gtk.Main; with Gtk.Widget; with Gtk.Label; with Util.Log.Loggers; package body MAT.Callbacks is -- The logger Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("MAT.Callbacks"); type Info is record Builder : access Gtkada.Builder.Gtkada_Builder_Record'Class; end record; package Timer_Callback is new Glib.Main.Generic_Sources (MAT.Targets.Gtkmat.Target_Type_Access); Timer : Glib.Main.G_Source_Id; MemTotal : Natural := 1; function Refresh_Timeout (Target : in MAT.Targets.Gtkmat.Target_Type_Access) return Boolean is begin Target.Refresh_Process; return True; end Refresh_Timeout; -- ------------------------------ -- Initialize and register the callbacks. -- ------------------------------ procedure Initialize (Target : in MAT.Targets.Gtkmat.Target_Type_Access; Builder : in Gtkada.Builder.Gtkada_Builder) is begin Builder.Register_Handler (Handler_Name => "quit", Handler => MAT.Callbacks.On_Menu_Quit'Access); Builder.Register_Handler (Handler_Name => "about", Handler => MAT.Callbacks.On_Menu_About'Access); Builder.Register_Handler (Handler_Name => "close-about", Handler => MAT.Callbacks.On_Close_About'Access); Timer := Timer_Callback.Timeout_Add (1000, Refresh_Timeout'Access, Target); end Initialize; -- ------------------------------ -- Callback executed when the "quit" action is executed from the menu. -- ------------------------------ procedure On_Menu_Quit (Object : access Gtkada.Builder.Gtkada_Builder_Record'Class) is begin Gtk.Main.Main_Quit; end On_Menu_Quit; -- ------------------------------ -- Callback executed when the "about" action is executed from the menu. -- ------------------------------ procedure On_Menu_About (Object : access Gtkada.Builder.Gtkada_Builder_Record'Class) is About : constant Gtk.Widget.Gtk_Widget := Gtk.Widget.Gtk_Widget (Object.Get_Object ("about")); begin About.Show; end On_Menu_About; -- ------------------------------ -- Callback executed when the "close-about" action is executed from the about box. -- ------------------------------ procedure On_Close_About (Object : access Gtkada.Builder.Gtkada_Builder_Record'Class) is About : constant Gtk.Widget.Gtk_Widget := Gtk.Widget.Gtk_Widget (Object.Get_Object ("about")); begin About.Hide; end On_Close_About; end MAT.Callbacks;
Update the refresh timeout operation to refresh the process information
Update the refresh timeout operation to refresh the process information
Ada
apache-2.0
stcarrez/mat,stcarrez/mat,stcarrez/mat
7ae9107d35db91c6ec16ae37e687b05a0c72ca7b
awa/plugins/awa-images/regtests/awa-images-services-tests.adb
awa/plugins/awa-images/regtests/awa-images-services-tests.adb
----------------------------------------------------------------------- -- awa-storages-services-tests -- Unit tests for storage service -- 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.Test_Caller; with Security.Contexts; with AWA.Services.Contexts; with AWA.Tests.Helpers.Users; with AWA.Images.Modules; package body AWA.Images.Services.Tests is use Util.Tests; use ADO; package Caller is new Util.Test_Caller (Test, "Images.Services"); procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is begin Caller.Add_Test (Suite, "Test AWA.Images.Create_Image", Test_Create_Image'Access); end Add_Tests; -- ------------------------------ -- Test creation of a storage object -- ------------------------------ procedure Test_Create_Image (T : in out Test) is Sec_Ctx : Security.Contexts.Security_Context; Context : AWA.Services.Contexts.Service_Context; Source : constant String := Util.Tests.Get_Path ("regtests/files/images/bast-12.jpg"); Thumb : constant String := Util.Tests.Get_Test_Path ("regtests/result/bast-12-thumb.jpg"); Width : Natural; Height : Natural; begin AWA.Tests.Helpers.Users.Login (Context, Sec_Ctx, "[email protected]"); T.Manager := AWA.Images.Modules.Get_Image_Manager; T.Manager.Create_Thumbnail (Source, Thumb, Width, Height); Util.Tests.Assert_Equals (T, 1720, Width, "Invalid image width"); Util.Tests.Assert_Equals (T, 1098, Height, "Invalid image height"); end Test_Create_Image; end AWA.Images.Services.Tests;
----------------------------------------------------------------------- -- awa-storages-services-tests -- Unit tests for storage service -- 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 Util.Test_Caller; with Security.Contexts; with AWA.Services.Contexts; with AWA.Tests.Helpers.Users; with AWA.Images.Modules; package body AWA.Images.Services.Tests is use Util.Tests; use ADO; package Caller is new Util.Test_Caller (Test, "Images.Services"); procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is begin Caller.Add_Test (Suite, "Test AWA.Images.Create_Image", Test_Create_Image'Access); end Add_Tests; -- ------------------------------ -- Test creation of a storage object -- ------------------------------ procedure Test_Create_Image (T : in out Test) is Sec_Ctx : Security.Contexts.Security_Context; Context : AWA.Services.Contexts.Service_Context; Source : constant String := Util.Tests.Get_Path ("regtests/files/images/bast-12.jpg"); Thumb : constant String := Util.Tests.Get_Test_Path ("regtests/result/bast-12-thumb.jpg"); Width : Natural := 64; Height : Natural := 64; begin AWA.Tests.Helpers.Users.Login (Context, Sec_Ctx, "[email protected]"); T.Manager := AWA.Images.Modules.Get_Image_Manager; T.Manager.Create_Thumbnail (Source, Thumb, Width, Height); Util.Tests.Assert_Equals (T, 1720, Width, "Invalid image width"); Util.Tests.Assert_Equals (T, 1098, Height, "Invalid image height"); end Test_Create_Image; end AWA.Images.Services.Tests;
Fix the thumbnail creation unit test
Fix the thumbnail creation unit test
Ada
apache-2.0
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
9b1118a384e009f58433dd0a01bd83980f4437ca
regtests/wiki-tests.adb
regtests/wiki-tests.adb
----------------------------------------------------------------------- -- Render Tests - Unit tests for AWA Wiki rendering -- Copyright (C) 2013, 2016 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Text_IO; with Ada.Directories; with Util.Measures; with Wiki.Render.Wiki; with Wiki.Render.Html; with Wiki.Render.Text; with Wiki.Filters.Html; with Wiki.Filters.TOC; with Wiki.Plugins.Templates; with Wiki.Streams.Text_IO; with Wiki.Streams.Html.Text_IO; with Wiki.Documents; with Wiki.Parsers; package body Wiki.Tests is use Ada.Strings.Unbounded; -- ------------------------------ -- Test rendering a wiki text in HTML or text. -- ------------------------------ procedure Test_Render (T : in out Test) is use Ada.Directories; Result_File : constant String := To_String (T.Result); Dir : constant String := Containing_Directory (Result_File); Doc : Wiki.Documents.Document; Engine : Wiki.Parsers.Parser; Toc_Filter : aliased Wiki.Filters.TOC.TOC_Filter; Html_Filter : aliased Wiki.Filters.Html.Html_Filter_Type; Template : aliased Wiki.Plugins.Templates.File_Template_Plugin; Input : aliased Wiki.Streams.Text_IO.File_Input_Stream; Output : aliased Wiki.Streams.Html.Text_IO.Html_File_Output_Stream; begin if not Exists (Dir) then Create_Path (Dir); end if; Input.Open (Path => To_String (T.File), Form => "WCEM=8"); Output.Create (Result_File, "WCEM=8"); Template.Set_Template_Path (Containing_Directory (To_String (T.File))); declare Time : Util.Measures.Stamp; begin Engine.Set_Syntax (T.Source); Engine.Set_Plugin_Factory (Template'Unchecked_Access); Engine.Add_Filter (Toc_Filter'Unchecked_Access); Engine.Add_Filter (Html_Filter'Unchecked_Access); Engine.Parse (Input'Unchecked_Access, Doc); Util.Measures.Report (Time, "Parse " & To_String (T.Name)); if T.Source = Wiki.SYNTAX_HTML then declare Renderer : aliased Wiki.Render.Wiki.Wiki_Renderer; begin Renderer.Set_Output_Stream (Output'Unchecked_Access, T.Format); Renderer.Render (Doc); Output.Close; Util.Measures.Report (Time, "Render Wiki " & To_String (T.Name)); end; elsif T.Is_Html then declare Renderer : aliased Wiki.Render.Html.Html_Renderer; begin Renderer.Set_Output_Stream (Output'Unchecked_Access); Renderer.Set_Render_TOC (True); Renderer.Render (Doc); Output.Close; Util.Measures.Report (Time, "Render HTML " & To_String (T.Name)); end; else declare Renderer : aliased Wiki.Render.Text.Text_Renderer; begin Renderer.Set_Output_Stream (Output'Unchecked_Access); Renderer.Render (Doc); Output.Close; Util.Measures.Report (Time, "Render Text " & To_String (T.Name)); end; end if; end; Input.Close; Util.Tests.Assert_Equal_Files (T => T, Expect => To_String (T.Expect), Test => Result_File, Message => "Render"); end Test_Render; -- ------------------------------ -- Test case name -- ------------------------------ overriding function Name (T : in Test) return Util.Tests.Message_String is begin if T.Source = Wiki.SYNTAX_HTML then return Util.Tests.Format ("Test IMPORT " & To_String (T.Name)); elsif T.Is_Html then return Util.Tests.Format ("Test HTML " & To_String (T.Name)); else return Util.Tests.Format ("Test TEXT " & To_String (T.Name)); end if; end Name; -- ------------------------------ -- Perform the test. -- ------------------------------ overriding procedure Run_Test (T : in out Test) is begin T.Test_Render; end Run_Test; procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is use Ada.Directories; procedure Add_Import_Tests; procedure Add_Wiki_Tests; function Create_Test (Name : in String; Path : in String; Format : in Wiki.Wiki_Syntax; Prefix : in String; Is_Html : in Boolean) return Test_Case_Access; Result_Dir : constant String := "regtests/result"; Expect_Dir : constant String := "regtests/expect"; Expect_Path : constant String := Util.Tests.Get_Path (Expect_Dir); Result_Path : constant String := Util.Tests.Get_Test_Path (Result_Dir); Search : Search_Type; Filter : constant Filter_Type := (others => True); Ent : Directory_Entry_Type; function Create_Test (Name : in String; Path : in String; Format : in Wiki.Wiki_Syntax; Prefix : in String; Is_Html : in Boolean) return Test_Case_Access is Tst : Test_Case_Access; begin Tst := new Test; Tst.Is_Html := Is_Html; Tst.Name := To_Unbounded_String (Name); Tst.File := To_Unbounded_String (Path); Tst.Expect := To_Unbounded_String (Expect_Path & Prefix & Name); Tst.Result := To_Unbounded_String (Result_Path & Prefix & Name); Tst.Format := Format; Tst.Source := Format; return Tst; end Create_Test; procedure Add_Wiki_Tests is Dir : constant String := "regtests/files/wiki"; Path : constant String := Util.Tests.Get_Path (Dir); begin if Kind (Path) /= Directory then Ada.Text_IO.Put_Line ("Cannot read test directory: " & Path); end if; Start_Search (Search, Directory => Path, Pattern => "*.*", Filter => Filter); while More_Entries (Search) loop Get_Next_Entry (Search, Ent); declare Simple : constant String := Simple_Name (Ent); Ext : constant String := Ada.Directories.Extension (Simple); Tst : Test_Case_Access; Format : Wiki.Wiki_Syntax; begin if Simple /= "." and then Simple /= ".." and then Simple /= ".svn" and then Simple (Simple'Last) /= '~' then if Ext = "wiki" then Format := Wiki.SYNTAX_GOOGLE; elsif Ext = "dotclear" then Format := Wiki.SYNTAX_DOTCLEAR; elsif Ext = "creole" then Format := Wiki.SYNTAX_CREOLE; elsif Ext = "phpbb" then Format := Wiki.SYNTAX_PHPBB; elsif Ext = "mediawiki" then Format := Wiki.SYNTAX_MEDIA_WIKI; else Format := Wiki.SYNTAX_MIX; end if; Tst := Create_Test (Simple, Path & "/" & Simple, Format, "/wiki-html/", True); Suite.Add_Test (Tst.all'Access); Tst := Create_Test (Simple, Path & "/" & Simple, Format, "/wiki-txt/", False); Suite.Add_Test (Tst.all'Access); end if; end; end loop; end Add_Wiki_Tests; procedure Add_Import_Tests is Dir : constant String := "regtests/files/html"; Path : constant String := Util.Tests.Get_Path (Dir); begin if Kind (Path) /= Directory then Ada.Text_IO.Put_Line ("Cannot read test directory: " & Path); end if; Start_Search (Search, Directory => Path, Pattern => "*.*", Filter => Filter); while More_Entries (Search) loop Get_Next_Entry (Search, Ent); declare Simple : constant String := Simple_Name (Ent); Name : constant String := Base_Name (Simple); Tst : Test_Case_Access; begin if Simple /= "." and then Simple /= ".." and then Simple /= ".svn" and then Simple (Simple'Last) /= '~' then for Syntax in Wiki.Wiki_Syntax'Range loop case Syntax is when Wiki.SYNTAX_CREOLE => Tst := Create_Test (Name & ".creole", Path & "/" & Simple, Syntax, "/wiki-import/", True); when Wiki.SYNTAX_DOTCLEAR => Tst := Create_Test (Name & ".dotclear", Path & "/" & Simple, Syntax, "/wiki-import/", True); when Wiki.SYNTAX_MEDIA_WIKI => Tst := Create_Test (Name & ".mediawiki", Path & "/" & Simple, Syntax, "/wiki-import/", True); when others => Tst := null; end case; if Tst /= null then Tst.Source := Wiki.SYNTAX_HTML; Suite.Add_Test (Tst.all'Access); end if; end loop; end if; end; end loop; end Add_Import_Tests; begin Add_Wiki_Tests; Add_Import_Tests; end Add_Tests; end Wiki.Tests;
----------------------------------------------------------------------- -- Render Tests - Unit tests for AWA Wiki rendering -- Copyright (C) 2013, 2016 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Text_IO; with Ada.Directories; with Util.Measures; with Wiki.Render.Wiki; with Wiki.Render.Html; with Wiki.Render.Text; with Wiki.Filters.Html; with Wiki.Filters.TOC; with Wiki.Plugins.Templates; with Wiki.Plugins.Conditions; with Wiki.Streams.Text_IO; with Wiki.Streams.Html.Text_IO; with Wiki.Documents; with Wiki.Parsers; package body Wiki.Tests is use Ada.Strings.Unbounded; -- ------------------------------ -- Test rendering a wiki text in HTML or text. -- ------------------------------ procedure Test_Render (T : in out Test) is use Ada.Directories; Result_File : constant String := To_String (T.Result); Dir : constant String := Containing_Directory (Result_File); Doc : Wiki.Documents.Document; Engine : Wiki.Parsers.Parser; Toc_Filter : aliased Wiki.Filters.TOC.TOC_Filter; Html_Filter : aliased Wiki.Filters.Html.Html_Filter_Type; Template : aliased Wiki.Plugins.Templates.File_Template_Plugin; Condition : aliased Wiki.Plugins.Conditions.Condition_Plugin; Input : aliased Wiki.Streams.Text_IO.File_Input_Stream; Output : aliased Wiki.Streams.Html.Text_IO.Html_File_Output_Stream; type Test_Factory is new Wiki.Plugins.Plugin_Factory with null record; -- Find a plugin knowing its name. overriding function Find (Factory : in Test_Factory; Name : in String) return Wiki.Plugins.Wiki_Plugin_Access; overriding function Find (Factory : in Test_Factory; Name : in String) return Wiki.Plugins.Wiki_Plugin_Access is pragma Unreferenced (Factory); begin if Name = "if" or Name = "else" or Name = "elsif" or Name = "end" then return Condition'Unchecked_Access; else return Template.Find (Name); end if; end Find; Local_Factory : aliased Test_Factory; begin if not Exists (Dir) then Create_Path (Dir); end if; Input.Open (Path => To_String (T.File), Form => "WCEM=8"); Output.Create (Result_File, "WCEM=8"); Template.Set_Template_Path (Containing_Directory (To_String (T.File))); Condition.Append ("public", ""); Condition.Append ("user", "admin"); declare Time : Util.Measures.Stamp; begin Engine.Set_Syntax (T.Source); Engine.Set_Plugin_Factory (Local_Factory'Unchecked_Access); Engine.Add_Filter (Toc_Filter'Unchecked_Access); Engine.Add_Filter (Html_Filter'Unchecked_Access); Engine.Parse (Input'Unchecked_Access, Doc); Util.Measures.Report (Time, "Parse " & To_String (T.Name)); if T.Source = Wiki.SYNTAX_HTML then declare Renderer : aliased Wiki.Render.Wiki.Wiki_Renderer; begin Renderer.Set_Output_Stream (Output'Unchecked_Access, T.Format); Renderer.Render (Doc); Output.Close; Util.Measures.Report (Time, "Render Wiki " & To_String (T.Name)); end; elsif T.Is_Html then declare Renderer : aliased Wiki.Render.Html.Html_Renderer; begin Renderer.Set_Output_Stream (Output'Unchecked_Access); Renderer.Set_Render_TOC (True); Renderer.Render (Doc); Output.Close; Util.Measures.Report (Time, "Render HTML " & To_String (T.Name)); end; else declare Renderer : aliased Wiki.Render.Text.Text_Renderer; begin Renderer.Set_Output_Stream (Output'Unchecked_Access); Renderer.Render (Doc); Output.Close; Util.Measures.Report (Time, "Render Text " & To_String (T.Name)); end; end if; end; Input.Close; Util.Tests.Assert_Equal_Files (T => T, Expect => To_String (T.Expect), Test => Result_File, Message => "Render"); end Test_Render; -- ------------------------------ -- Test case name -- ------------------------------ overriding function Name (T : in Test) return Util.Tests.Message_String is begin if T.Source = Wiki.SYNTAX_HTML then return Util.Tests.Format ("Test IMPORT " & To_String (T.Name)); elsif T.Is_Html then return Util.Tests.Format ("Test HTML " & To_String (T.Name)); else return Util.Tests.Format ("Test TEXT " & To_String (T.Name)); end if; end Name; -- ------------------------------ -- Perform the test. -- ------------------------------ overriding procedure Run_Test (T : in out Test) is begin T.Test_Render; end Run_Test; procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is use Ada.Directories; procedure Add_Import_Tests; procedure Add_Wiki_Tests; function Create_Test (Name : in String; Path : in String; Format : in Wiki.Wiki_Syntax; Prefix : in String; Is_Html : in Boolean) return Test_Case_Access; Result_Dir : constant String := "regtests/result"; Expect_Dir : constant String := "regtests/expect"; Expect_Path : constant String := Util.Tests.Get_Path (Expect_Dir); Result_Path : constant String := Util.Tests.Get_Test_Path (Result_Dir); Search : Search_Type; Filter : constant Filter_Type := (others => True); Ent : Directory_Entry_Type; function Create_Test (Name : in String; Path : in String; Format : in Wiki.Wiki_Syntax; Prefix : in String; Is_Html : in Boolean) return Test_Case_Access is Tst : Test_Case_Access; begin Tst := new Test; Tst.Is_Html := Is_Html; Tst.Name := To_Unbounded_String (Name); Tst.File := To_Unbounded_String (Path); Tst.Expect := To_Unbounded_String (Expect_Path & Prefix & Name); Tst.Result := To_Unbounded_String (Result_Path & Prefix & Name); Tst.Format := Format; Tst.Source := Format; return Tst; end Create_Test; procedure Add_Wiki_Tests is Dir : constant String := "regtests/files/wiki"; Path : constant String := Util.Tests.Get_Path (Dir); begin if Kind (Path) /= Directory then Ada.Text_IO.Put_Line ("Cannot read test directory: " & Path); end if; Start_Search (Search, Directory => Path, Pattern => "*.*", Filter => Filter); while More_Entries (Search) loop Get_Next_Entry (Search, Ent); declare Simple : constant String := Simple_Name (Ent); Ext : constant String := Ada.Directories.Extension (Simple); Tst : Test_Case_Access; Format : Wiki.Wiki_Syntax; begin if Simple /= "." and then Simple /= ".." and then Simple /= ".svn" and then Simple (Simple'Last) /= '~' then if Ext = "wiki" then Format := Wiki.SYNTAX_GOOGLE; elsif Ext = "dotclear" then Format := Wiki.SYNTAX_DOTCLEAR; elsif Ext = "creole" then Format := Wiki.SYNTAX_CREOLE; elsif Ext = "phpbb" then Format := Wiki.SYNTAX_PHPBB; elsif Ext = "mediawiki" then Format := Wiki.SYNTAX_MEDIA_WIKI; else Format := Wiki.SYNTAX_MIX; end if; Tst := Create_Test (Simple, Path & "/" & Simple, Format, "/wiki-html/", True); Suite.Add_Test (Tst.all'Access); Tst := Create_Test (Simple, Path & "/" & Simple, Format, "/wiki-txt/", False); Suite.Add_Test (Tst.all'Access); end if; end; end loop; end Add_Wiki_Tests; procedure Add_Import_Tests is Dir : constant String := "regtests/files/html"; Path : constant String := Util.Tests.Get_Path (Dir); begin if Kind (Path) /= Directory then Ada.Text_IO.Put_Line ("Cannot read test directory: " & Path); end if; Start_Search (Search, Directory => Path, Pattern => "*.*", Filter => Filter); while More_Entries (Search) loop Get_Next_Entry (Search, Ent); declare Simple : constant String := Simple_Name (Ent); Name : constant String := Base_Name (Simple); Tst : Test_Case_Access; begin if Simple /= "." and then Simple /= ".." and then Simple /= ".svn" and then Simple (Simple'Last) /= '~' then for Syntax in Wiki.Wiki_Syntax'Range loop case Syntax is when Wiki.SYNTAX_CREOLE => Tst := Create_Test (Name & ".creole", Path & "/" & Simple, Syntax, "/wiki-import/", True); when Wiki.SYNTAX_DOTCLEAR => Tst := Create_Test (Name & ".dotclear", Path & "/" & Simple, Syntax, "/wiki-import/", True); when Wiki.SYNTAX_MEDIA_WIKI => Tst := Create_Test (Name & ".mediawiki", Path & "/" & Simple, Syntax, "/wiki-import/", True); when others => Tst := null; end case; if Tst /= null then Tst.Source := Wiki.SYNTAX_HTML; Suite.Add_Test (Tst.all'Access); end if; end loop; end if; end; end loop; end Add_Import_Tests; begin Add_Wiki_Tests; Add_Import_Tests; end Add_Tests; end Wiki.Tests;
Define a condition plugin with some variables Register the condition plugin and use it when the plugin name is one of 'if', 'else', 'elsif' or 'end'
Define a condition plugin with some variables Register the condition plugin and use it when the plugin name is one of 'if', 'else', 'elsif' or 'end'
Ada
apache-2.0
stcarrez/ada-wiki,stcarrez/ada-wiki
5e562c5857713cd6c6024615323eb84eb1a1ec29
src/el-methods-proc_1.adb
src/el-methods-proc_1.adb
----------------------------------------------------------------------- -- EL.Methods.Proc_1 -- Procedure Binding 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. ----------------------------------------------------------------------- package body EL.Methods.Proc_1 is use EL.Expressions; -- ------------------------------ -- Returns True if the method is a valid method which accepts the arguments -- defined by the package instantiation. -- ------------------------------ function Is_Valid (Method : in EL.Expressions.Method_Info) return Boolean is begin if Method.Binding = null then return False; else return Method.Binding.all in Binding'Class; end if; end Is_Valid; -- ------------------------------ -- Execute the method describe by the method binding object. -- The method signature is: -- -- procedure F (Obj : in out <Bean>; -- Param : in out Param1_Type); -- -- where <Bean> inherits from <b>Readonly_Bean</b> -- (See <b>Bind</b> package) -- -- Raises <b>Invalid_Method</b> if the method referenced by -- the method expression does not exist or does not match -- the signature. -- ------------------------------ procedure Execute (Method : in EL.Expressions.Method_Info; Param : in out Param1_Type) is begin if Method.Binding = null then raise EL.Expressions.Invalid_Method with "Method not found"; end if; -- If the binding has the wrong type, we are trying to invoke -- a method with a different signature. if not (Method.Binding.all in Binding'Class) then raise EL.Expressions.Invalid_Method with "Invalid signature for method '" & Method.Binding.Name.all & "'"; end if; declare Proxy : constant Binding_Access := Binding (Method.Binding.all)'Access; begin Proxy.Method (Method.Object, Param); end; end Execute; -- ------------------------------ -- Execute the method describe by the method expression -- and with the given context. The method signature is: -- -- procedure F (Obj : in out <Bean>; -- Param : in Param1_Type); -- -- where <Bean> inherits from <b>Readonly_Bean</b> -- (See <b>Bind</b> package) -- -- Raises <b>Invalid_Method</b> if the method referenced by -- the method expression does not exist or does not match -- the signature. -- ------------------------------ procedure Execute (Method : in EL.Expressions.Method_Expression'Class; Param : in out Param1_Type; Context : in EL.Contexts.ELContext'Class) is Info : constant Method_Info := Method.Get_Method_Info (Context); begin Execute (Info, Param); end Execute; -- ------------------------------ -- 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. -- ------------------------------ package body Bind is procedure Method_Access (O : access Util.Beans.Basic.Readonly_Bean'Class; P1 : in out Param1_Type) is Object : constant access Bean := Bean (O.all)'Access; begin Method (Object.all, P1); end Method_Access; end Bind; end EL.Methods.Proc_1;
----------------------------------------------------------------------- -- EL.Methods.Proc_1 -- Procedure Binding 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 Util.Beans.Objects; package body EL.Methods.Proc_1 is use EL.Expressions; -- ------------------------------ -- Returns True if the method is a valid method which accepts the arguments -- defined by the package instantiation. -- ------------------------------ function Is_Valid (Method : in EL.Expressions.Method_Info) return Boolean is begin if Method.Binding = null then return False; else return Method.Binding.all in Binding'Class; end if; end Is_Valid; -- ------------------------------ -- Execute the method describe by the method binding object. -- The method signature is: -- -- procedure F (Obj : in out <Bean>; -- Param : in out Param1_Type); -- -- where <Bean> inherits from <b>Readonly_Bean</b> -- (See <b>Bind</b> package) -- -- Raises <b>Invalid_Method</b> if the method referenced by -- the method expression does not exist or does not match -- the signature. -- ------------------------------ procedure Execute (Method : in EL.Expressions.Method_Info; Param : in out Param1_Type) is begin if Method.Binding = null then raise EL.Expressions.Invalid_Method with "Method not found"; end if; -- If the binding has the wrong type, we are trying to invoke -- a method with a different signature. if not (Method.Binding.all in Binding'Class) then raise EL.Expressions.Invalid_Method with "Invalid signature for method '" & Method.Binding.Name.all & "'"; end if; declare Proxy : constant Binding_Access := Binding (Method.Binding.all)'Access; begin Proxy.Method (Util.Beans.Objects.To_Bean (Method.Object), Param); end; end Execute; -- ------------------------------ -- Execute the method describe by the method expression -- and with the given context. The method signature is: -- -- procedure F (Obj : in out <Bean>; -- Param : in Param1_Type); -- -- where <Bean> inherits from <b>Readonly_Bean</b> -- (See <b>Bind</b> package) -- -- Raises <b>Invalid_Method</b> if the method referenced by -- the method expression does not exist or does not match -- the signature. -- ------------------------------ procedure Execute (Method : in EL.Expressions.Method_Expression'Class; Param : in out Param1_Type; Context : in EL.Contexts.ELContext'Class) is Info : constant Method_Info := Method.Get_Method_Info (Context); begin Execute (Info, Param); end Execute; -- ------------------------------ -- 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. -- ------------------------------ package body Bind is procedure Method_Access (O : access Util.Beans.Basic.Readonly_Bean'Class; P1 : in out Param1_Type) is Object : constant access Bean := Bean (O.all)'Access; begin Method (Object.all, P1); end Method_Access; end Bind; end EL.Methods.Proc_1;
Update use of Method_Info record after change of type for the Object member
Update use of Method_Info record after change of type for the Object member
Ada
apache-2.0
stcarrez/ada-el
4d992b88e52e16bb401dc31b7355b40fcf14f475
src/gen-commands-page.adb
src/gen-commands-page.adb
----------------------------------------------------------------------- -- gen-commands-page -- Page creation command for dynamo -- Copyright (C) 2011, 2012, 2013, 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.Directories; with Ada.Text_IO; with Gen.Artifacts; with GNAT.Command_Line; with Util.Strings; package body Gen.Commands.Page is -- ------------------------------ -- Execute the command with the arguments. -- ------------------------------ overriding procedure Execute (Cmd : in Command; Name : in String; Args : in Argument_List'Class; Generator : in out Gen.Generator.Handler) is pragma Unreferenced (Cmd); use Ada.Strings.Unbounded; function Get_Layout return String; function Get_Name return String; Dir : constant String := Generator.Get_Result_Directory & "web/"; function Get_Name return String is Name : constant String := Args.Get_Argument (1); Pos : constant Natural := Util.Strings.Rindex (Name, '.'); begin if Pos = 0 then return Name; elsif Name (Pos .. Name'Last) = ".xhtml" then return Name (Name'First .. Pos - 1); elsif Name (Pos .. Name'Last) = ".html" then return Name (Name'First .. Pos - 1); else return Name; end if; end Get_Name; function Get_Layout return String is begin if Args.Get_Count = 1 then return "layout"; end if; declare Layout : constant String := Args.Get_Argument (2); begin if Ada.Directories.Exists (Dir & "WEB-INF/layouts/" & Layout & ".xhtml") then return Layout; end if; Generator.Info ("Layout file {0} not found.", Layout); return Layout; end; end Get_Layout; begin if Args.Get_Count = 0 or Args.Get_Count > 2 then Gen.Commands.Usage; return; end if; Generator.Set_Force_Save (False); Generator.Set_Result_Directory (Dir); Generator.Set_Global ("pageName", Get_Name); Generator.Set_Global ("layout", Get_Layout); Gen.Generator.Generate_All (Generator, Gen.Artifacts.ITERATION_TABLE, "page"); end Execute; -- ------------------------------ -- Write the help associated with the command. -- ------------------------------ overriding procedure Help (Cmd : in Command; Generator : in out Gen.Generator.Handler) is pragma Unreferenced (Cmd); use Ada.Text_IO; use Ada.Directories; Path : constant String := Generator.Get_Result_Directory & "web/WEB-INF/layouts"; Filter : constant Filter_Type := (Ordinary_File => True, others => False); Search : Search_Type; Ent : Directory_Entry_Type; begin Put_Line ("add-page: Add a new web page to the application"); Put_Line ("Usage: add-page NAME [LAYOUT]"); New_Line; Put_Line (" The web page is an XHTML file created under the 'web' directory."); Put_Line (" The NAME can contain a directory that will be created if necessary."); Put_Line (" The new web page can be configured to use the given layout."); Put_Line (" The layout file must exist to be used. The default layout is 'layout'."); Put_Line (" You can create a new layout with 'add-layout' command."); Put_Line (" You can also write your layout by adding an XHTML file in the directory:"); Put_Line (" " & Path); if Exists (Path) then New_Line; Put_Line (" Available layouts:"); Start_Search (Search, Directory => Path, Pattern => "*.xhtml", Filter => Filter); while More_Entries (Search) loop Get_Next_Entry (Search, Ent); declare Name : constant String := Simple_Name (Ent); Layout : constant String := Base_Name (Name); begin Put_Line (" " & Layout); end; end loop; end if; New_Line; Put_Line (" The following files are generated:"); Put_Line (" web/<name>.xhtml"); end Help; end Gen.Commands.Page;
----------------------------------------------------------------------- -- gen-commands-page -- Page creation command for dynamo -- Copyright (C) 2011, 2012, 2013, 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.Directories; with Ada.Text_IO; with Gen.Artifacts; with Util.Strings; package body Gen.Commands.Page is -- ------------------------------ -- Execute the command with the arguments. -- ------------------------------ overriding procedure Execute (Cmd : in Command; Name : in String; Args : in Argument_List'Class; Generator : in out Gen.Generator.Handler) is pragma Unreferenced (Cmd, Name); use Ada.Strings.Unbounded; function Get_Layout return String; function Get_Name return String; Dir : constant String := Generator.Get_Result_Directory & "web/"; function Get_Name return String is Name : constant String := Args.Get_Argument (1); Pos : constant Natural := Util.Strings.Rindex (Name, '.'); begin if Pos = 0 then return Name; elsif Name (Pos .. Name'Last) = ".xhtml" then return Name (Name'First .. Pos - 1); elsif Name (Pos .. Name'Last) = ".html" then return Name (Name'First .. Pos - 1); else return Name; end if; end Get_Name; function Get_Layout return String is begin if Args.Get_Count = 1 then return "layout"; end if; declare Layout : constant String := Args.Get_Argument (2); begin if Ada.Directories.Exists (Dir & "WEB-INF/layouts/" & Layout & ".xhtml") then return Layout; end if; Generator.Info ("Layout file {0} not found.", Layout); return Layout; end; end Get_Layout; begin if Args.Get_Count = 0 or Args.Get_Count > 2 then Gen.Commands.Usage; return; end if; Generator.Set_Force_Save (False); Generator.Set_Result_Directory (Dir); Generator.Set_Global ("pageName", Get_Name); Generator.Set_Global ("layout", Get_Layout); Gen.Generator.Generate_All (Generator, Gen.Artifacts.ITERATION_TABLE, "page"); end Execute; -- ------------------------------ -- Write the help associated with the command. -- ------------------------------ overriding procedure Help (Cmd : in Command; Generator : in out Gen.Generator.Handler) is pragma Unreferenced (Cmd); use Ada.Text_IO; use Ada.Directories; Path : constant String := Generator.Get_Result_Directory & "web/WEB-INF/layouts"; Filter : constant Filter_Type := (Ordinary_File => True, others => False); Search : Search_Type; Ent : Directory_Entry_Type; begin Put_Line ("add-page: Add a new web page to the application"); Put_Line ("Usage: add-page NAME [LAYOUT]"); New_Line; Put_Line (" The web page is an XHTML file created under the 'web' directory."); Put_Line (" The NAME can contain a directory that will be created if necessary."); Put_Line (" The new web page can be configured to use the given layout."); Put_Line (" The layout file must exist to be used. The default layout is 'layout'."); Put_Line (" You can create a new layout with 'add-layout' command."); Put_Line (" You can also write your layout by adding an XHTML file in the directory:"); Put_Line (" " & Path); if Exists (Path) then New_Line; Put_Line (" Available layouts:"); Start_Search (Search, Directory => Path, Pattern => "*.xhtml", Filter => Filter); while More_Entries (Search) loop Get_Next_Entry (Search, Ent); declare Name : constant String := Simple_Name (Ent); Layout : constant String := Base_Name (Name); begin Put_Line (" " & Layout); end; end loop; end if; New_Line; Put_Line (" The following files are generated:"); Put_Line (" web/<name>.xhtml"); end Help; end Gen.Commands.Page;
Fix compilation warning
Fix compilation warning
Ada
apache-2.0
stcarrez/dynamo,stcarrez/dynamo,stcarrez/dynamo
cb5042b983720866250768a86d2503144fe1a152
regtests/asf-routes-tests.adb
regtests/asf-routes-tests.adb
----------------------------------------------------------------------- -- asf-routes-tests - Unit tests for ASF.Routes -- Copyright (C) 2015 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Measures; with Util.Log.Loggers; with Util.Test_Caller; with EL.Contexts.Default; package body ASF.Routes.Tests is Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("ASF.Routes.Tests"); package Caller is new Util.Test_Caller (Test, "Routes"); procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is begin Caller.Add_Test (Suite, "Test ASF.Routes.Add_Route (fixed path)", Test_Add_Route_With_Path'Access); Caller.Add_Test (Suite, "Test ASF.Routes.Add_Route (:param path)", Test_Add_Route_With_Param'Access); Caller.Add_Test (Suite, "Test ASF.Routes.Add_Route (*.ext path)", Test_Add_Route_With_Ext'Access); Caller.Add_Test (Suite, "Test ASF.Routes.Add_Route (#{} path)", Test_Add_Route_With_EL'Access); Caller.Add_Test (Suite, "Test ASF.Routes.Iterate", Test_Iterate'Access); end Add_Tests; overriding function Get_Value (Bean : in Test_Bean; Name : in String) return Util.Beans.Objects.Object is begin if Name = "id" then return Util.Beans.Objects.To_Object (Bean.Id); elsif Name = "name" then return Util.Beans.Objects.To_Object (Bean.Name); else return Util.Beans.Objects.Null_Object; end if; end Get_Value; overriding procedure Set_Value (Bean : in out Test_Bean; Name : in String; Value : in Util.Beans.Objects.Object) is begin if Name = "id" then Bean.Id := Util.Beans.Objects.To_Unbounded_String (Value); elsif Name = "name" then Bean.Name := Util.Beans.Objects.To_Unbounded_String (Value); end if; end Set_Value; -- ------------------------------ -- Setup the test instance. -- ------------------------------ overriding procedure Set_Up (T : in out Test) is begin T.Bean := new Test_Bean; ASF.Tests.EL_Test (T).Set_Up; T.Root_Resolver.Register (Ada.Strings.Unbounded.To_Unbounded_String ("user"), Util.Beans.Objects.To_Object (T.Bean.all'Access)); for I in T.Routes'Range loop T.Routes (I) := new Test_Route_Type '(Index => I); end loop; end Set_Up; -- ------------------------------ -- Verify that the path matches the given route. -- ------------------------------ procedure Verify_Route (T : in out Test; Router : in out Router_Type; Path : in String; Index : in Positive; Bean : in out Test_Bean'Class) is Route : constant Route_Type_Access := T.Routes (Index).all'Access; R : Route_Context_Type; begin Router.Find_Route (Path, R); declare P : constant String := Get_Path (R); begin T.Assert_Equals (Path, P, "Add_Route + Find_Route with " & Path); T.Assert (Get_Route (R) /= null, "Get_Route returns a null route for " & Path); T.Assert (Get_Route (R) = Route, "Get_Route returns a wrong route for " & Path); -- Inject the path parameters in the bean instance. Inject_Parameters (R, Bean, T.ELContext.all); end; end Verify_Route; -- ------------------------------ -- Add the route associted with the path pattern. -- ------------------------------ procedure Add_Route (T : in out Test; Router : in out Router_Type; Path : in String; Index : in Positive; Bean : in out Test_Bean'Class) is Route : constant Route_Type_Access := T.Routes (Index).all'Access; begin Router.Add_Route (Path, Route, T.ELContext.all); Verify_Route (T, Router, Path, Index, Bean); end Add_Route; -- ------------------------------ -- Test the Add_Route with simple fixed path components. -- Example: /list/index.html -- ------------------------------ procedure Test_Add_Route_With_Path (T : in out Test) is Router : Router_Type; Bean : Test_Bean; begin Add_Route (T, Router, "/page.html", 1, Bean); Add_Route (T, Router, "/list/page.html", 2, Bean); Add_Route (T, Router, "/list/index.html", 3, Bean); Add_Route (T, Router, "/view/page/content/index.html", 4, Bean); Add_Route (T, Router, "/list//page/view.html", 5, Bean); Add_Route (T, Router, "/list////page/content.html", 6, Bean); Verify_Route (T, Router, "/list/index.html", 3, Bean); end Test_Add_Route_With_Path; -- ------------------------------ -- Test the Add_Route with extension mapping. -- Example: /list/*.html -- ------------------------------ procedure Test_Add_Route_With_Ext (T : in out Test) is Router : Router_Type; Bean : Test_Bean; begin Add_Route (T, Router, "/page.html", 1, Bean); Add_Route (T, Router, "/list/*.html", 2, Bean); Add_Route (T, Router, "/list/index.html", 3, Bean); Add_Route (T, Router, "/view/page/content/page1.html", 4, Bean); Add_Route (T, Router, "/view/page/content/page2.html", 5, Bean); Add_Route (T, Router, "/view/page/content/*.html", 6, Bean); Add_Route (T, Router, "/ajax/*", 7, Bean); -- Verify precedence and wildcard matching. Verify_Route (T, Router, "/list/index.html", 3, Bean); Verify_Route (T, Router, "/list/admin.html", 2, Bean); Verify_Route (T, Router, "/list/1/2/3/admin.html", 2, Bean); Verify_Route (T, Router, "/view/page/content/t.html", 6, Bean); Verify_Route (T, Router, "/view/page/content/1/t.html", 6, Bean); Verify_Route (T, Router, "/view/page/content/1/2/t.html", 6, Bean); Verify_Route (T, Router, "/ajax/form/save", 7, Bean); end Test_Add_Route_With_Ext; -- ------------------------------ -- Test the Add_Route with fixed path components and path parameters. -- Example: /users/:id/view.html -- ------------------------------ procedure Test_Add_Route_With_Param (T : in out Test) is use Ada.Strings.Unbounded; Router : Router_Type; Bean : Test_Bean; begin Add_Route (T, Router, "/users/:id/view.html", 1, Bean); T.Assert_Equals (":id", To_String (Bean.Id), "Bean injection failed for :id"); Bean.Id := To_Unbounded_String (""); Add_Route (T, Router, "/users/:id/list.html", 2, Bean); T.Assert_Equals (":id", To_String (Bean.Id), "Bean injection failed for :id"); Bean.Id := To_Unbounded_String (""); Add_Route (T, Router, "/users/:id/index.html", 3, Bean); T.Assert_Equals (":id", To_String (Bean.Id), "Bean injection failed for :id"); Bean.Id := To_Unbounded_String (""); Add_Route (T, Router, "/view/page/content/index.html", 4, Bean); Add_Route (T, Router, "/list//page/view.html", 5, Bean); Add_Route (T, Router, "/list////page/content.html", 6, Bean); T.Assert_Equals ("", To_String (Bean.Id), "Bean injection failed for fixed path"); Add_Route (T, Router, "/users/:id/:name/index.html", 7, Bean); T.Assert_Equals (":id", To_String (Bean.Id), "Bean injection failed for :id"); T.Assert_Equals (":name", To_String (Bean.Name), "Bean injection failed for :name"); Add_Route (T, Router, "/users/list/index.html", 8, Bean); Verify_Route (T, Router, "/users/1234/view.html", 1, Bean); T.Assert_Equals ("1234", To_String (Bean.Id), "Bean injection failed for :id"); Verify_Route (T, Router, "/users/234/567/index.html", 7, Bean); T.Assert_Equals ("234", To_String (Bean.Id), "Bean injection failed for :id"); T.Assert_Equals ("567", To_String (Bean.Name), "Bean injection failed for :name"); end Test_Add_Route_With_Param; -- ------------------------------ -- Test the Add_Route with fixed path components and EL path injection. -- Example: /users/#{user.id}/view.html -- ------------------------------ procedure Test_Add_Route_With_EL (T : in out Test) is use Ada.Strings.Unbounded; Router : Router_Type; Bean : aliased Test_Bean; begin Add_Route (T, Router, "/users/#{user.id}", 1, Bean); Add_Route (T, Router, "/users/view.html", 2, Bean); Add_Route (T, Router, "/users/#{user.id}/#{user.name}/index.html", 3, Bean); Add_Route (T, Router, "/users/admin/#{user.id}/pages/#{user.name}", 4, Bean); -- Verify that the path parameters are injected in the 'user' bean (= T.Bean). Verify_Route (T, Router, "/users/234/567/index.html", 3, Bean); T.Assert_Equals ("234", To_String (T.Bean.Id), "Bean injection failed for :id"); T.Assert_Equals ("567", To_String (T.Bean.Name), "Bean injection failed for :name"); end Test_Add_Route_With_EL; P_1 : aliased constant String := "/list/index.html"; P_2 : aliased constant String := "/users/:id"; P_3 : aliased constant String := "/users/:id/view"; P_4 : aliased constant String := "/users/index.html"; P_5 : aliased constant String := "/users/:id/:name"; P_6 : aliased constant String := "/users/:id/:name/view.html"; P_7 : aliased constant String := "/users/:id/list"; P_8 : aliased constant String := "/users/test.html"; P_9 : aliased constant String := "/admin/1/2/3/4/5/list.html"; P_10 : aliased constant String := "/admin/*.html"; P_11 : aliased constant String := "/admin/*.png"; P_12 : aliased constant String := "/admin/*.jpg"; P_13 : aliased constant String := "/users/:id/page/*.xml"; P_14 : aliased constant String := "/*.jsf"; type Const_String_Access is access constant String; type String_Array is array (Positive range <>) of Const_String_Access; Path_Array : constant String_Array := (P_1'Access, P_2'Access, P_3'Access, P_4'Access, P_5'Access, P_6'Access, P_7'Access, P_8'Access, P_9'Access, P_10'Access, P_11'Access, P_12'Access, P_13'Access, P_14'Access); -- ------------------------------ -- Test the Iterate over several paths. -- ------------------------------ procedure Test_Iterate (T : in out Test) is Router : Router_Type; Bean : Test_Bean; procedure Process (Pattern : in String; Route : in Route_Type_Access) is begin T.Assert (Route /= null, "The route is null for " & Pattern); T.Assert (Route.all in Test_Route_Type'Class, "Invalid route for " & Pattern); Log.Info ("Route {0} to {1}", Pattern, Natural'Image (Test_Route_Type (Route.all).Index)); T.Assert_Equals (Pattern, Path_Array (Test_Route_Type (Route.all).Index).all, "Invalid route for " & Pattern); end Process; begin for I in Path_Array'Range loop Add_Route (T, Router, Path_Array (I).all, I, Bean); end loop; Router.Iterate (Process'Access); declare R : Route_Context_Type; St : Util.Measures.Stamp; begin for I in 1 .. 1000 loop declare R : Route_Context_Type; begin Router.Find_Route ("/admin/1/2/3/4/5/list.html", R); end; end loop; Util.Measures.Report (St, "Find 1000 routes (fixed path)"); end; declare R : Route_Context_Type; St : Util.Measures.Stamp; begin for I in 1 .. 1000 loop declare R : Route_Context_Type; begin Router.Find_Route ("/admin/1/2/3/4/5/list.jsf", R); end; end loop; Util.Measures.Report (St, "Find 1000 routes (extension)"); end; end Test_Iterate; end ASF.Routes.Tests;
----------------------------------------------------------------------- -- asf-routes-tests - Unit tests for ASF.Routes -- Copyright (C) 2015 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Measures; with Util.Log.Loggers; with Util.Test_Caller; with EL.Contexts.Default; package body ASF.Routes.Tests is Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("ASF.Routes.Tests"); package Caller is new Util.Test_Caller (Test, "Routes"); procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is begin Caller.Add_Test (Suite, "Test ASF.Routes.Add_Route (fixed path)", Test_Add_Route_With_Path'Access); Caller.Add_Test (Suite, "Test ASF.Routes.Add_Route (:param path)", Test_Add_Route_With_Param'Access); Caller.Add_Test (Suite, "Test ASF.Routes.Add_Route (*.ext path)", Test_Add_Route_With_Ext'Access); Caller.Add_Test (Suite, "Test ASF.Routes.Add_Route (#{} path)", Test_Add_Route_With_EL'Access); Caller.Add_Test (Suite, "Test ASF.Routes.Iterate", Test_Iterate'Access); end Add_Tests; overriding function Get_Value (Bean : in Test_Bean; Name : in String) return Util.Beans.Objects.Object is begin if Name = "id" then return Util.Beans.Objects.To_Object (Bean.Id); elsif Name = "name" then return Util.Beans.Objects.To_Object (Bean.Name); else return Util.Beans.Objects.Null_Object; end if; end Get_Value; overriding procedure Set_Value (Bean : in out Test_Bean; Name : in String; Value : in Util.Beans.Objects.Object) is begin if Name = "id" then Bean.Id := Util.Beans.Objects.To_Unbounded_String (Value); elsif Name = "name" then Bean.Name := Util.Beans.Objects.To_Unbounded_String (Value); end if; end Set_Value; -- ------------------------------ -- Setup the test instance. -- ------------------------------ overriding procedure Set_Up (T : in out Test) is begin T.Bean := new Test_Bean; ASF.Tests.EL_Test (T).Set_Up; T.Root_Resolver.Register (Ada.Strings.Unbounded.To_Unbounded_String ("user"), Util.Beans.Objects.To_Object (T.Bean.all'Access)); for I in T.Routes'Range loop T.Routes (I) := new Test_Route_Type '(Index => I); end loop; end Set_Up; -- ------------------------------ -- Verify that the path matches the given route. -- ------------------------------ procedure Verify_Route (T : in out Test; Router : in out Router_Type; Path : in String; Index : in Positive; Bean : in out Test_Bean'Class) is Route : constant Route_Type_Access := T.Routes (Index).all'Access; R : Route_Context_Type; begin Router.Find_Route (Path, R); declare P : constant String := Get_Path (R); begin T.Assert_Equals (Path, P, "Add_Route + Find_Route with " & Path); T.Assert (Get_Route (R) /= null, "Get_Route returns a null route for " & Path); T.Assert (Get_Route (R) = Route, "Get_Route returns a wrong route for " & Path); -- Inject the path parameters in the bean instance. Inject_Parameters (R, Bean, T.ELContext.all); end; end Verify_Route; -- ------------------------------ -- Add the route associted with the path pattern. -- ------------------------------ procedure Add_Route (T : in out Test; Router : in out Router_Type; Path : in String; Index : in Positive; Bean : in out Test_Bean'Class) is Route : constant Route_Type_Access := T.Routes (Index).all'Access; begin Router.Add_Route (Path, Route, T.ELContext.all); Verify_Route (T, Router, Path, Index, Bean); end Add_Route; -- ------------------------------ -- Test the Add_Route with simple fixed path components. -- Example: /list/index.html -- ------------------------------ procedure Test_Add_Route_With_Path (T : in out Test) is Router : Router_Type; Bean : Test_Bean; begin Add_Route (T, Router, "/page.html", 1, Bean); Add_Route (T, Router, "/list/page.html", 2, Bean); Add_Route (T, Router, "/list/index.html", 3, Bean); Add_Route (T, Router, "/view/page/content/index.html", 4, Bean); Add_Route (T, Router, "/list//page/view.html", 5, Bean); Add_Route (T, Router, "/list////page/content.html", 6, Bean); Verify_Route (T, Router, "/list/index.html", 3, Bean); end Test_Add_Route_With_Path; -- ------------------------------ -- Test the Add_Route with extension mapping. -- Example: /list/*.html -- ------------------------------ procedure Test_Add_Route_With_Ext (T : in out Test) is Router : Router_Type; Bean : Test_Bean; begin Add_Route (T, Router, "/page.html", 1, Bean); Add_Route (T, Router, "/list/*.html", 2, Bean); Add_Route (T, Router, "/list/index.html", 3, Bean); Add_Route (T, Router, "/view/page/content/page1.html", 4, Bean); Add_Route (T, Router, "/view/page/content/page2.html", 5, Bean); Add_Route (T, Router, "/view/page/content/*.html", 6, Bean); Add_Route (T, Router, "/ajax/*", 7, Bean); Add_Route (T, Router, "*.html", 8, Bean); -- Verify precedence and wildcard matching. Verify_Route (T, Router, "/list/index.html", 3, Bean); Verify_Route (T, Router, "/list/admin.html", 2, Bean); Verify_Route (T, Router, "/list/1/2/3/admin.html", 2, Bean); Verify_Route (T, Router, "/view/page/content/t.html", 6, Bean); Verify_Route (T, Router, "/view/page/content/1/t.html", 6, Bean); Verify_Route (T, Router, "/view/page/content/1/2/t.html", 6, Bean); Verify_Route (T, Router, "/ajax/form/save", 7, Bean); Verify_Route (T, Router, "/view/index.html", 8, Bean); end Test_Add_Route_With_Ext; -- ------------------------------ -- Test the Add_Route with fixed path components and path parameters. -- Example: /users/:id/view.html -- ------------------------------ procedure Test_Add_Route_With_Param (T : in out Test) is use Ada.Strings.Unbounded; Router : Router_Type; Bean : Test_Bean; begin Add_Route (T, Router, "/users/:id/view.html", 1, Bean); T.Assert_Equals (":id", To_String (Bean.Id), "Bean injection failed for :id"); Bean.Id := To_Unbounded_String (""); Add_Route (T, Router, "/users/:id/list.html", 2, Bean); T.Assert_Equals (":id", To_String (Bean.Id), "Bean injection failed for :id"); Bean.Id := To_Unbounded_String (""); Add_Route (T, Router, "/users/:id/index.html", 3, Bean); T.Assert_Equals (":id", To_String (Bean.Id), "Bean injection failed for :id"); Bean.Id := To_Unbounded_String (""); Add_Route (T, Router, "/view/page/content/index.html", 4, Bean); Add_Route (T, Router, "/list//page/view.html", 5, Bean); Add_Route (T, Router, "/list////page/content.html", 6, Bean); T.Assert_Equals ("", To_String (Bean.Id), "Bean injection failed for fixed path"); Add_Route (T, Router, "/users/:id/:name/index.html", 7, Bean); T.Assert_Equals (":id", To_String (Bean.Id), "Bean injection failed for :id"); T.Assert_Equals (":name", To_String (Bean.Name), "Bean injection failed for :name"); Add_Route (T, Router, "/users/list/index.html", 8, Bean); Verify_Route (T, Router, "/users/1234/view.html", 1, Bean); T.Assert_Equals ("1234", To_String (Bean.Id), "Bean injection failed for :id"); Verify_Route (T, Router, "/users/234/567/index.html", 7, Bean); T.Assert_Equals ("234", To_String (Bean.Id), "Bean injection failed for :id"); T.Assert_Equals ("567", To_String (Bean.Name), "Bean injection failed for :name"); end Test_Add_Route_With_Param; -- ------------------------------ -- Test the Add_Route with fixed path components and EL path injection. -- Example: /users/#{user.id}/view.html -- ------------------------------ procedure Test_Add_Route_With_EL (T : in out Test) is use Ada.Strings.Unbounded; Router : Router_Type; Bean : aliased Test_Bean; begin Add_Route (T, Router, "/users/#{user.id}", 1, Bean); Add_Route (T, Router, "/users/view.html", 2, Bean); Add_Route (T, Router, "/users/#{user.id}/#{user.name}/index.html", 3, Bean); Add_Route (T, Router, "/users/admin/#{user.id}/pages/#{user.name}", 4, Bean); -- Verify that the path parameters are injected in the 'user' bean (= T.Bean). Verify_Route (T, Router, "/users/234/567/index.html", 3, Bean); T.Assert_Equals ("234", To_String (T.Bean.Id), "Bean injection failed for :id"); T.Assert_Equals ("567", To_String (T.Bean.Name), "Bean injection failed for :name"); end Test_Add_Route_With_EL; P_1 : aliased constant String := "/list/index.html"; P_2 : aliased constant String := "/users/:id"; P_3 : aliased constant String := "/users/:id/view"; P_4 : aliased constant String := "/users/index.html"; P_5 : aliased constant String := "/users/:id/:name"; P_6 : aliased constant String := "/users/:id/:name/view.html"; P_7 : aliased constant String := "/users/:id/list"; P_8 : aliased constant String := "/users/test.html"; P_9 : aliased constant String := "/admin/1/2/3/4/5/list.html"; P_10 : aliased constant String := "/admin/*.html"; P_11 : aliased constant String := "/admin/*.png"; P_12 : aliased constant String := "/admin/*.jpg"; P_13 : aliased constant String := "/users/:id/page/*.xml"; P_14 : aliased constant String := "/*.jsf"; type Const_String_Access is access constant String; type String_Array is array (Positive range <>) of Const_String_Access; Path_Array : constant String_Array := (P_1'Access, P_2'Access, P_3'Access, P_4'Access, P_5'Access, P_6'Access, P_7'Access, P_8'Access, P_9'Access, P_10'Access, P_11'Access, P_12'Access, P_13'Access, P_14'Access); -- ------------------------------ -- Test the Iterate over several paths. -- ------------------------------ procedure Test_Iterate (T : in out Test) is Router : Router_Type; Bean : Test_Bean; procedure Process (Pattern : in String; Route : in Route_Type_Access) is begin T.Assert (Route /= null, "The route is null for " & Pattern); T.Assert (Route.all in Test_Route_Type'Class, "Invalid route for " & Pattern); Log.Info ("Route {0} to {1}", Pattern, Natural'Image (Test_Route_Type (Route.all).Index)); T.Assert_Equals (Pattern, Path_Array (Test_Route_Type (Route.all).Index).all, "Invalid route for " & Pattern); end Process; begin for I in Path_Array'Range loop Add_Route (T, Router, Path_Array (I).all, I, Bean); end loop; Router.Iterate (Process'Access); declare R : Route_Context_Type; St : Util.Measures.Stamp; begin for I in 1 .. 1000 loop declare R : Route_Context_Type; begin Router.Find_Route ("/admin/1/2/3/4/5/list.html", R); end; end loop; Util.Measures.Report (St, "Find 1000 routes (fixed path)"); end; declare R : Route_Context_Type; St : Util.Measures.Stamp; begin for I in 1 .. 1000 loop declare R : Route_Context_Type; begin Router.Find_Route ("/admin/1/2/3/4/5/list.jsf", R); end; end loop; Util.Measures.Report (St, "Find 1000 routes (extension)"); end; end Test_Iterate; end ASF.Routes.Tests;
Add a wildcard route test
Add a wildcard route test
Ada
apache-2.0
stcarrez/ada-asf,stcarrez/ada-asf,stcarrez/ada-asf
0c459c3999a33ee525ef56a234f00880ca5225b9
regtests/util-files-tests.adb
regtests/util-files-tests.adb
----------------------------------------------------------------------- -- files.tests -- Unit tests for files -- Copyright (C) 2009, 2010, 2011, 2012, 2013, 2019 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Directories; with Util.Test_Caller; package body Util.Files.Tests is use Util.Tests; package Caller is new Util.Test_Caller (Test, "Files"); procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is begin Caller.Add_Test (Suite, "Test Util.Files.Read_File", Test_Read_File'Access); Caller.Add_Test (Suite, "Test Util.Files.Read_File (missing)", Test_Read_File_Missing'Access); Caller.Add_Test (Suite, "Test Util.Files.Read_File (truncate)", Test_Read_File'Access); Caller.Add_Test (Suite, "Test Util.Files.Write_File", Test_Write_File'Access); Caller.Add_Test (Suite, "Test Util.Files.Iterate_Path", Test_Iterate_Path'Access); Caller.Add_Test (Suite, "Test Util.Files.Find_File_Path", Test_Find_File_Path'Access); Caller.Add_Test (Suite, "Test Util.Files.Compose_Path", Test_Compose_Path'Access); Caller.Add_Test (Suite, "Test Util.Files.Get_Relative_Path", Test_Get_Relative_Path'Access); end Add_Tests; -- ------------------------------ -- Test reading a file into a string -- Reads this ada source file and checks we have read it correctly -- ------------------------------ procedure Test_Read_File (T : in out Test) is Result : Unbounded_String; begin Read_File (Path => "regtests/util-files-tests.adb", Into => Result); T.Assert (Index (Result, "Util.Files.Tests") > 0, "Content returned by Read_File is not correct"); T.Assert (Index (Result, "end Util.Files.Tests;") > 0, "Content returned by Read_File is not correct"); end Test_Read_File; procedure Test_Read_File_Missing (T : in out Test) is Result : Unbounded_String; pragma Unreferenced (Result); begin Read_File (Path => "regtests/files-test--util.adb", Into => Result); T.Assert (False, "No exception raised"); exception when others => null; end Test_Read_File_Missing; procedure Test_Read_File_Truncate (T : in out Test) is Result : Unbounded_String; begin Read_File (Path => "regtests/util-files-tests.adb", Into => Result, Max_Size => 50); Assert_Equals (T, Length (Result), 50, "Read_File did not truncate correctly"); T.Assert (Index (Result, "Apache License") > 0, "Content returned by Read_File is not correct"); end Test_Read_File_Truncate; -- ------------------------------ -- Check writing a file -- ------------------------------ procedure Test_Write_File (T : in out Test) is Path : constant String := Util.Tests.Get_Test_Path ("test-write.txt"); Content : constant String := "Testing Util.Files.Write_File" & ASCII.LF; Result : Unbounded_String; begin Write_File (Path => Path, Content => Content); Read_File (Path => Path, Into => Result); Assert_Equals (T, To_String (Result), Content, "Invalid content written or read"); end Test_Write_File; -- ------------------------------ -- Check Find_File_Path -- ------------------------------ procedure Test_Find_File_Path (T : in out Test) is Dir : constant String := Util.Tests.Get_Path ("regtests"); Paths : constant String := ".;" & Dir; begin declare P : constant String := Util.Files.Find_File_Path ("test.properties", Paths); begin Assert_Equals (T, Dir & "/test.properties", P, "Invalid path returned"); end; Assert_Equals (T, "blablabla.properties", Util.Files.Find_File_Path ("blablabla.properties", Paths)); end Test_Find_File_Path; -- ------------------------------ -- Check Iterate_Path -- ------------------------------ procedure Test_Iterate_Path (T : in out Test) is procedure Check_Path (Dir : in String; Done : out Boolean); Last : Unbounded_String; procedure Check_Path (Dir : in String; Done : out Boolean) is begin if Dir = "a" or Dir = "bc" or Dir = "de" then Done := False; else Done := True; end if; Last := To_Unbounded_String (Dir); end Check_Path; begin Iterate_Path ("a;bc;de;f", Check_Path'Access); Assert_Equals (T, "f", Last, "Invalid last path"); Iterate_Path ("de;bc;de;b", Check_Path'Access); Assert_Equals (T, "b", Last, "Invalid last path"); Iterate_Path ("de;bc;de;a", Check_Path'Access, Ada.Strings.Backward); Assert_Equals (T, "de", Last, "Invalid last path"); end Test_Iterate_Path; -- ------------------------------ -- Test the Compose_Path operation -- ------------------------------ procedure Test_Compose_Path (T : in out Test) is begin Assert_Equals (T, "src/sys/processes/os-none", Compose_Path ("src;regtests;src/sys/processes", "os-none"), "Invalid path composition"); Assert_Equals (T, "regtests/bundles", Compose_Path ("src;regtests", "bundles"), "Invalid path composition"); if Ada.Directories.Exists ("/usr/bin") then Assert_Equals (T, "/usr/bin;/usr/local/bin;/usr/bin", Compose_Path ("/usr;/usr/local;/usr", "bin"), "Invalid path composition"); end if; end Test_Compose_Path; -- ------------------------------ -- Test the Get_Relative_Path operation. -- ------------------------------ procedure Test_Get_Relative_Path (T : in out Test) is begin Assert_Equals (T, "../util", Get_Relative_Path ("/home/john/src/asf", "/home/john/src/util"), "Invalid relative path"); Assert_Equals (T, "../util", Get_Relative_Path ("/home/john/src/asf/", "/home/john/src/util"), "Invalid relative path"); Assert_Equals (T, "../util/b", Get_Relative_Path ("/home/john/src/asf", "/home/john/src/util/b"), "Invalid relative path"); Assert_Equals (T, "../as", Get_Relative_Path ("/home/john/src/asf", "/home/john/src/as"), "Invalid relative path"); Assert_Equals (T, "../../", Get_Relative_Path ("/home/john/src/asf", "/home/john"), "Invalid relative path"); Assert_Equals (T, "/usr/share/admin", Get_Relative_Path ("/home/john/src/asf", "/usr/share/admin"), "Invalid absolute path"); Assert_Equals (T, "/home/john", Get_Relative_Path ("home/john/src/asf", "/home/john"), "Invalid relative path"); Assert_Equals (T, "e", Get_Relative_Path ("/home/john/src/asf", "/home/john/src/asf/e"), "Invalid relative path"); Assert_Equals (T, ".", Get_Relative_Path ("/home/john/src/asf", "/home/john/src/asf/"), "Invalid relative path"); end Test_Get_Relative_Path; end Util.Files.Tests;
----------------------------------------------------------------------- -- files.tests -- Unit tests for files -- Copyright (C) 2009, 2010, 2011, 2012, 2013, 2019, 2022 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with System; with Ada.Directories; with Util.Systems.Constants; with Util.Test_Caller; package body Util.Files.Tests is use Util.Tests; package Caller is new Util.Test_Caller (Test, "Files"); procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is begin Caller.Add_Test (Suite, "Test Util.Files.Read_File", Test_Read_File'Access); Caller.Add_Test (Suite, "Test Util.Files.Read_File (missing)", Test_Read_File_Missing'Access); Caller.Add_Test (Suite, "Test Util.Files.Read_File (truncate)", Test_Read_File'Access); Caller.Add_Test (Suite, "Test Util.Files.Write_File", Test_Write_File'Access); Caller.Add_Test (Suite, "Test Util.Files.Iterate_Path", Test_Iterate_Path'Access); Caller.Add_Test (Suite, "Test Util.Files.Find_File_Path", Test_Find_File_Path'Access); Caller.Add_Test (Suite, "Test Util.Files.Compose_Path", Test_Compose_Path'Access); Caller.Add_Test (Suite, "Test Util.Files.Get_Relative_Path", Test_Get_Relative_Path'Access); Caller.Add_Test (Suite, "Test Util.Files.Delete_Tree", Test_Delete_Tree'Access); end Add_Tests; -- ------------------------------ -- Test reading a file into a string -- Reads this ada source file and checks we have read it correctly -- ------------------------------ procedure Test_Read_File (T : in out Test) is Result : Unbounded_String; begin Read_File (Path => "regtests/util-files-tests.adb", Into => Result); T.Assert (Index (Result, "Util.Files.Tests") > 0, "Content returned by Read_File is not correct"); T.Assert (Index (Result, "end Util.Files.Tests;") > 0, "Content returned by Read_File is not correct"); end Test_Read_File; procedure Test_Read_File_Missing (T : in out Test) is Result : Unbounded_String; pragma Unreferenced (Result); begin Read_File (Path => "regtests/files-test--util.adb", Into => Result); T.Assert (False, "No exception raised"); exception when others => null; end Test_Read_File_Missing; procedure Test_Read_File_Truncate (T : in out Test) is Result : Unbounded_String; begin Read_File (Path => "regtests/util-files-tests.adb", Into => Result, Max_Size => 50); Assert_Equals (T, Length (Result), 50, "Read_File did not truncate correctly"); T.Assert (Index (Result, "Apache License") > 0, "Content returned by Read_File is not correct"); end Test_Read_File_Truncate; -- ------------------------------ -- Check writing a file -- ------------------------------ procedure Test_Write_File (T : in out Test) is Path : constant String := Util.Tests.Get_Test_Path ("test-write.txt"); Content : constant String := "Testing Util.Files.Write_File" & ASCII.LF; Result : Unbounded_String; begin Write_File (Path => Path, Content => Content); Read_File (Path => Path, Into => Result); Assert_Equals (T, To_String (Result), Content, "Invalid content written or read"); end Test_Write_File; -- ------------------------------ -- Check Find_File_Path -- ------------------------------ procedure Test_Find_File_Path (T : in out Test) is Dir : constant String := Util.Tests.Get_Path ("regtests"); Paths : constant String := ".;" & Dir; begin declare P : constant String := Util.Files.Find_File_Path ("test.properties", Paths); begin Assert_Equals (T, Dir & "/test.properties", P, "Invalid path returned"); end; Assert_Equals (T, "blablabla.properties", Util.Files.Find_File_Path ("blablabla.properties", Paths)); end Test_Find_File_Path; -- ------------------------------ -- Check Iterate_Path -- ------------------------------ procedure Test_Iterate_Path (T : in out Test) is procedure Check_Path (Dir : in String; Done : out Boolean); Last : Unbounded_String; procedure Check_Path (Dir : in String; Done : out Boolean) is begin if Dir = "a" or Dir = "bc" or Dir = "de" then Done := False; else Done := True; end if; Last := To_Unbounded_String (Dir); end Check_Path; begin Iterate_Path ("a;bc;de;f", Check_Path'Access); Assert_Equals (T, "f", Last, "Invalid last path"); Iterate_Path ("de;bc;de;b", Check_Path'Access); Assert_Equals (T, "b", Last, "Invalid last path"); Iterate_Path ("de;bc;de;a", Check_Path'Access, Ada.Strings.Backward); Assert_Equals (T, "de", Last, "Invalid last path"); end Test_Iterate_Path; -- ------------------------------ -- Test the Compose_Path operation -- ------------------------------ procedure Test_Compose_Path (T : in out Test) is begin Assert_Equals (T, "src/sys/processes/os-none", Compose_Path ("src;regtests;src/sys/processes", "os-none"), "Invalid path composition"); Assert_Equals (T, "regtests/bundles", Compose_Path ("src;regtests", "bundles"), "Invalid path composition"); if Ada.Directories.Exists ("/usr/bin") then Assert_Equals (T, "/usr/bin;/usr/local/bin;/usr/bin", Compose_Path ("/usr;/usr/local;/usr", "bin"), "Invalid path composition"); end if; end Test_Compose_Path; -- ------------------------------ -- Test the Get_Relative_Path operation. -- ------------------------------ procedure Test_Get_Relative_Path (T : in out Test) is begin Assert_Equals (T, "../util", Get_Relative_Path ("/home/john/src/asf", "/home/john/src/util"), "Invalid relative path"); Assert_Equals (T, "../util", Get_Relative_Path ("/home/john/src/asf/", "/home/john/src/util"), "Invalid relative path"); Assert_Equals (T, "../util/b", Get_Relative_Path ("/home/john/src/asf", "/home/john/src/util/b"), "Invalid relative path"); Assert_Equals (T, "../as", Get_Relative_Path ("/home/john/src/asf", "/home/john/src/as"), "Invalid relative path"); Assert_Equals (T, "../../", Get_Relative_Path ("/home/john/src/asf", "/home/john"), "Invalid relative path"); Assert_Equals (T, "/usr/share/admin", Get_Relative_Path ("/home/john/src/asf", "/usr/share/admin"), "Invalid absolute path"); Assert_Equals (T, "/home/john", Get_Relative_Path ("home/john/src/asf", "/home/john"), "Invalid relative path"); Assert_Equals (T, "e", Get_Relative_Path ("/home/john/src/asf", "/home/john/src/asf/e"), "Invalid relative path"); Assert_Equals (T, ".", Get_Relative_Path ("/home/john/src/asf", "/home/john/src/asf/"), "Invalid relative path"); end Test_Get_Relative_Path; function Sys_Symlink (Target : in System.Address; Link : in System.Address) return Integer with Import => True, Convention => C, Link_Name => Util.Systems.Constants.SYMBOL_PREFIX & "symlink"; pragma Weak_External (Sys_Symlink); -- ------------------------------ -- Test the Delete_Tree operation. -- ------------------------------ procedure Test_Delete_Tree (T : in out Test) is use type System.Address; Path : constant String := Util.Tests.Get_Test_Path ("test-delete-tree"); begin if Ada.Directories.Exists (Path) then Delete_Tree (Path); end if; -- Create a directory tree with symlink links that point to a non-existing file. Ada.Directories.Create_Directory (Path); for I in 1 .. 10 loop declare P : constant String := Compose (Path, Util.Strings.Image (I)); S : String (1 .. P'Length + 3); R : Integer; begin Ada.Directories.Create_Directory (P); S (1 .. P'Length) := P; S (P'Length + 1) := '/'; S (P'Length + 2) := 'A'; S (S'Last) := ASCII.NUL; for J in 1 .. 5 loop Ada.Directories.Create_Path (Compose (P, Util.Strings.Image (J))); end loop; if Sys_Symlink'Address /= System.Null_Address then R := Sys_Symlink (S'Address, S'Address); end if; end; end loop; T.Assert (Ada.Directories.Exists (Path), "Directory must exist"); -- Ada.Directories.Delete_Tree (Path) fails to delete the tree. Delete_Tree (Path); T.Assert (not Ada.Directories.Exists (Path), "Directory must have been deleted"); end Test_Delete_Tree; end Util.Files.Tests;
Add Test_Delete_Tree and register the new test for execution The new test creates a directory tree with several symbolic links to missing files. The Ada.Directories.Delete_Tree procedure fails but the Util.Files.Delete_Tree must succeed.
Add Test_Delete_Tree and register the new test for execution The new test creates a directory tree with several symbolic links to missing files. The Ada.Directories.Delete_Tree procedure fails but the Util.Files.Delete_Tree must succeed.
Ada
apache-2.0
stcarrez/ada-util,stcarrez/ada-util
add88637b240d33ed6972218f5f8fe63390ae671
awa/regtests/awa-testsuite.adb
awa/regtests/awa-testsuite.adb
----------------------------------------------------------------------- -- Util testsuite - Util Testsuite -- 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 AWA.Users.Services.Tests; with AWA.Users.Tests; with AWA.Blogs.Services.Tests; with AWA.Wikis.Parsers.Tests; with AWA.Wikis.Writers.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.Services.Tests; with AWA.Votes.Modules.Tests; with AWA.Questions.Services.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.Converters.Dates; with AWA.Tests; with AWA.Services.Contexts; with AWA.Jobs.Services.Tests; with AWA.Jobs.Modules.Tests; with ASF.Server.Web; with ASF.Server.Tests; 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; 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; 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.Wikis.Parsers.Tests.Add_Tests (Ret); AWA.Wikis.Writers.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.Blogs.Services.Tests.Add_Tests (Ret); AWA.Storages.Services.Tests.Add_Tests (Ret); AWA.Images.Services.Tests.Add_Tests (Ret); AWA.Votes.Modules.Tests.Add_Tests (Ret); AWA.Questions.Services.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 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.Storages.Modules.NAME, URI => "storages", Module => Storages'Access); Register (App => Application.all'Access, Name => AWA.Images.Modules.NAME, URI => "images", Module => Images'Access); Register (App => Application.all'Access, Name => AWA.Jobs.Modules.NAME, URI => "jobs", Module => Jobs'Access); Register (App => Application.all'Access, Name => AWA.Votes.Modules.NAME, URI => "votes", Module => Votes'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); 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; ASF.Server.Tests.Set_Context (Application.all'Access); end; end if; end Initialize; end AWA.Testsuite;
----------------------------------------------------------------------- -- Util testsuite - Util Testsuite -- 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 AWA.Users.Services.Tests; with AWA.Users.Tests; with AWA.Blogs.Services.Tests; with AWA.Wikis.Parsers.Tests; with AWA.Wikis.Writers.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.Services.Tests; with AWA.Votes.Modules.Tests; with AWA.Questions.Modules.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.Converters.Dates; with AWA.Tests; with AWA.Services.Contexts; with AWA.Jobs.Services.Tests; with AWA.Jobs.Modules.Tests; with ASF.Server.Web; with ASF.Server.Tests; 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; 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; 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.Wikis.Parsers.Tests.Add_Tests (Ret); AWA.Wikis.Writers.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.Blogs.Services.Tests.Add_Tests (Ret); AWA.Storages.Services.Tests.Add_Tests (Ret); AWA.Images.Services.Tests.Add_Tests (Ret); AWA.Votes.Modules.Tests.Add_Tests (Ret); AWA.Questions.Modules.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 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.Storages.Modules.NAME, URI => "storages", Module => Storages'Access); Register (App => Application.all'Access, Name => AWA.Images.Modules.NAME, URI => "images", Module => Images'Access); Register (App => Application.all'Access, Name => AWA.Jobs.Modules.NAME, URI => "jobs", Module => Jobs'Access); Register (App => Application.all'Access, Name => AWA.Votes.Modules.NAME, URI => "votes", Module => Votes'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); 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; ASF.Server.Tests.Set_Context (Application.all'Access); end; end if; end Initialize; end AWA.Testsuite;
Update the testsuite
Update the testsuite
Ada
apache-2.0
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
f23a34248464b4a72b7574f308d254850d22620d
awa/src/awa-modules.adb
awa/src/awa-modules.adb
----------------------------------------------------------------------- -- awa -- Ada Web Application -- Copyright (C) 2009, 2010, 2011, 2012 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with ASF.Requests; with ASF.Responses; with ASF.Server; with Ada.IO_Exceptions; with Util.Files; with Util.Properties; with EL.Contexts.Default; with AWA.Modules.Reader; with AWA.Applications; package body AWA.Modules is -- ------------------------------ -- Get the module name -- ------------------------------ function Get_Name (Plugin : in Module) return String is begin return To_String (Plugin.Name); end Get_Name; -- ------------------------------ -- Get the base URI for this module -- ------------------------------ function Get_URI (Plugin : in Module) return String is begin return To_String (Plugin.URI); end Get_URI; -- ------------------------------ -- Get the application in which this module is registered. -- ------------------------------ function Get_Application (Plugin : in Module) return Application_Access is begin return Plugin.App; end Get_Application; -- ------------------------------ -- Get the module configuration property identified by the name. -- If the configuration property does not exist, returns the default value. -- ------------------------------ function Get_Config (Plugin : Module; Name : String; Default : String := "") return String is begin return Plugin.Config.Get (Name, Default); end Get_Config; -- ------------------------------ -- Get the module configuration property identified by the name. -- If the configuration property does not exist, returns the default value. -- ------------------------------ function Get_Config (Plugin : in Module; Name : in String; Default : in Integer := -1) return Integer is Value : constant String := Plugin.Config.Get (Name, Integer'Image (Default)); begin return Integer'Value (Value); exception when Constraint_Error => return Default; end Get_Config; -- ------------------------------ -- Get the module configuration property identified by the <tt>Config</tt> parameter. -- If the property does not exist, the default configuration value is returned. -- ------------------------------ function Get_Config (Plugin : in Module; Config : in ASF.Applications.Config_Param) return String is begin return Plugin.Config.Get (Config); end Get_Config; -- ------------------------------ -- Send the event to the module -- ------------------------------ procedure Send_Event (Plugin : in Module; Content : in AWA.Events.Module_Event'Class) is begin Plugin.App.Send_Event (Content); end Send_Event; -- ------------------------------ -- Find the module with the given name -- ------------------------------ function Find_Module (Plugin : Module; Name : String) return Module_Access is begin if Plugin.Registry = null then return null; end if; return Find_By_Name (Plugin.Registry.all, Name); end Find_Module; -- ------------------------------ -- Register under the given name a function to create the bean instance when -- it is accessed for a first time. The scope defines the scope of the bean. -- bean -- ------------------------------ procedure Register (Plugin : in out Module; Name : in String; Bind : in ASF.Beans.Class_Binding_Access) is begin Plugin.App.Register_Class (Name, Bind); end Register; -- ------------------------------ -- Finalize the module. -- ------------------------------ overriding procedure Finalize (Plugin : in out Module) is begin null; end Finalize; procedure Initialize (Manager : in out Module_Manager; Module : in AWA.Modules.Module'Class) is begin Manager.Module := Module.Self; end Initialize; function Get_Value (Manager : in Module_Manager; Name : in String) return Util.Beans.Objects.Object is pragma Unreferenced (Manager, Name); begin return Util.Beans.Objects.Null_Object; end Get_Value; -- Module manager -- -- ------------------------------ -- Get the database connection for reading -- ------------------------------ function Get_Session (Manager : Module_Manager) return ADO.Sessions.Session is begin return Manager.Module.Get_Session; end Get_Session; -- ------------------------------ -- Get the database connection for writing -- ------------------------------ function Get_Master_Session (Manager : Module_Manager) return ADO.Sessions.Master_Session is begin return Manager.Module.Get_Master_Session; end Get_Master_Session; -- ------------------------------ -- Send the event to the module. The module identified by <b>To</b> is -- found and the event is posted on its event channel. -- ------------------------------ procedure Send_Event (Manager : in Module_Manager; Content : in AWA.Events.Module_Event'Class) is begin Manager.Module.Send_Event (Content); end Send_Event; procedure Initialize (Plugin : in out Module; App : in Application_Access; Props : in ASF.Applications.Config) is pragma Unreferenced (Props); begin Plugin.Self := Plugin'Unchecked_Access; Plugin.App := App; end Initialize; -- ------------------------------ -- Initialize the registry -- ------------------------------ procedure Initialize (Registry : in out Module_Registry; Config : in ASF.Applications.Config) is begin Registry.Config := Config; end Initialize; -- ------------------------------ -- Register the module in the registry. -- ------------------------------ procedure Register (Registry : in Module_Registry_Access; App : in Application_Access; Plugin : in Module_Access; Name : in String; URI : in String) is procedure Copy (Params : in Util.Properties.Manager'Class); procedure Copy (Params : in Util.Properties.Manager'Class) is begin Plugin.Config.Copy (From => Params, Prefix => Name & ".", Strip => True); end Copy; Paths : constant String := Registry.Config.Get (Applications.P_Module_Dir.P); begin Log.Info ("Register module '{0}' under URI '{1}'", Name, URI); if Plugin.Registry /= null then Log.Error ("Module '{0}' is already attached to a registry", Name); raise Program_Error with "Module '" & Name & "' already registered"; end if; Plugin.App := App; Plugin.Registry := Registry; Plugin.Name := To_Unbounded_String (Name); Plugin.URI := To_Unbounded_String (URI); Plugin.Registry.Name_Map.Insert (Name, Plugin); if URI /= "" then Plugin.Registry.URI_Map.Insert (URI, Plugin); end if; -- Load the module configuration file Log.Debug ("Module search path: {0}", Paths); declare Base : constant String := Name & ".properties"; Path : constant String := Util.Files.Find_File_Path (Base, Paths); begin Plugin.Config.Load_Properties (Path => Path, Prefix => Name & ".", Strip => True); exception when Ada.IO_Exceptions.Name_Error => Log.Info ("Module configuration file '{0}' does not exist", Path); end; Plugin.Initialize (App, Plugin.Config); -- Read the module XML configuration file if there is one. declare Base : constant String := Plugin.Config.Get ("config", Name & ".xml"); Path : constant String := Util.Files.Find_File_Path (Base, Paths); Ctx : aliased EL.Contexts.Default.Default_Context; begin AWA.Modules.Reader.Read_Configuration (Plugin.all, Path, Ctx'Unchecked_Access); exception when Ada.IO_Exceptions.Name_Error => Log.Warn ("Module configuration file '{0}' does not exist", Path); end; -- Override the module configuration with the application configuration App.Get_Init_Parameters (Copy'Access); Plugin.Configure (Plugin.Config); exception when Constraint_Error => Log.Error ("Another module is already registered " & "under name '{0}' or URI '{1}'", Name, URI); raise; end Register; -- ------------------------------ -- Find the module with the given name -- ------------------------------ function Find_By_Name (Registry : Module_Registry; Name : String) return Module_Access is Pos : constant Module_Maps.Cursor := Module_Maps.Find (Registry.Name_Map, Name); begin if Module_Maps.Has_Element (Pos) then return Module_Maps.Element (Pos); end if; return null; end Find_By_Name; -- ------------------------------ -- Find the module mapped to a given URI -- ------------------------------ function Find_By_URI (Registry : Module_Registry; URI : String) return Module_Access is Pos : constant Module_Maps.Cursor := Module_Maps.Find (Registry.URI_Map, URI); begin if Module_Maps.Has_Element (Pos) then return Module_Maps.Element (Pos); end if; return null; end Find_By_URI; -- ------------------------------ -- Iterate over the modules that have been registered and execute the <b>Process</b> -- procedure on each of the module instance. -- ------------------------------ procedure Iterate (Registry : in Module_Registry; Process : access procedure (Plugin : in out Module'Class)) is Iter : Module_Maps.Cursor := Registry.Name_Map.First; begin while Module_Maps.Has_Element (Iter) loop Process (Module_Maps.Element (Iter).all); Module_Maps.Next (Iter); end loop; end Iterate; -- ------------------------------ -- Get the database connection for reading -- ------------------------------ function Get_Session (Manager : Module) return ADO.Sessions.Session is begin return Manager.App.Get_Session; end Get_Session; -- ------------------------------ -- Get the database connection for writing -- ------------------------------ function Get_Master_Session (Manager : Module) return ADO.Sessions.Master_Session is begin return Manager.App.Get_Master_Session; end Get_Master_Session; -- ------------------------------ -- Add a listener to the module listner list. The module will invoke the listner -- depending on events or actions that occur in the module. -- ------------------------------ procedure Add_Listener (Into : in out Module; Item : in Util.Listeners.Listener_Access) is begin Util.Listeners.Add_Listener (Into.Listeners, Item); end Add_Listener; -- ------------------------------ -- Remove a listener from the module listener list. -- ------------------------------ procedure Remove_Listener (Into : in out Module; Item : in Util.Listeners.Listener_Access) is begin Util.Listeners.Remove_Listener (Into.Listeners, Item); end Remove_Listener; -- Get per request manager => look in Request -- Get per session manager => look in Request.Get_Session -- Get per application manager => look in Application -- Get per pool manager => look in pool attached to Application function Get_Manager return Manager_Type_Access is procedure Process (Request : in out ASF.Requests.Request'Class; Response : in out ASF.Responses.Response'Class); Value : Util.Beans.Objects.Object; procedure Process (Request : in out ASF.Requests.Request'Class; Response : in out ASF.Responses.Response'Class) is pragma Unreferenced (Response); begin Value := Request.Get_Attribute (Name); if Util.Beans.Objects.Is_Null (Value) then declare M : constant Manager_Type_Access := new Manager_Type; begin Value := Util.Beans.Objects.To_Object (M.all'Unchecked_Access); Request.Set_Attribute (Name, Value); end; end if; end Process; begin ASF.Server.Update_Context (Process'Access); if Util.Beans.Objects.Is_Null (Value) then return null; end if; declare B : constant access Util.Beans.Basic.Readonly_Bean'Class := Util.Beans.Objects.To_Bean (Value); begin if not (B.all in Manager_Type'Class) then return null; end if; return Manager_Type'Class (B.all)'Unchecked_Access; end; end Get_Manager; end AWA.Modules;
----------------------------------------------------------------------- -- awa -- Ada Web Application -- Copyright (C) 2009, 2010, 2011, 2012, 2015 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with ASF.Requests; with ASF.Responses; with ASF.Server; with Ada.IO_Exceptions; with Util.Files; with Util.Properties; with EL.Contexts.Default; with AWA.Modules.Reader; with AWA.Applications; package body AWA.Modules is -- ------------------------------ -- Get the module name -- ------------------------------ function Get_Name (Plugin : in Module) return String is begin return To_String (Plugin.Name); end Get_Name; -- ------------------------------ -- Get the base URI for this module -- ------------------------------ function Get_URI (Plugin : in Module) return String is begin return To_String (Plugin.URI); end Get_URI; -- ------------------------------ -- Get the application in which this module is registered. -- ------------------------------ function Get_Application (Plugin : in Module) return Application_Access is begin return Plugin.App; end Get_Application; -- ------------------------------ -- Get the module configuration property identified by the name. -- If the configuration property does not exist, returns the default value. -- ------------------------------ function Get_Config (Plugin : Module; Name : String; Default : String := "") return String is begin return Plugin.Config.Get (Name, Default); end Get_Config; -- ------------------------------ -- Get the module configuration property identified by the name. -- If the configuration property does not exist, returns the default value. -- ------------------------------ function Get_Config (Plugin : in Module; Name : in String; Default : in Integer := -1) return Integer is Value : constant String := Plugin.Config.Get (Name, Integer'Image (Default)); begin return Integer'Value (Value); exception when Constraint_Error => return Default; end Get_Config; -- ------------------------------ -- Get the module configuration property identified by the <tt>Config</tt> parameter. -- If the property does not exist, the default configuration value is returned. -- ------------------------------ function Get_Config (Plugin : in Module; Config : in ASF.Applications.Config_Param) return String is begin return Plugin.Config.Get (Config); end Get_Config; -- ------------------------------ -- Send the event to the module -- ------------------------------ procedure Send_Event (Plugin : in Module; Content : in AWA.Events.Module_Event'Class) is begin Plugin.App.Send_Event (Content); end Send_Event; -- ------------------------------ -- Find the module with the given name -- ------------------------------ function Find_Module (Plugin : Module; Name : String) return Module_Access is begin if Plugin.Registry = null then return null; end if; return Find_By_Name (Plugin.Registry.all, Name); end Find_Module; -- ------------------------------ -- Register under the given name a function to create the bean instance when -- it is accessed for a first time. The scope defines the scope of the bean. -- bean -- ------------------------------ procedure Register (Plugin : in out Module; Name : in String; Bind : in ASF.Beans.Class_Binding_Access) is begin Plugin.App.Register_Class (Name, Bind); end Register; -- ------------------------------ -- Finalize the module. -- ------------------------------ overriding procedure Finalize (Plugin : in out Module) is begin null; end Finalize; procedure Initialize (Manager : in out Module_Manager; Module : in AWA.Modules.Module'Class) is begin Manager.Module := Module.Self; end Initialize; function Get_Value (Manager : in Module_Manager; Name : in String) return Util.Beans.Objects.Object is pragma Unreferenced (Manager, Name); begin return Util.Beans.Objects.Null_Object; end Get_Value; -- Module manager -- -- ------------------------------ -- Get the database connection for reading -- ------------------------------ function Get_Session (Manager : Module_Manager) return ADO.Sessions.Session is begin return Manager.Module.Get_Session; end Get_Session; -- ------------------------------ -- Get the database connection for writing -- ------------------------------ function Get_Master_Session (Manager : Module_Manager) return ADO.Sessions.Master_Session is begin return Manager.Module.Get_Master_Session; end Get_Master_Session; -- ------------------------------ -- Send the event to the module. The module identified by <b>To</b> is -- found and the event is posted on its event channel. -- ------------------------------ procedure Send_Event (Manager : in Module_Manager; Content : in AWA.Events.Module_Event'Class) is begin Manager.Module.Send_Event (Content); end Send_Event; procedure Initialize (Plugin : in out Module; App : in Application_Access; Props : in ASF.Applications.Config) is pragma Unreferenced (Props); begin Plugin.Self := Plugin'Unchecked_Access; Plugin.App := App; end Initialize; -- ------------------------------ -- Initialize the registry -- ------------------------------ procedure Initialize (Registry : in out Module_Registry; Config : in ASF.Applications.Config) is begin Registry.Config := Config; end Initialize; -- ------------------------------ -- Register the module in the registry. -- ------------------------------ procedure Register (Registry : in Module_Registry_Access; App : in Application_Access; Plugin : in Module_Access; Name : in String; URI : in String) is procedure Copy (Params : in Util.Properties.Manager'Class); procedure Copy (Params : in Util.Properties.Manager'Class) is begin Plugin.Config.Copy (From => Params, Prefix => Name & ".", Strip => True); end Copy; Paths : constant String := Registry.Config.Get (Applications.P_Module_Dir.P); begin Log.Info ("Register module '{0}' under URI '{1}'", Name, URI); if Plugin.Registry /= null then Log.Error ("Module '{0}' is already attached to a registry", Name); raise Program_Error with "Module '" & Name & "' already registered"; end if; Plugin.App := App; Plugin.Registry := Registry; Plugin.Name := To_Unbounded_String (Name); Plugin.URI := To_Unbounded_String (URI); Plugin.Registry.Name_Map.Insert (Name, Plugin); if URI /= "" then Plugin.Registry.URI_Map.Insert (URI, Plugin); end if; -- Load the module configuration file Log.Debug ("Module search path: {0}", Paths); declare Base : constant String := Name & ".properties"; Path : constant String := Util.Files.Find_File_Path (Base, Paths); begin Plugin.Config.Load_Properties (Path => Path, Prefix => Name & ".", Strip => True); exception when Ada.IO_Exceptions.Name_Error => Log.Info ("Module configuration file '{0}' does not exist", Path); end; Plugin.Initialize (App, Plugin.Config); -- Read the module XML configuration file if there is one. declare Base : constant String := Plugin.Config.Get ("config", Name & ".xml"); Path : constant String := Util.Files.Find_File_Path (Base, Paths); Ctx : aliased EL.Contexts.Default.Default_Context; begin AWA.Modules.Reader.Read_Configuration (Plugin.all, Path, Ctx'Unchecked_Access); exception when Ada.IO_Exceptions.Name_Error => Log.Warn ("Module configuration file '{0}' does not exist", Path); end; -- Override the module configuration with the application configuration App.Get_Init_Parameters (Copy'Access); Plugin.Configure (Plugin.Config); exception when Constraint_Error => Log.Error ("Another module is already registered " & "under name '{0}' or URI '{1}'", Name, URI); raise; end Register; -- ------------------------------ -- Find the module with the given name -- ------------------------------ function Find_By_Name (Registry : Module_Registry; Name : String) return Module_Access is Pos : constant Module_Maps.Cursor := Module_Maps.Find (Registry.Name_Map, Name); begin if Module_Maps.Has_Element (Pos) then return Module_Maps.Element (Pos); end if; return null; end Find_By_Name; -- ------------------------------ -- Find the module mapped to a given URI -- ------------------------------ function Find_By_URI (Registry : Module_Registry; URI : String) return Module_Access is Pos : constant Module_Maps.Cursor := Module_Maps.Find (Registry.URI_Map, URI); begin if Module_Maps.Has_Element (Pos) then return Module_Maps.Element (Pos); end if; return null; end Find_By_URI; -- ------------------------------ -- Iterate over the modules that have been registered and execute the <b>Process</b> -- procedure on each of the module instance. -- ------------------------------ procedure Iterate (Registry : in Module_Registry; Process : access procedure (Plugin : in out Module'Class)) is Iter : Module_Maps.Cursor := Registry.Name_Map.First; begin while Module_Maps.Has_Element (Iter) loop Process (Module_Maps.Element (Iter).all); Module_Maps.Next (Iter); end loop; end Iterate; -- ------------------------------ -- Get the database connection for reading -- ------------------------------ function Get_Session (Manager : Module) return ADO.Sessions.Session is begin return Manager.App.Get_Session; end Get_Session; -- ------------------------------ -- Get the database connection for writing -- ------------------------------ function Get_Master_Session (Manager : Module) return ADO.Sessions.Master_Session is begin return Manager.App.Get_Master_Session; end Get_Master_Session; -- ------------------------------ -- Add a listener to the module listner list. The module will invoke the listner -- depending on events or actions that occur in the module. -- ------------------------------ procedure Add_Listener (Into : in out Module; Item : in Util.Listeners.Listener_Access) is begin Util.Listeners.Add_Listener (Into.Listeners, Item); end Add_Listener; -- ------------------------------ -- Find the module with the given name in the application and add the listener to the -- module listener list. -- ------------------------------ procedure Add_Listener (Plugin : in Module; Name : in String; Item : in Util.Listeners.Listener_Access) is M : constant Module_Access := Plugin.App.Find_Module (Name); begin if M = null then Log.Error ("Cannot find module {0} to add a lifecycle listener", Name); else M.Add_Listener (Item); end if; end Add_Listener; -- ------------------------------ -- Remove a listener from the module listener list. -- ------------------------------ procedure Remove_Listener (Into : in out Module; Item : in Util.Listeners.Listener_Access) is begin Util.Listeners.Remove_Listener (Into.Listeners, Item); end Remove_Listener; -- Get per request manager => look in Request -- Get per session manager => look in Request.Get_Session -- Get per application manager => look in Application -- Get per pool manager => look in pool attached to Application function Get_Manager return Manager_Type_Access is procedure Process (Request : in out ASF.Requests.Request'Class; Response : in out ASF.Responses.Response'Class); Value : Util.Beans.Objects.Object; procedure Process (Request : in out ASF.Requests.Request'Class; Response : in out ASF.Responses.Response'Class) is pragma Unreferenced (Response); begin Value := Request.Get_Attribute (Name); if Util.Beans.Objects.Is_Null (Value) then declare M : constant Manager_Type_Access := new Manager_Type; begin Value := Util.Beans.Objects.To_Object (M.all'Unchecked_Access); Request.Set_Attribute (Name, Value); end; end if; end Process; begin ASF.Server.Update_Context (Process'Access); if Util.Beans.Objects.Is_Null (Value) then return null; end if; declare B : constant access Util.Beans.Basic.Readonly_Bean'Class := Util.Beans.Objects.To_Bean (Value); begin if not (B.all in Manager_Type'Class) then return null; end if; return Manager_Type'Class (B.all)'Unchecked_Access; end; end Get_Manager; end AWA.Modules;
Implement the Add_Listener procedure
Implement the Add_Listener procedure
Ada
apache-2.0
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
ff80ebdc377bb0253e3a1c0344d37d7e793fbfe7
src/asf-security-servlets.adb
src/asf-security-servlets.adb
----------------------------------------------------------------------- -- security-openid-servlets - Servlets for OpenID 2.0 Authentication -- 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 ASF.Sessions; with Util.Beans.Objects; with Util.Beans.Objects.Records; with Util.Log.Loggers; package body ASF.Security.Servlets is use Util.Log; -- The logger Log : constant Loggers.Logger := Loggers.Create ("Security.Openid.Servlets"); -- Make a package to store the Association in the session. package Association_Bean is new Util.Beans.Objects.Records (Openid.Association); subtype Association_Access is Association_Bean.Element_Type_Access; -- ------------------------------ -- Called by the servlet container to indicate to a servlet that the servlet -- is being placed into service. -- ------------------------------ procedure Initialize (Server : in out Openid_Servlet; Context : in ASF.Servlets.Servlet_Registry'Class) is begin null; end Initialize; -- Property name that specifies the OpenID callback URL. OPENID_VERIFY_URL : constant String := "openid.callback_url"; -- Property name that specifies the realm. OPENID_REALM : constant String := "openid.realm"; -- Name of the session attribute which holds information about the active authentication. OPENID_ASSOC_ATTRIBUTE : constant String := "openid-assoc"; procedure Initialize (Server : in Openid_Servlet; Manager : in out OpenID.Manager) is Ctx : constant ASF.Servlets.Servlet_Registry_Access := Server.Get_Servlet_Context; Callback_URI : constant String := Ctx.Get_Init_Parameter (OPENID_VERIFY_URL); Realm : constant String := Ctx.Get_Init_Parameter (OPENID_REALM); begin Manager.Initialize (Return_To => Callback_URI, Name => Realm); end Initialize; function Get_Provider_URL (Server : in Request_Auth_Servlet; Request : in ASF.Requests.Request'Class) return String is Ctx : constant ASF.Servlets.Servlet_Registry_Access := Server.Get_Servlet_Context; URI : constant String := Request.Get_Path_Info; begin if URI'Length = 0 then return ""; end if; Log.Info ("OpenID authentication with {0}", URI); return Ctx.Get_Init_Parameter ("openid.provider." & URI (URI'First + 1 .. URI'Last)); end Get_Provider_URL; -- ------------------------------ -- Proceed to the OpenID authentication with an OpenID provider. -- Find the OpenID provider URL and starts the discovery, association phases -- during which a private key is obtained from the OpenID provider. -- After OpenID discovery and association, the user will be redirected to -- the OpenID provider. -- ------------------------------ procedure Do_Get (Server : in Request_Auth_Servlet; Request : in out ASF.Requests.Request'Class; Response : in out ASF.Responses.Response'Class) is Provider : constant String := Server.Get_Provider_URL (Request); begin Log.Info ("Request OpenId authentication to {0}", Provider); if Provider'Length = 0 then Response.Set_Status (ASF.Responses.SC_NOT_FOUND); return; end if; declare Mgr : OpenID.Manager; OP : OpenID.End_Point; Bean : constant Util.Beans.Objects.Object := Association_Bean.Create; Assoc : constant Association_Access := Association_Bean.To_Element_Access (Bean); begin Server.Initialize (Mgr); -- Yadis discovery (get the XRDS file). Mgr.Discover (Provider, OP); -- Associate to the OpenID provider and get an end-point with a key. Mgr.Associate (OP, Assoc.all); -- Save the association in the HTTP session and -- redirect the user to the OpenID provider. declare Auth_URL : constant String := Mgr.Get_Authentication_URL (OP, Assoc.all); Session : ASF.Sessions.Session := Request.Get_Session (Create => True); begin Log.Info ("Redirect to auth URL: {0}", Auth_URL); Response.Send_Redirect (Location => Auth_URL); Session.Set_Attribute (Name => OPENID_ASSOC_ATTRIBUTE, Value => Bean); end; end; end Do_Get; -- ------------------------------ -- Verify the authentication result that was returned by the OpenID provider. -- If the authentication succeeded and the signature was correct, sets a -- user principals on the session. -- ------------------------------ procedure Do_Get (Server : in Verify_Auth_Servlet; Request : in out ASF.Requests.Request'Class; Response : in out ASF.Responses.Response'Class) is use type OpenID.Auth_Result; type Auth_Params is new OpenID.Parameters with null record; overriding function Get_Parameter (Params : in Auth_Params; Name : in String) return String; overriding function Get_Parameter (Params : in Auth_Params; Name : in String) return String is pragma Unreferenced (Params); begin return Request.Get_Parameter (Name); end Get_Parameter; Session : ASF.Sessions.Session := Request.Get_Session (Create => False); Bean : Util.Beans.Objects.Object; Mgr : OpenID.Manager; Assoc : Association_Access; Auth : OpenID.Authentication; Params : Auth_Params; Ctx : constant ASF.Servlets.Servlet_Registry_Access := Server.Get_Servlet_Context; begin Log.Info ("Verify openid authentication"); if not Session.Is_Valid then Log.Warn ("Session has expired during OpenID authentication process"); Response.Set_Status (ASF.Responses.SC_FORBIDDEN); return; end if; Bean := Session.Get_Attribute (OPENID_ASSOC_ATTRIBUTE); -- Cleanup the session and drop the association end point. Session.Remove_Attribute (OPENID_ASSOC_ATTRIBUTE); if Util.Beans.Objects.Is_Null (Bean) then Log.Warn ("Verify openid request without active session"); Response.Set_Status (ASF.Responses.SC_FORBIDDEN); return; end if; Assoc := Association_Bean.To_Element_Access (Bean); Server.Initialize (Mgr); -- Verify that what we receive through the callback matches the association key. Mgr.Verify (Assoc.all, Params, Auth); if OpenID.Get_Status (Auth) /= OpenID.AUTHENTICATED then Log.Info ("Authentication has failed"); Response.Set_Status (ASF.Responses.SC_FORBIDDEN); return; end if; Log.Info ("Authentication succeeded for {0}", OpenID.Get_Email (Auth)); -- Get a user principal and set it on the session. declare User : ASF.Principals.Principal_Access; URL : constant String := Ctx.Get_Init_Parameter ("openid.success_url"); begin Verify_Auth_Servlet'Class (Server).Create_Principal (Auth, User); Session.Set_Principal (User); Log.Info ("Redirect user to success URL: {0}", URL); Response.Send_Redirect (Location => URL); end; end Do_Get; -- ------------------------------ -- Create a principal object that correspond to the authenticated user identified -- by the <b>Auth</b> information. The principal will be attached to the session -- and will be destroyed when the session is closed. -- ------------------------------ procedure Create_Principal (Server : in Verify_Auth_Servlet; Auth : in OpenID.Authentication; Result : out ASF.Principals.Principal_Access) is pragma Unreferenced (Server); P : constant OpenID.Principal_Access := OpenID.Create_Principal (Auth); begin Result := P.all'Access; end Create_Principal; end ASF.Security.Servlets;
----------------------------------------------------------------------- -- security-openid-servlets - Servlets for OpenID 2.0 Authentication -- 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 ASF.Sessions; with Util.Beans.Objects; with Util.Beans.Objects.Records; with Util.Log.Loggers; package body ASF.Security.Servlets is -- The logger Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("Security.Servlets"); -- Make a package to store the Association in the session. package Association_Bean is new Util.Beans.Objects.Records (OpenID.Association); subtype Association_Access is Association_Bean.Element_Type_Access; -- ------------------------------ -- Called by the servlet container to indicate to a servlet that the servlet -- is being placed into service. -- ------------------------------ procedure Initialize (Server : in out Openid_Servlet; Context : in ASF.Servlets.Servlet_Registry'Class) is begin null; end Initialize; -- Property name that specifies the OpenID callback URL. OPENID_VERIFY_URL : constant String := "openid.callback_url"; -- Property name that specifies the realm. OPENID_REALM : constant String := "openid.realm"; -- Name of the session attribute which holds information about the active authentication. OPENID_ASSOC_ATTRIBUTE : constant String := "openid-assoc"; procedure Initialize (Server : in Openid_Servlet; Manager : in out OpenID.Manager) is Ctx : constant ASF.Servlets.Servlet_Registry_Access := Server.Get_Servlet_Context; Callback_URI : constant String := Ctx.Get_Init_Parameter (OPENID_VERIFY_URL); Realm : constant String := Ctx.Get_Init_Parameter (OPENID_REALM); begin Manager.Initialize (Return_To => Callback_URI, Name => Realm); end Initialize; function Get_Provider_URL (Server : in Request_Auth_Servlet; Request : in ASF.Requests.Request'Class) return String is Ctx : constant ASF.Servlets.Servlet_Registry_Access := Server.Get_Servlet_Context; URI : constant String := Request.Get_Path_Info; begin if URI'Length = 0 then return ""; end if; Log.Info ("OpenID authentication with {0}", URI); return Ctx.Get_Init_Parameter ("openid.provider." & URI (URI'First + 1 .. URI'Last)); end Get_Provider_URL; -- ------------------------------ -- Proceed to the OpenID authentication with an OpenID provider. -- Find the OpenID provider URL and starts the discovery, association phases -- during which a private key is obtained from the OpenID provider. -- After OpenID discovery and association, the user will be redirected to -- the OpenID provider. -- ------------------------------ procedure Do_Get (Server : in Request_Auth_Servlet; Request : in out ASF.Requests.Request'Class; Response : in out ASF.Responses.Response'Class) is Provider : constant String := Server.Get_Provider_URL (Request); begin Log.Info ("Request OpenId authentication to {0}", Provider); if Provider'Length = 0 then Response.Set_Status (ASF.Responses.SC_NOT_FOUND); return; end if; declare Mgr : OpenID.Manager; OP : OpenID.End_Point; Bean : constant Util.Beans.Objects.Object := Association_Bean.Create; Assoc : constant Association_Access := Association_Bean.To_Element_Access (Bean); begin Server.Initialize (Mgr); -- Yadis discovery (get the XRDS file). Mgr.Discover (Provider, OP); -- Associate to the OpenID provider and get an end-point with a key. Mgr.Associate (OP, Assoc.all); -- Save the association in the HTTP session and -- redirect the user to the OpenID provider. declare Auth_URL : constant String := Mgr.Get_Authentication_URL (OP, Assoc.all); Session : ASF.Sessions.Session := Request.Get_Session (Create => True); begin Log.Info ("Redirect to auth URL: {0}", Auth_URL); Response.Send_Redirect (Location => Auth_URL); Session.Set_Attribute (Name => OPENID_ASSOC_ATTRIBUTE, Value => Bean); end; end; end Do_Get; -- ------------------------------ -- Verify the authentication result that was returned by the OpenID provider. -- If the authentication succeeded and the signature was correct, sets a -- user principals on the session. -- ------------------------------ procedure Do_Get (Server : in Verify_Auth_Servlet; Request : in out ASF.Requests.Request'Class; Response : in out ASF.Responses.Response'Class) is use type OpenID.Auth_Result; type Auth_Params is new OpenID.Parameters with null record; overriding function Get_Parameter (Params : in Auth_Params; Name : in String) return String; overriding function Get_Parameter (Params : in Auth_Params; Name : in String) return String is pragma Unreferenced (Params); begin return Request.Get_Parameter (Name); end Get_Parameter; Session : ASF.Sessions.Session := Request.Get_Session (Create => False); Bean : Util.Beans.Objects.Object; Mgr : OpenID.Manager; Assoc : Association_Access; Auth : OpenID.Authentication; Params : Auth_Params; Ctx : constant ASF.Servlets.Servlet_Registry_Access := Server.Get_Servlet_Context; begin Log.Info ("Verify openid authentication"); if not Session.Is_Valid then Log.Warn ("Session has expired during OpenID authentication process"); Response.Set_Status (ASF.Responses.SC_FORBIDDEN); return; end if; Bean := Session.Get_Attribute (OPENID_ASSOC_ATTRIBUTE); -- Cleanup the session and drop the association end point. Session.Remove_Attribute (OPENID_ASSOC_ATTRIBUTE); if Util.Beans.Objects.Is_Null (Bean) then Log.Warn ("Verify openid request without active session"); Response.Set_Status (ASF.Responses.SC_FORBIDDEN); return; end if; Assoc := Association_Bean.To_Element_Access (Bean); Server.Initialize (Mgr); -- Verify that what we receive through the callback matches the association key. Mgr.Verify (Assoc.all, Params, Auth); if OpenID.Get_Status (Auth) /= OpenID.AUTHENTICATED then Log.Info ("Authentication has failed"); Response.Set_Status (ASF.Responses.SC_FORBIDDEN); return; end if; Log.Info ("Authentication succeeded for {0}", OpenID.Get_Email (Auth)); -- Get a user principal and set it on the session. declare User : ASF.Principals.Principal_Access; URL : constant String := Ctx.Get_Init_Parameter ("openid.success_url"); begin Verify_Auth_Servlet'Class (Server).Create_Principal (Auth, User); Session.Set_Principal (User); Log.Info ("Redirect user to success URL: {0}", URL); Response.Send_Redirect (Location => URL); end; end Do_Get; -- ------------------------------ -- Create a principal object that correspond to the authenticated user identified -- by the <b>Auth</b> information. The principal will be attached to the session -- and will be destroyed when the session is closed. -- ------------------------------ procedure Create_Principal (Server : in Verify_Auth_Servlet; Auth : in OpenID.Authentication; Result : out ASF.Principals.Principal_Access) is pragma Unreferenced (Server); P : constant OpenID.Principal_Access := OpenID.Create_Principal (Auth); begin Result := P.all'Access; end Create_Principal; end ASF.Security.Servlets;
Fix compilation warning
Fix compilation warning
Ada
apache-2.0
stcarrez/ada-asf,stcarrez/ada-asf,stcarrez/ada-asf
126694a12fb61618c4ecb18139ba291adf91943c
regtests/security-policies-tests.adb
regtests/security-policies-tests.adb
----------------------------------------------------------------------- -- Security-policies-tests - Unit tests for Security.Permissions -- Copyright (C) 2011, 2012, 2013 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Files; with Util.Test_Caller; with Util.Measures; with Security.Contexts; with Security.Policies.Roles; with Security.Permissions.Tests; with Security.Policies.URLs; package body Security.Policies.Tests is use Util.Tests; procedure Configure_Policy (Manager : in out Security.Policies.Policy_Manager; Name : in String); package Caller is new Util.Test_Caller (Test, "Security.Policies"); procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is begin Caller.Add_Test (Suite, "Test Security.Permissions.Create_Role", Test_Create_Role'Access); Caller.Add_Test (Suite, "Test Security.Permissions.Has_Permission", Test_Has_Permission'Access); Caller.Add_Test (Suite, "Test Security.Permissions.Read_Policy (empty)", Test_Read_Empty_Policy'Access); Caller.Add_Test (Suite, "Test Security.Policies.Add_Policy", Test_Get_Role_Policy'Access); Caller.Add_Test (Suite, "Test Security.Policies.Get_Policy", Test_Get_Role_Policy'Access); Caller.Add_Test (Suite, "Test Security.Policies.Roles.Get_Role_Policy", Test_Get_Role_Policy'Access); Caller.Add_Test (Suite, "Test Security.Policies.Read_Policy", Test_Read_Policy'Access); Caller.Add_Test (Suite, "Test Security.Policies.Roles.Set_Roles", Test_Set_Roles'Access); Caller.Add_Test (Suite, "Test Security.Policies.Roles.Set_Roles (invalid)", Test_Set_Invalid_Roles'Access); -- These tests are identical but registered under different names -- for the test documentation. Caller.Add_Test (Suite, "Test Security.Contexts.Has_Permission", Test_Role_Policy'Access); Caller.Add_Test (Suite, "Test Security.Controllers.Roles.Has_Permission", Test_Role_Policy'Access); Caller.Add_Test (Suite, "Test Security.Permissions.Role_Policy", Test_Role_Policy'Access); Caller.Add_Test (Suite, "Test Security.Contexts.Has_Permission (all-permission)", Test_Anonymous_Permission'Access); Caller.Add_Test (Suite, "Test Security.Contexts.Has_Permission (auth-permission)", Test_Anonymous_Permission'Access); end Add_Tests; -- ------------------------------ -- Get the roles assigned to the user. -- ------------------------------ function Get_Roles (User : in Test_Principal) return Roles.Role_Map is begin return User.Roles; end Get_Roles; -- ------------------------------ -- Get the principal name. -- ------------------------------ function Get_Name (From : in Test_Principal) return String is begin return Util.Strings.To_String (From.Name); end Get_Name; -- ------------------------------ -- Test Create_Role and Get_Role_Name -- ------------------------------ procedure Test_Create_Role (T : in out Test) is use Security.Policies.Roles; M : Security.Policies.Roles.Role_Policy; Role : Role_Type; begin M.Create_Role (Name => "admin", Role => Role); Assert_Equals (T, "admin", M.Get_Role_Name (Role), "Invalid name"); for I in Role + 1 .. Role_Type'Last loop declare Name : constant String := "admin-" & Role_Type'Image (I); Role2 : Role_Type; begin Role2 := M.Find_Role ("admin"); T.Assert (Role2 = Role, "Find_Role returned an invalid role"); M.Create_Role (Name => Name, Role => Role2); Assert_Equals (T, Name, M.Get_Role_Name (Role2), "Invalid name"); end; end loop; end Test_Create_Role; -- ------------------------------ -- Test Set_Roles -- ------------------------------ procedure Test_Set_Roles (T : in out Test) is use Security.Policies.Roles; M : Security.Policies.Roles.Role_Policy; Admin : Role_Type; Manager : Role_Type; Map : Role_Map := (others => false); begin M.Create_Role (Name => "manager", Role => Manager); M.Create_Role (Name => "admin", Role => Admin); Assert_Equals (T, "admin", M.Get_Role_Name (Admin), "Invalid name"); T.Assert (not Map (Admin), "The admin role must not set in the map"); M.Set_Roles ("admin", Map); T.Assert (Map (Admin), "The admin role is not set in the map"); T.Assert (not Map (Manager), "The manager role must not be set in the map"); M.Set_Roles ("manager,admin", Map); T.Assert (Map (Admin), "The admin role is not set in the map"); T.Assert (Map (Manager), "The manager role is not set in the map"); end Test_Set_Roles; -- ------------------------------ -- Test Set_Roles on an invalid role name -- ------------------------------ procedure Test_Set_Invalid_Roles (T : in out Test) is use Security.Policies.Roles; M : Security.Policies.Roles.Role_Policy; Map : Role_Map := (others => False); begin M.Set_Roles ("manager,admin", Map); T.Assert (False, "No exception was raised"); exception when E : Security.Policies.Roles.Invalid_Name => null; end Test_Set_Invalid_Roles; -- ------------------------------ -- Test Has_Permission -- ------------------------------ procedure Test_Has_Permission (T : in out Test) is M : Security.Policies.Policy_Manager (1); -- Perm : Permissions.Permission_Type; User : Test_Principal; begin -- T.Assert (not M.Has_Permission (User, 1), "User has a non-existing permission"); null; end Test_Has_Permission; procedure Configure_Policy (Manager : in out Security.Policies.Policy_Manager; Name : in String) is Dir : constant String := "regtests/files/permissions/"; Path : constant String := Util.Tests.Get_Path (Dir); R : constant Security.Policies.Roles.Role_Policy_Access := new Roles.Role_Policy; U : constant Security.Policies.URLs.URL_Policy_Access := new URLs.URL_Policy; begin Manager.Add_Policy (R.all'Access); Manager.Add_Policy (U.all'Access); Manager.Read_Policy (Util.Files.Compose (Path, Name)); end Configure_Policy; -- ------------------------------ -- Test the Get_Policy, Get_Role_Policy and Add_Policy operations. -- ------------------------------ procedure Test_Get_Role_Policy (T : in out Test) is use type Roles.Role_Policy_Access; M : aliased Security.Policies.Policy_Manager (Max_Policies => 2); P : Security.Policies.Policy_Access; R : Security.Policies.Roles.Role_Policy_Access; begin P := M.Get_Policy (Security.Policies.Roles.NAME); T.Assert (P = null, "Get_Policy succeeded"); R := Security.Policies.Roles.Get_Role_Policy (M); T.Assert (R = null, "Get_Role_Policy succeeded"); R := new Roles.Role_Policy; M.Add_Policy (R.all'Access); P := M.Get_Policy (Security.Policies.Roles.NAME); T.Assert (P /= null, "Role policy not found"); T.Assert (P.all in Roles.Role_Policy'Class, "Invalid role policy"); R := Security.Policies.Roles.Get_Role_Policy (M); T.Assert (R /= null, "Get_Role_Policy should not return null"); end Test_Get_Role_Policy; -- ------------------------------ -- Test reading an empty policy file -- ------------------------------ procedure Test_Read_Empty_Policy (T : in out Test) is M : aliased Security.Policies.Policy_Manager (Max_Policies => 2); User : aliased Test_Principal; Context : aliased Security.Contexts.Security_Context; R : Security.Policies.Roles.Role_Policy_Access; begin Configure_Policy (M, "empty.xml"); Context.Set_Context (Manager => M'Unchecked_Access, Principal => User'Unchecked_Access); R := Security.Policies.Roles.Get_Role_Policy (M); declare Admin : Policies.Roles.Role_Type; pragma Unreferenced (Admin); begin Admin := R.Find_Role ("admin"); T.Fail ("'admin' role was returned"); exception when Security.Policies.Roles.Invalid_Name => null; end; T.Assert (not Contexts.Has_Permission (Permissions.Tests.P_Admin.Permission), "Has_Permission (admin) failed for empty policy"); T.Assert (not Contexts.Has_Permission (Permissions.Tests.P_Create.Permission), "Has_Permission (create) failed for empty policy"); T.Assert (not Contexts.Has_Permission (Permissions.Tests.P_Update.Permission), "Has_Permission (update) failed for empty policy"); T.Assert (not Contexts.Has_Permission (Permissions.Tests.P_Delete.Permission), "Has_Permission (delete) failed for empty policy"); end Test_Read_Empty_Policy; -- ------------------------------ -- Test reading policy files -- ------------------------------ procedure Test_Read_Policy (T : in out Test) is use Security.Permissions.Tests; M : aliased Security.Policies.Policy_Manager (Max_Policies => 2); User : aliased Test_Principal; Admin : Policies.Roles.Role_Type; Context : aliased Security.Contexts.Security_Context; R : Security.Policies.Roles.Role_Policy_Access; begin Configure_Policy (M, "simple-policy.xml"); Context.Set_Context (Manager => M'Unchecked_Access, Principal => User'Unchecked_Access); R := Security.Policies.Roles.Get_Role_Policy (M); Admin := R.Find_Role ("admin"); T.Assert (not Contexts.Has_Permission (Permission => P_Admin.Permission), "Permission was granted but user has no role"); User.Roles (Admin) := True; T.Assert (Contexts.Has_Permission (Permission => P_Admin.Permission), "Permission was not granted and user has admin role"); declare S : Util.Measures.Stamp; Result : Boolean; begin for I in 1 .. 1_000 loop Result := Contexts.Has_Permission (Permission => P_Admin.Permission); end loop; Util.Measures.Report (S, "Has_Permission role based", 1_000); T.Assert (Result, "Permission not granted"); end; declare S : Util.Measures.Stamp; begin for I in 1 .. 1_000 loop declare URL : constant String := "/admin/list.html"; P : constant URLs.URL_Permission (URL'Length) := URLs.URL_Permission '(Len => URL'Length, URL => URL); begin T.Assert (Contexts.Has_Permission (Permission => P), "Permission not granted"); end; end loop; Util.Measures.Report (S, "Has_Permission (cache hit)", 1_000); end; end Test_Read_Policy; -- ------------------------------ -- Read the policy file <b>File</b> and perform a test on the given URI -- with a user having the given role. -- ------------------------------ procedure Check_Policy (T : in out Test; File : in String; Role : in String; URL : in String; Anonymous : in Boolean := False; Granted : in Boolean := True) is M : aliased Security.Policies.Policy_Manager (2); User : aliased Test_Principal; Admin : Roles.Role_Type; Context : aliased Security.Contexts.Security_Context; R : Security.Policies.Roles.Role_Policy_Access; U : Security.Policies.URLs.URL_Policy_Access; begin Configure_Policy (M, File); if Anonymous then Context.Set_Context (Manager => M'Unchecked_Access, Principal => null); else Context.Set_Context (Manager => M'Unchecked_Access, Principal => User'Unchecked_Access); end if; R := Security.Policies.Roles.Get_Role_Policy (M); U := Security.Policies.URLs.Get_URL_Policy (M); Admin := R.Find_Role (Role); declare P : constant URLs.URL_Permission (URL'Length) := URLs.URL_Permission '(Len => URL'Length, URL => URL); begin if not Anonymous then -- A user without the role should not have the permission. T.Assert (not U.Has_Permission (Context => Context, Permission => P), "Permission was granted for user without role. URL=" & URL); -- Set the role. User.Roles (Admin) := True; end if; if Granted then T.Assert (U.Has_Permission (Context => Context, Permission => P), "Permission was not granted for user with role. URL=" & URL); else T.Assert (not U.Has_Permission (Context => Context, Permission => P), "Permission was granted for user with role. URL=" & URL); end if; end; end Check_Policy; -- ------------------------------ -- Test reading policy files and using the <role-permission> controller -- ------------------------------ procedure Test_Role_Policy (T : in out Test) is begin T.Check_Policy (File => "policy-with-role.xml", Role => "developer", URL => "/developer/user-should-have-developer-role"); T.Check_Policy (File => "policy-with-role.xml", Role => "manager", URL => "/developer/user-should-have-manager-role"); T.Check_Policy (File => "policy-with-role.xml", Role => "manager", URL => "/manager/user-should-have-manager-role"); T.Check_Policy (File => "policy-with-role.xml", Role => "admin", URL => "/manager/user-should-have-admin-role"); T.Check_Policy (File => "policy-with-role.xml", Role => "admin", URL => "/admin/user-should-have-admin-role"); T.Check_Policy (File => "policy-with-role.xml", Role => "developer", URL => "/admin/user-with-developer-role-should-not-access-admin", Granted => False); end Test_Role_Policy; -- ------------------------------ -- Test anonymous users and permissions. -- ------------------------------ procedure Test_Anonymous_Permission (T : in out Test) is begin T.Check_Policy (File => "simple-policy.xml", Role => "admin", URL => "/admin/page.html", Anonymous => True, Granted => False); T.Check_Policy (File => "simple-policy.xml", Role => "admin", URL => "/user/totopage.html", Anonymous => True, Granted => False); -- Anonymous users can access the page. T.Check_Policy (File => "simple-policy.xml", Role => "admin", URL => "/page.html", Anonymous => True, Granted => True); end Test_Anonymous_Permission; end Security.Policies.Tests;
----------------------------------------------------------------------- -- Security-policies-tests - Unit tests for Security.Permissions -- Copyright (C) 2011, 2012, 2013 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Files; with Util.Test_Caller; with Util.Measures; with Security.Contexts; with Security.Permissions.Tests; with Security.Policies.URLs; package body Security.Policies.Tests is use Util.Tests; procedure Configure_Policy (Manager : in out Security.Policies.Policy_Manager; Name : in String); package Caller is new Util.Test_Caller (Test, "Security.Policies"); procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is begin Caller.Add_Test (Suite, "Test Security.Permissions.Create_Role", Test_Create_Role'Access); Caller.Add_Test (Suite, "Test Security.Permissions.Has_Permission", Test_Has_Permission'Access); Caller.Add_Test (Suite, "Test Security.Permissions.Read_Policy (empty)", Test_Read_Empty_Policy'Access); Caller.Add_Test (Suite, "Test Security.Policies.Add_Policy", Test_Get_Role_Policy'Access); Caller.Add_Test (Suite, "Test Security.Policies.Get_Policy", Test_Get_Role_Policy'Access); Caller.Add_Test (Suite, "Test Security.Policies.Roles.Get_Role_Policy", Test_Get_Role_Policy'Access); Caller.Add_Test (Suite, "Test Security.Policies.Read_Policy", Test_Read_Policy'Access); Caller.Add_Test (Suite, "Test Security.Policies.Roles.Set_Roles", Test_Set_Roles'Access); Caller.Add_Test (Suite, "Test Security.Policies.Roles.Set_Roles (invalid)", Test_Set_Invalid_Roles'Access); -- These tests are identical but registered under different names -- for the test documentation. Caller.Add_Test (Suite, "Test Security.Contexts.Has_Permission", Test_Role_Policy'Access); Caller.Add_Test (Suite, "Test Security.Controllers.Roles.Has_Permission", Test_Role_Policy'Access); Caller.Add_Test (Suite, "Test Security.Permissions.Role_Policy", Test_Role_Policy'Access); Caller.Add_Test (Suite, "Test Security.Contexts.Has_Permission (all-permission)", Test_Anonymous_Permission'Access); Caller.Add_Test (Suite, "Test Security.Contexts.Has_Permission (auth-permission)", Test_Anonymous_Permission'Access); end Add_Tests; -- ------------------------------ -- Get the roles assigned to the user. -- ------------------------------ function Get_Roles (User : in Test_Principal) return Roles.Role_Map is begin return User.Roles; end Get_Roles; -- ------------------------------ -- Get the principal name. -- ------------------------------ function Get_Name (From : in Test_Principal) return String is begin return Util.Strings.To_String (From.Name); end Get_Name; -- ------------------------------ -- Test Create_Role and Get_Role_Name -- ------------------------------ procedure Test_Create_Role (T : in out Test) is use Security.Policies.Roles; M : Security.Policies.Roles.Role_Policy; Role : Role_Type; begin M.Create_Role (Name => "admin", Role => Role); Assert_Equals (T, "admin", M.Get_Role_Name (Role), "Invalid name"); for I in Role + 1 .. Role_Type'Last loop declare Name : constant String := "admin-" & Role_Type'Image (I); Role2 : Role_Type; begin Role2 := M.Find_Role ("admin"); T.Assert (Role2 = Role, "Find_Role returned an invalid role"); M.Create_Role (Name => Name, Role => Role2); Assert_Equals (T, Name, M.Get_Role_Name (Role2), "Invalid name"); end; end loop; end Test_Create_Role; -- ------------------------------ -- Test Set_Roles -- ------------------------------ procedure Test_Set_Roles (T : in out Test) is use Security.Policies.Roles; M : Security.Policies.Roles.Role_Policy; Admin : Role_Type; Manager : Role_Type; Map : Role_Map := (others => False); begin M.Create_Role (Name => "manager", Role => Manager); M.Create_Role (Name => "admin", Role => Admin); Assert_Equals (T, "admin", M.Get_Role_Name (Admin), "Invalid name"); T.Assert (not Map (Admin), "The admin role must not set in the map"); M.Set_Roles ("admin", Map); T.Assert (Map (Admin), "The admin role is not set in the map"); T.Assert (not Map (Manager), "The manager role must not be set in the map"); M.Set_Roles ("manager,admin", Map); T.Assert (Map (Admin), "The admin role is not set in the map"); T.Assert (Map (Manager), "The manager role is not set in the map"); end Test_Set_Roles; -- ------------------------------ -- Test Set_Roles on an invalid role name -- ------------------------------ procedure Test_Set_Invalid_Roles (T : in out Test) is use Security.Policies.Roles; M : Security.Policies.Roles.Role_Policy; Map : Role_Map := (others => False); pragma Unreferenced (Map); begin M.Set_Roles ("manager,admin", Map); T.Assert (False, "No exception was raised"); exception when 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 (Permissions.Tests.P_Admin.Permission); Context : aliased Security.Contexts.Security_Context; begin T.Assert (not M.Has_Permission (Context, Perm), "User has a non-existing permission"); end Test_Has_Permission; procedure Configure_Policy (Manager : in out Security.Policies.Policy_Manager; Name : in String) is Dir : constant String := "regtests/files/permissions/"; Path : constant String := Util.Tests.Get_Path (Dir); R : constant Security.Policies.Roles.Role_Policy_Access := new Roles.Role_Policy; U : constant Security.Policies.URLs.URL_Policy_Access := new URLs.URL_Policy; begin Manager.Add_Policy (R.all'Access); Manager.Add_Policy (U.all'Access); Manager.Read_Policy (Util.Files.Compose (Path, Name)); end Configure_Policy; -- ------------------------------ -- Test the Get_Policy, Get_Role_Policy and Add_Policy operations. -- ------------------------------ procedure Test_Get_Role_Policy (T : in out Test) is use type Roles.Role_Policy_Access; M : aliased Security.Policies.Policy_Manager (Max_Policies => 2); P : Security.Policies.Policy_Access; R : Security.Policies.Roles.Role_Policy_Access; begin P := M.Get_Policy (Security.Policies.Roles.NAME); T.Assert (P = null, "Get_Policy succeeded"); R := Security.Policies.Roles.Get_Role_Policy (M); T.Assert (R = null, "Get_Role_Policy succeeded"); R := new Roles.Role_Policy; M.Add_Policy (R.all'Access); P := M.Get_Policy (Security.Policies.Roles.NAME); T.Assert (P /= null, "Role policy not found"); T.Assert (P.all in Roles.Role_Policy'Class, "Invalid role policy"); R := Security.Policies.Roles.Get_Role_Policy (M); T.Assert (R /= null, "Get_Role_Policy should not return null"); end Test_Get_Role_Policy; -- ------------------------------ -- Test reading an empty policy file -- ------------------------------ procedure Test_Read_Empty_Policy (T : in out Test) is M : aliased Security.Policies.Policy_Manager (Max_Policies => 2); User : aliased Test_Principal; Context : aliased Security.Contexts.Security_Context; R : Security.Policies.Roles.Role_Policy_Access; begin Configure_Policy (M, "empty.xml"); Context.Set_Context (Manager => M'Unchecked_Access, Principal => User'Unchecked_Access); R := Security.Policies.Roles.Get_Role_Policy (M); declare Admin : Policies.Roles.Role_Type; pragma Unreferenced (Admin); begin Admin := R.Find_Role ("admin"); T.Fail ("'admin' role was returned"); exception when Security.Policies.Roles.Invalid_Name => null; end; T.Assert (not Contexts.Has_Permission (Permissions.Tests.P_Admin.Permission), "Has_Permission (admin) failed for empty policy"); T.Assert (not Contexts.Has_Permission (Permissions.Tests.P_Create.Permission), "Has_Permission (create) failed for empty policy"); T.Assert (not Contexts.Has_Permission (Permissions.Tests.P_Update.Permission), "Has_Permission (update) failed for empty policy"); T.Assert (not Contexts.Has_Permission (Permissions.Tests.P_Delete.Permission), "Has_Permission (delete) failed for empty policy"); end Test_Read_Empty_Policy; -- ------------------------------ -- Test reading policy files -- ------------------------------ procedure Test_Read_Policy (T : in out Test) is use Security.Permissions.Tests; M : aliased Security.Policies.Policy_Manager (Max_Policies => 2); User : aliased Test_Principal; Admin : Policies.Roles.Role_Type; Context : aliased Security.Contexts.Security_Context; R : Security.Policies.Roles.Role_Policy_Access; begin Configure_Policy (M, "simple-policy.xml"); Context.Set_Context (Manager => M'Unchecked_Access, Principal => User'Unchecked_Access); R := Security.Policies.Roles.Get_Role_Policy (M); Admin := R.Find_Role ("admin"); T.Assert (not Contexts.Has_Permission (Permission => P_Admin.Permission), "Permission was granted but user has no role"); User.Roles (Admin) := True; T.Assert (Contexts.Has_Permission (Permission => P_Admin.Permission), "Permission was not granted and user has admin role"); declare S : Util.Measures.Stamp; Result : Boolean; begin for I in 1 .. 1_000 loop Result := Contexts.Has_Permission (Permission => P_Admin.Permission); end loop; Util.Measures.Report (S, "Has_Permission role based", 1_000); T.Assert (Result, "Permission not granted"); end; declare S : Util.Measures.Stamp; begin for I in 1 .. 1_000 loop declare URL : constant String := "/admin/list.html"; P : constant URLs.URL_Permission (URL'Length) := URLs.URL_Permission '(Len => URL'Length, URL => URL); begin T.Assert (Contexts.Has_Permission (Permission => P), "Permission not granted"); end; end loop; Util.Measures.Report (S, "Has_Permission (cache hit)", 1_000); end; end Test_Read_Policy; -- ------------------------------ -- Read the policy file <b>File</b> and perform a test on the given URI -- with a user having the given role. -- ------------------------------ procedure Check_Policy (T : in out Test; File : in String; Role : in String; URL : in String; Anonymous : in Boolean := False; Granted : in Boolean := True) is M : aliased Security.Policies.Policy_Manager (2); User : aliased Test_Principal; Admin : Roles.Role_Type; Context : aliased Security.Contexts.Security_Context; R : Security.Policies.Roles.Role_Policy_Access; U : Security.Policies.URLs.URL_Policy_Access; begin Configure_Policy (M, File); if Anonymous then Context.Set_Context (Manager => M'Unchecked_Access, Principal => null); else Context.Set_Context (Manager => M'Unchecked_Access, Principal => User'Unchecked_Access); end if; R := Security.Policies.Roles.Get_Role_Policy (M); U := Security.Policies.URLs.Get_URL_Policy (M); Admin := R.Find_Role (Role); declare P : constant URLs.URL_Permission (URL'Length) := URLs.URL_Permission '(Len => URL'Length, URL => URL); begin if not Anonymous then -- A user without the role should not have the permission. T.Assert (not U.Has_Permission (Context => Context, Permission => P), "Permission was granted for user without role. URL=" & URL); -- Set the role. User.Roles (Admin) := True; end if; if Granted then T.Assert (U.Has_Permission (Context => Context, Permission => P), "Permission was not granted for user with role. URL=" & URL); else T.Assert (not U.Has_Permission (Context => Context, Permission => P), "Permission was granted for user with role. URL=" & URL); end if; end; end Check_Policy; -- ------------------------------ -- Test reading policy files and using the <role-permission> controller -- ------------------------------ procedure Test_Role_Policy (T : in out Test) is begin T.Check_Policy (File => "policy-with-role.xml", Role => "developer", URL => "/developer/user-should-have-developer-role"); T.Check_Policy (File => "policy-with-role.xml", Role => "manager", URL => "/developer/user-should-have-manager-role"); T.Check_Policy (File => "policy-with-role.xml", Role => "manager", URL => "/manager/user-should-have-manager-role"); T.Check_Policy (File => "policy-with-role.xml", Role => "admin", URL => "/manager/user-should-have-admin-role"); T.Check_Policy (File => "policy-with-role.xml", Role => "admin", URL => "/admin/user-should-have-admin-role"); T.Check_Policy (File => "policy-with-role.xml", Role => "developer", URL => "/admin/user-with-developer-role-should-not-access-admin", Granted => False); end Test_Role_Policy; -- ------------------------------ -- Test anonymous users and permissions. -- ------------------------------ procedure Test_Anonymous_Permission (T : in out Test) is begin T.Check_Policy (File => "simple-policy.xml", Role => "admin", URL => "/admin/page.html", Anonymous => True, Granted => False); T.Check_Policy (File => "simple-policy.xml", Role => "admin", URL => "/user/totopage.html", Anonymous => True, Granted => False); -- Anonymous users can access the page. T.Check_Policy (File => "simple-policy.xml", Role => "admin", URL => "/page.html", Anonymous => True, Granted => True); end Test_Anonymous_Permission; end Security.Policies.Tests;
Update the Has_Permission test that was empty and checked nothing
Update the Has_Permission test that was empty and checked nothing
Ada
apache-2.0
stcarrez/ada-security
ac0bf917f88b5f55dbeced9f0a56ca1e08efda3f
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.Permissions.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 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); 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 := Roles.Role_Policy'Class (P.all)'Access; declare Admin : Policies.Roles.Role_Type; begin Admin := R.Find_Role ("admin"); T.Fail ("'admin' role was returned"); exception when Security.Policies.Roles.Invalid_Name => null; end; T.Assert (not Contexts.Has_Permission (Permissions.Tests.P_Admin.Permission), "Has_Permission (admin) failed for empty policy"); T.Assert (not Contexts.Has_Permission (Permissions.Tests.P_Create.Permission), "Has_Permission (create) failed for empty policy"); T.Assert (not Contexts.Has_Permission (Permissions.Tests.P_Update.Permission), "Has_Permission (update) failed for empty policy"); T.Assert (not Contexts.Has_Permission (Permissions.Tests.P_Delete.Permission), "Has_Permission (delete) failed for empty policy"); end Test_Read_Empty_Policy; -- ------------------------------ -- Test reading policy files -- ------------------------------ procedure Test_Read_Policy (T : in out Test) is M : aliased Security.Policies.Policy_Manager (Max_Policies => 2); User : aliased Test_Principal; Admin_Perm : Policies.Roles.Role_Type; Manager_Perm : Policies.Roles.Role_Type; Context : aliased Security.Contexts.Security_Context; R : Security.Policies.Roles.Role_Policy_Access := new Roles.Role_Policy; begin Configure_Policy (M, "simple-policy.xml"); User.Roles (Admin_Perm) := True; Context.Set_Context (Manager => M'Unchecked_Access, Principal => User'Unchecked_Access); declare use Security.Permissions.Tests; S : Util.Measures.Stamp; begin for I in 1 .. 1_000 loop declare URI : constant String := "/admin/home/" & Util.Strings.Image (I) & "/l.html"; P : constant URLs.URI_Permission (URI'Length) := URLs.URI_Permission '(Len => URI'Length, URI => URI); begin T.Assert (Contexts.Has_Permission (Permission => P_Admin.Permission), "Permission not granted"); end; end loop; Util.Measures.Report (S, "Has_Permission (1000 calls, cache miss)"); end; declare use Security.Permissions.Tests; S : Util.Measures.Stamp; begin for I in 1 .. 1_000 loop declare URI : constant String := "/admin/home/list.html"; P : constant URLs.URI_Permission (URI'Length) := URLs.URI_Permission '(Len => URI'Length, URI => URI); begin T.Assert (Contexts.Has_Permission (Permission => P_Admin.Permission), "Permission not granted"); end; end loop; Util.Measures.Report (S, "Has_Permission (1000 calls, cache hit)"); end; end Test_Read_Policy; -- ------------------------------ -- Read the policy file <b>File</b> and perform a test on the given URI -- with a user having the given role. -- ------------------------------ procedure Check_Policy (T : in out Test; File : in String; Role : in String; URI : in String) is M : aliased Security.Policies.Policy_Manager (2); User : aliased Test_Principal; Admin_Perm : Roles.Role_Type; Context : aliased Security.Contexts.Security_Context; P : Security.Policies.Policy_Access; R : Security.Policies.Roles.Role_Policy_Access; U : Security.Policies.URLs.URL_Policy_Access := new URLs.URL_Policy; begin Configure_Policy (M, File); Context.Set_Context (Manager => M'Unchecked_Access, Principal => User'Unchecked_Access); 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 := Roles.Role_Policy'Class (P.all)'Access; Admin_Perm := R.Find_Role (Role); declare P : constant URLs.URI_Permission (URI'Length) := URLs.URI_Permission '(Len => URI'Length, URI => URI); begin -- A user without the role should not have the permission. T.Assert (not U.Has_Permission (Context => Context'Unchecked_Access, Permission => P), "Permission was granted for user without role. URI=" & URI); -- Set the role. User.Roles (Admin_Perm) := True; T.Assert (U.Has_Permission (Context => Context'Unchecked_Access, Permission => P), "Permission was not granted for user with role. URI=" & URI); end; end Check_Policy; -- ------------------------------ -- Test reading policy files and using the <role-permission> controller -- ------------------------------ procedure Test_Role_Policy (T : in out Test) is begin T.Check_Policy (File => "policy-with-role.xml", Role => "developer", URI => "/developer/user-should-have-developer-role"); T.Check_Policy (File => "policy-with-role.xml", Role => "manager", URI => "/developer/user-should-have-manager-role"); T.Check_Policy (File => "policy-with-role.xml", Role => "manager", URI => "/manager/user-should-have-manager-role"); T.Check_Policy (File => "policy-with-role.xml", Role => "admin", URI => "/manager/user-should-have-admin-role"); T.Check_Policy (File => "policy-with-role.xml", Role => "admin", URI => "/admin/user-should-have-admin-role"); end Test_Role_Policy; end Security.Policies.Tests;
----------------------------------------------------------------------- -- Security-policies-tests - Unit tests for Security.Permissions -- Copyright (C) 2011, 2012 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Tests; with Util.Files; with Util.Test_Caller; with Util.Measures; with Security.Contexts; with Security.Policies.Roles; with Security.Permissions.Tests; package body Security.Policies.Tests is use Util.Tests; package Caller is new Util.Test_Caller (Test, "Security.Policies"); procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is begin Caller.Add_Test (Suite, "Test Security.Permissions.Create_Role", Test_Create_Role'Access); Caller.Add_Test (Suite, "Test Security.Permissions.Has_Permission", Test_Has_Permission'Access); Caller.Add_Test (Suite, "Test Security.Permissions.Read_Policy (empty)", Test_Read_Empty_Policy'Access); Caller.Add_Test (Suite, "Test Security.Policies.Add_Policy", Test_Get_Role_Policy'Access); Caller.Add_Test (Suite, "Test Security.Policies.Get_Policy", Test_Get_Role_Policy'Access); Caller.Add_Test (Suite, "Test Security.Policies.Roles.Get_Role_Policy", Test_Get_Role_Policy'Access); Caller.Add_Test (Suite, "Test Security.Policies.Read_Policy", Test_Read_Policy'Access); Caller.Add_Test (Suite, "Test Security.Policies.Roles.Set_Roles", Test_Set_Roles'Access); Caller.Add_Test (Suite, "Test Security.Policies.Roles.Set_Roles (invalid)", Test_Set_Invalid_Roles'Access); -- These tests are identical but registered under different names -- for the test documentation. Caller.Add_Test (Suite, "Test Security.Contexts.Has_Permission", Test_Role_Policy'Access); Caller.Add_Test (Suite, "Test Security.Controllers.Roles.Has_Permission", Test_Role_Policy'Access); Caller.Add_Test (Suite, "Test Security.Permissions.Role_Policy", Test_Role_Policy'Access); end Add_Tests; -- ------------------------------ -- Get the roles assigned to the user. -- ------------------------------ function Get_Roles (User : in Test_Principal) return Roles.Role_Map is begin return User.Roles; end Get_Roles; -- ------------------------------ -- Get the principal name. -- ------------------------------ function Get_Name (From : in Test_Principal) return String is begin return Util.Strings.To_String (From.Name); end Get_Name; -- ------------------------------ -- Test Create_Role and Get_Role_Name -- ------------------------------ procedure Test_Create_Role (T : in out Test) is use Security.Policies.Roles; M : Security.Policies.Roles.Role_Policy; Role : Role_Type; begin M.Create_Role (Name => "admin", Role => Role); Assert_Equals (T, "admin", M.Get_Role_Name (Role), "Invalid name"); for I in Role + 1 .. Role_Type'Last loop declare Name : constant String := "admin-" & Role_Type'Image (I); Role2 : Role_Type; begin Role2 := M.Find_Role ("admin"); T.Assert (Role2 = Role, "Find_Role returned an invalid role"); M.Create_Role (Name => Name, Role => Role2); Assert_Equals (T, Name, M.Get_Role_Name (Role2), "Invalid name"); end; end loop; end Test_Create_Role; -- ------------------------------ -- Test Set_Roles -- ------------------------------ procedure Test_Set_Roles (T : in out Test) is use Security.Policies.Roles; M : Security.Policies.Roles.Role_Policy; Admin : Role_Type; Manager : Role_Type; Map : Role_Map := (others => False); begin M.Create_Role (Name => "manager", Role => Manager); M.Create_Role (Name => "admin", Role => Admin); Assert_Equals (T, "admin", M.Get_Role_Name (Admin), "Invalid name"); T.Assert (not Map (Admin), "The admin role must not set in the map"); M.Set_Roles ("admin", Map); T.Assert (Map (Admin), "The admin role is not set in the map"); T.Assert (not Map (Manager), "The manager role must not be set in the map"); Map := (others => False); M.Set_Roles ("manager,admin", Map); T.Assert (Map (Admin), "The admin role is not set in the map"); T.Assert (Map (Manager), "The manager role is not set in the map"); end Test_Set_Roles; -- ------------------------------ -- Test Set_Roles on an invalid role name -- ------------------------------ procedure Test_Set_Invalid_Roles (T : in out Test) is use Security.Policies.Roles; M : Security.Policies.Roles.Role_Policy; Map : Role_Map := (others => False); begin M.Set_Roles ("manager,admin", Map); T.Assert (False, "No exception was raised"); exception when E : Security.Policies.Roles.Invalid_Name => null; end Test_Set_Invalid_Roles; -- ------------------------------ -- Test Has_Permission -- ------------------------------ procedure Test_Has_Permission (T : in out Test) is M : Security.Policies.Policy_Manager (1); -- Perm : Permissions.Permission_Type; User : Test_Principal; begin -- T.Assert (not M.Has_Permission (User, 1), "User has a non-existing permission"); null; end Test_Has_Permission; procedure Configure_Policy (Manager : in out Security.Policies.Policy_Manager; Name : in String) is Dir : constant String := "regtests/files/permissions/"; Path : constant String := Util.Tests.Get_Path (Dir); R : Security.Policies.Roles.Role_Policy_Access := new Roles.Role_Policy; U : Security.Policies.URLs.URL_Policy_Access := new URLs.URL_Policy; begin Manager.Add_Policy (R.all'Access); Manager.Add_Policy (U.all'Access); Manager.Read_Policy (Util.Files.Compose (Path, Name)); end Configure_Policy; -- ------------------------------ -- Test the Get_Policy, Get_Role_Policy and Add_Policy operations. -- ------------------------------ procedure Test_Get_Role_Policy (T : in out Test) is use type Roles.Role_Policy_Access; M : aliased Security.Policies.Policy_Manager (Max_Policies => 2); P : Security.Policies.Policy_Access; R : Security.Policies.Roles.Role_Policy_Access; begin P := M.Get_Policy (Security.Policies.Roles.NAME); T.Assert (P = null, "Get_Policy succeeded"); R := Security.Policies.Roles.Get_Role_Policy (M); T.Assert (R = null, "Get_Role_Policy succeeded"); R := new Roles.Role_Policy; M.Add_Policy (R.all'Access); P := M.Get_Policy (Security.Policies.Roles.NAME); T.Assert (P /= null, "Role policy not found"); T.Assert (P.all in Roles.Role_Policy'Class, "Invalid role policy"); R := Security.Policies.Roles.Get_Role_Policy (M); T.Assert (R /= null, "Get_Role_Policy should not return null"); end Test_Get_Role_Policy; -- ------------------------------ -- Test reading an empty policy file -- ------------------------------ procedure Test_Read_Empty_Policy (T : in out Test) is M : aliased Security.Policies.Policy_Manager (Max_Policies => 2); User : aliased Test_Principal; Context : aliased Security.Contexts.Security_Context; P : Security.Policies.Policy_Access; R : Security.Policies.Roles.Role_Policy_Access; begin Configure_Policy (M, "empty.xml"); Context.Set_Context (Manager => M'Unchecked_Access, Principal => User'Unchecked_Access); R := Security.Policies.Roles.Get_Role_Policy (M); declare Admin : Policies.Roles.Role_Type; begin Admin := R.Find_Role ("admin"); T.Fail ("'admin' role was returned"); exception when Security.Policies.Roles.Invalid_Name => null; end; T.Assert (not Contexts.Has_Permission (Permissions.Tests.P_Admin.Permission), "Has_Permission (admin) failed for empty policy"); T.Assert (not Contexts.Has_Permission (Permissions.Tests.P_Create.Permission), "Has_Permission (create) failed for empty policy"); T.Assert (not Contexts.Has_Permission (Permissions.Tests.P_Update.Permission), "Has_Permission (update) failed for empty policy"); T.Assert (not Contexts.Has_Permission (Permissions.Tests.P_Delete.Permission), "Has_Permission (delete) failed for empty policy"); end Test_Read_Empty_Policy; -- ------------------------------ -- Test reading policy files -- ------------------------------ procedure Test_Read_Policy (T : in out Test) is M : aliased Security.Policies.Policy_Manager (Max_Policies => 2); User : aliased Test_Principal; Admin_Perm : Policies.Roles.Role_Type; Manager_Perm : Policies.Roles.Role_Type; Context : aliased Security.Contexts.Security_Context; R : Security.Policies.Roles.Role_Policy_Access := new Roles.Role_Policy; begin Configure_Policy (M, "simple-policy.xml"); Context.Set_Context (Manager => M'Unchecked_Access, Principal => User'Unchecked_Access); User.Roles (Admin_Perm) := True; declare use Security.Permissions.Tests; S : Util.Measures.Stamp; begin for I in 1 .. 1_000 loop declare URI : constant String := "/admin/home/" & Util.Strings.Image (I) & "/l.html"; P : constant URLs.URI_Permission (URI'Length) := URLs.URI_Permission '(Len => URI'Length, URI => URI); begin T.Assert (Contexts.Has_Permission (Permission => P_Admin.Permission), "Permission not granted"); end; end loop; Util.Measures.Report (S, "Has_Permission (1000 calls, cache miss)"); end; declare use Security.Permissions.Tests; S : Util.Measures.Stamp; begin for I in 1 .. 1_000 loop declare URI : constant String := "/admin/home/list.html"; P : constant URLs.URI_Permission (URI'Length) := URLs.URI_Permission '(Len => URI'Length, URI => URI); begin T.Assert (Contexts.Has_Permission (Permission => P_Admin.Permission), "Permission not granted"); end; end loop; Util.Measures.Report (S, "Has_Permission (1000 calls, cache hit)"); end; end Test_Read_Policy; -- ------------------------------ -- Read the policy file <b>File</b> and perform a test on the given URI -- with a user having the given role. -- ------------------------------ procedure Check_Policy (T : in out Test; File : in String; Role : in String; URI : in String) is M : aliased Security.Policies.Policy_Manager (2); User : aliased Test_Principal; Admin_Perm : Roles.Role_Type; Context : aliased Security.Contexts.Security_Context; P : Security.Policies.Policy_Access; R : Security.Policies.Roles.Role_Policy_Access; U : Security.Policies.URLs.URL_Policy_Access := new URLs.URL_Policy; begin Configure_Policy (M, File); Context.Set_Context (Manager => M'Unchecked_Access, Principal => User'Unchecked_Access); R := Security.Policies.Roles.Get_Role_Policy (M); Admin_Perm := R.Find_Role (Role); declare P : constant URLs.URI_Permission (URI'Length) := URLs.URI_Permission '(Len => URI'Length, URI => URI); begin -- A user without the role should not have the permission. T.Assert (not U.Has_Permission (Context => Context'Unchecked_Access, Permission => P), "Permission was granted for user without role. URI=" & URI); -- Set the role. User.Roles (Admin_Perm) := True; T.Assert (U.Has_Permission (Context => Context'Unchecked_Access, Permission => P), "Permission was not granted for user with role. URI=" & URI); end; end Check_Policy; -- ------------------------------ -- Test reading policy files and using the <role-permission> controller -- ------------------------------ procedure Test_Role_Policy (T : in out Test) is begin T.Check_Policy (File => "policy-with-role.xml", Role => "developer", URI => "/developer/user-should-have-developer-role"); T.Check_Policy (File => "policy-with-role.xml", Role => "manager", URI => "/developer/user-should-have-manager-role"); T.Check_Policy (File => "policy-with-role.xml", Role => "manager", URI => "/manager/user-should-have-manager-role"); T.Check_Policy (File => "policy-with-role.xml", Role => "admin", URI => "/manager/user-should-have-admin-role"); T.Check_Policy (File => "policy-with-role.xml", Role => "admin", URI => "/admin/user-should-have-admin-role"); end Test_Role_Policy; end Security.Policies.Tests;
Add and implement a test for Get_Policy, Add_Policy, Get_Role_Policy
Add and implement a test for Get_Policy, Add_Policy, Get_Role_Policy
Ada
apache-2.0
stcarrez/ada-security
8c7c4b7c50cce79ef357d2e2519eb808017c1e79
awa/plugins/awa-wikis/src/awa-wikis-beans.ads
awa/plugins/awa-wikis/src/awa-wikis-beans.ads
----------------------------------------------------------------------- -- awa-wikis-beans -- Beans for module wikis -- Copyright (C) 2015 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Strings.Unbounded; with Util.Beans.Basic; with Util.Beans.Objects; with ADO; with AWA.Wikis.Modules; with AWA.Wikis.Models; with AWA.Tags.Beans; package AWA.Wikis.Beans is type Wiki_Space_Bean is new AWA.Wikis.Models.Wiki_Space_Bean with record Service : Modules.Wiki_Module_Access := null; -- List of tags associated with the question. Tags : aliased AWA.Tags.Beans.Tag_List_Bean; Tags_Bean : Util.Beans.Basic.Readonly_Bean_Access; end record; type Wiki_Space_Bean_Access is access all Wiki_Space_Bean'Class; -- Get the value identified by the name. overriding function Get_Value (From : in Wiki_Space_Bean; Name : in String) return Util.Beans.Objects.Object; -- Set the value identified by the name. overriding procedure Set_Value (From : in out Wiki_Space_Bean; Name : in String; Value : in Util.Beans.Objects.Object); -- Create or save the wiki space. overriding procedure Save (Bean : in out Wiki_Space_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String); -- Delete the wiki space. procedure Delete (Bean : in out Wiki_Space_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String); -- Create the Wiki_Space_Bean bean instance. function Create_Wiki_Space_Bean (Module : in AWA.Wikis.Modules.Wiki_Module_Access) return Util.Beans.Basic.Readonly_Bean_Access; type Wiki_Page_Bean is new AWA.Wikis.Models.Wiki_Page_Bean with record Service : Modules.Wiki_Module_Access := null; Wiki_Space : Wiki_Space_Bean; -- List of tags associated with the question. Tags : aliased AWA.Tags.Beans.Tag_List_Bean; Tags_Bean : Util.Beans.Basic.Readonly_Bean_Access; end record; type Wiki_Page_Bean_Access is access all Wiki_Page_Bean'Class; -- Get the value identified by the name. overriding function Get_Value (From : in Wiki_Page_Bean; Name : in String) return Util.Beans.Objects.Object; -- Set the value identified by the name. overriding procedure Set_Value (From : in out Wiki_Page_Bean; Name : in String; Value : in Util.Beans.Objects.Object); -- Create or save the wiki page. overriding procedure Save (Bean : in out Wiki_Page_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String); -- Delete the wiki page. overriding procedure Delete (Bean : in out Wiki_Page_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String); -- Create the Wiki_Page_Bean bean instance. function Create_Wiki_Page_Bean (Module : in AWA.Wikis.Modules.Wiki_Module_Access) return Util.Beans.Basic.Readonly_Bean_Access; type Init_Flag is (INIT_WIKI_LIST); type Init_Map is array (Init_Flag) of Boolean; -- ------------------------------ -- Admin List Bean -- ------------------------------ -- The <b>Wiki_Admin_Bean</b> is used for the administration of a wiki. It gives the -- list of wikis and pages that are created, published or not. type Wiki_Admin_Bean is new Util.Beans.Basic.Bean with record Module : AWA.Wikis.Modules.Wiki_Module_Access := null; -- The wiki space identifier. Wiki_Id : ADO.Identifier := ADO.NO_IDENTIFIER; -- List of blogs. Wiki_List : aliased AWA.Wikis.Models.Wiki_Info_List_Bean; Wiki_List_Bean : AWA.Wikis.Models.Wiki_Info_List_Bean_Access; -- Initialization flags. Init_Flags : aliased Init_Map := (others => False); Flags : access Init_Map; end record; type Wiki_Admin_Bean_Access is access all Wiki_Admin_Bean; -- Get the wiki space identifier. function Get_Wiki_Id (List : in Wiki_Admin_Bean) return ADO.Identifier; overriding function Get_Value (List : in Wiki_Admin_Bean; Name : in String) return Util.Beans.Objects.Object; -- Set the value identified by the name. overriding procedure Set_Value (From : in out Wiki_Admin_Bean; Name : in String; Value : in Util.Beans.Objects.Object); -- Load the list of wikis. procedure Load_Wikis (List : in Wiki_Admin_Bean); -- Create the Wiki_Admin_Bean bean instance. function Create_Wiki_Admin_Bean (Module : in AWA.Wikis.Modules.Wiki_Module_Access) return Util.Beans.Basic.Readonly_Bean_Access; end AWA.Wikis.Beans;
----------------------------------------------------------------------- -- awa-wikis-beans -- Beans for module wikis -- Copyright (C) 2015 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Strings.Unbounded; with Util.Beans.Basic; with Util.Beans.Objects; with ADO; with AWA.Wikis.Modules; with AWA.Wikis.Models; with AWA.Tags.Beans; package AWA.Wikis.Beans is type Wiki_Space_Bean is new AWA.Wikis.Models.Wiki_Space_Bean with record Service : Modules.Wiki_Module_Access := null; -- List of tags associated with the question. Tags : aliased AWA.Tags.Beans.Tag_List_Bean; Tags_Bean : Util.Beans.Basic.Readonly_Bean_Access; end record; type Wiki_Space_Bean_Access is access all Wiki_Space_Bean'Class; -- Get the value identified by the name. overriding function Get_Value (From : in Wiki_Space_Bean; Name : in String) return Util.Beans.Objects.Object; -- Set the value identified by the name. overriding procedure Set_Value (From : in out Wiki_Space_Bean; Name : in String; Value : in Util.Beans.Objects.Object); -- Create or save the wiki space. overriding procedure Save (Bean : in out Wiki_Space_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String); -- Delete the wiki space. procedure Delete (Bean : in out Wiki_Space_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String); -- Create the Wiki_Space_Bean bean instance. function Create_Wiki_Space_Bean (Module : in AWA.Wikis.Modules.Wiki_Module_Access) return Util.Beans.Basic.Readonly_Bean_Access; type Wiki_Page_Bean is new AWA.Wikis.Models.Wiki_Page_Bean with record Service : Modules.Wiki_Module_Access := null; -- The page content. Content : Models.Wiki_Content_Ref; Has_Content : Boolean := False; Wiki_Space : Wiki_Space_Bean; -- List of tags associated with the question. Tags : aliased AWA.Tags.Beans.Tag_List_Bean; Tags_Bean : Util.Beans.Basic.Readonly_Bean_Access; end record; type Wiki_Page_Bean_Access is access all Wiki_Page_Bean'Class; -- Get the value identified by the name. overriding function Get_Value (From : in Wiki_Page_Bean; Name : in String) return Util.Beans.Objects.Object; -- Set the value identified by the name. overriding procedure Set_Value (From : in out Wiki_Page_Bean; Name : in String; Value : in Util.Beans.Objects.Object); -- Create or save the wiki page. overriding procedure Save (Bean : in out Wiki_Page_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String); -- Load the wiki page. overriding procedure Load (Bean : in out Wiki_Page_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String); -- Delete the wiki page. overriding procedure Delete (Bean : in out Wiki_Page_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String); -- Create the Wiki_Page_Bean bean instance. function Create_Wiki_Page_Bean (Module : in AWA.Wikis.Modules.Wiki_Module_Access) return Util.Beans.Basic.Readonly_Bean_Access; type Init_Flag is (INIT_WIKI_LIST); type Init_Map is array (Init_Flag) of Boolean; -- ------------------------------ -- Admin List Bean -- ------------------------------ -- The <b>Wiki_Admin_Bean</b> is used for the administration of a wiki. It gives the -- list of wikis and pages that are created, published or not. type Wiki_Admin_Bean is new Util.Beans.Basic.Bean with record Module : AWA.Wikis.Modules.Wiki_Module_Access := null; -- The wiki space identifier. Wiki_Id : ADO.Identifier := ADO.NO_IDENTIFIER; -- List of blogs. Wiki_List : aliased AWA.Wikis.Models.Wiki_Info_List_Bean; Wiki_List_Bean : AWA.Wikis.Models.Wiki_Info_List_Bean_Access; -- Initialization flags. Init_Flags : aliased Init_Map := (others => False); Flags : access Init_Map; end record; type Wiki_Admin_Bean_Access is access all Wiki_Admin_Bean; -- Get the wiki space identifier. function Get_Wiki_Id (List : in Wiki_Admin_Bean) return ADO.Identifier; overriding function Get_Value (List : in Wiki_Admin_Bean; Name : in String) return Util.Beans.Objects.Object; -- Set the value identified by the name. overriding procedure Set_Value (From : in out Wiki_Admin_Bean; Name : in String; Value : in Util.Beans.Objects.Object); -- Load the list of wikis. procedure Load_Wikis (List : in Wiki_Admin_Bean); -- Create the Wiki_Admin_Bean bean instance. function Create_Wiki_Admin_Bean (Module : in AWA.Wikis.Modules.Wiki_Module_Access) return Util.Beans.Basic.Readonly_Bean_Access; end AWA.Wikis.Beans;
Declare the Load procedure to load the wiki page
Declare the Load procedure to load the wiki page
Ada
apache-2.0
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
e10ccf4d8f6fb72c521e0942c3040540ebd9ea2e
src/util-commands-drivers.adb
src/util-commands-drivers.adb
----------------------------------------------------------------------- -- util-commands-drivers -- Support to make command line tools -- 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.Log.Loggers; with Ada.Text_IO; use Ada.Text_IO; package body Util.Commands.Drivers is -- The logger Logs : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create (Driver_Name); -- ------------------------------ -- Write the command usage. -- ------------------------------ procedure Usage (Command : in Command_Type) is begin null; end Usage; -- ------------------------------ -- Print a message for the command. The level indicates whether the message is an error, -- warning or informational. The command name can be used to known the originator. -- The <tt>Log</tt> operation is redirected to the driver's <tt>Log</tt> procedure. -- ------------------------------ procedure Log (Command : in Command_Type; Level : in Util.Log.Level_Type; Name : in String; Message : in String) is begin Command.Driver.Log (Level, Name, Message); end Log; -- ------------------------------ -- Execute the help command with the arguments. -- Print the help for every registered command. -- ------------------------------ overriding procedure Execute (Command : in Help_Command_Type; Name : in String; Args : in Argument_List'Class; Context : in out Context_Type) is procedure Print (Position : in Command_Maps.Cursor); procedure Print (Position : in Command_Maps.Cursor) is Name : constant String := Command_Maps.Key (Position); begin Put_Line (" " & Name); end Print; begin Logs.Debug ("Execute command {0}", Name); if Args.Get_Count = 0 then -- Usage; New_Line; Put ("Type '"); Put (Args.Get_Command_Name); Put_Line (" help {command}' for help on a specific command."); New_Line; Put_Line ("Available subcommands:"); Command.Driver.List.Iterate (Process => Print'Access); else declare Cmd_Name : constant String := Args.Get_Argument (1); Target_Cmd : constant Command_Access := Command.Driver.Find_Command (Cmd_Name); begin if Target_Cmd = null then Logs.Error ("Unknown command {0}", Cmd_Name); else Target_Cmd.Help (Context); end if; end; end if; end Execute; -- ------------------------------ -- Write the help associated with the command. -- ------------------------------ procedure Help (Command : in Help_Command_Type; Context : in out Context_Type) is begin null; end Help; -- ------------------------------ -- Set the driver description printed in the usage. -- ------------------------------ procedure Set_Description (Driver : in out Driver_Type; Description : in String) is begin Driver.Desc := Ada.Strings.Unbounded.To_Unbounded_String (Description); end Set_Description; -- ------------------------------ -- Set the driver usage printed in the usage. -- ------------------------------ procedure Set_Usage (Driver : in out Driver_Type; Usage : in String) is begin Driver.Usage := Ada.Strings.Unbounded.To_Unbounded_String (Usage); end Set_Usage; -- ------------------------------ -- Register the command under the given name. -- ------------------------------ procedure Add_Command (Driver : in out Driver_Type; Name : in String; Command : in Command_Access) is begin Command.Driver := Driver'Unchecked_Access; Driver.List.Include (Name, Command); end Add_Command; -- ------------------------------ -- Register the command under the given name. -- ------------------------------ procedure Add_Command (Driver : in out Driver_Type; Name : in String; Handler : in Command_Handler) is begin Driver.List.Include (Name, new Handler_Command_Type '(Driver => Driver'Unchecked_Access, Handler => Handler)); end Add_Command; -- ------------------------------ -- Find the command having the given name. -- Returns null if the command was not found. -- ------------------------------ function Find_Command (Driver : in Driver_Type; Name : in String) return Command_Access is Pos : constant Command_Maps.Cursor := Driver.List.Find (Name); begin if Command_Maps.Has_Element (Pos) then return Command_Maps.Element (Pos); else return null; end if; end Find_Command; -- ------------------------------ -- Execute the command registered under the given name. -- ------------------------------ procedure Execute (Driver : in Driver_Type; Name : in String; Args : in Argument_List'Class; Context : in out Context_Type) is Command : constant Command_Access := Driver.Find_Command (Name); begin if Command /= null then Command.Execute (Name, Args, Context); else Logs.Error ("Unkown command {0}", Name); end if; end Execute; -- ------------------------------ -- Print a message for the command. The level indicates whether the message is an error, -- warning or informational. The command name can be used to known the originator. -- ------------------------------ procedure Log (Driver : in Driver_Type; Level : in Util.Log.Level_Type; Name : in String; Message : in String) is begin Logs.Print (Level, "{0}: {1}", Name, Message); end Log; -- ------------------------------ -- Execute the command with the arguments. -- ------------------------------ overriding procedure Execute (Command : in Handler_Command_Type; Name : in String; Args : in Argument_List'Class; Context : in out Context_Type) is begin Command.Handler (Name, Args, Context); end Execute; -- ------------------------------ -- Write the help associated with the command. -- ------------------------------ overriding procedure Help (Command : in Handler_Command_Type; Context : in out Context_Type) is begin null; end Help; end Util.Commands.Drivers;
----------------------------------------------------------------------- -- util-commands-drivers -- Support to make command line tools -- 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.Log.Loggers; with Ada.Text_IO; use Ada.Text_IO; package body Util.Commands.Drivers is use Ada.Strings.Unbounded; -- The logger Logs : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create (Driver_Name); -- ------------------------------ -- Write the command usage. -- ------------------------------ procedure Usage (Command : in Command_Type) is begin null; end Usage; -- ------------------------------ -- Print a message for the command. The level indicates whether the message is an error, -- warning or informational. The command name can be used to known the originator. -- The <tt>Log</tt> operation is redirected to the driver's <tt>Log</tt> procedure. -- ------------------------------ procedure Log (Command : in Command_Type; Level : in Util.Log.Level_Type; Name : in String; Message : in String) is begin Command.Driver.Log (Level, Name, Message); end Log; -- ------------------------------ -- Execute the help command with the arguments. -- Print the help for every registered command. -- ------------------------------ overriding procedure Execute (Command : in Help_Command_Type; Name : in String; Args : in Argument_List'Class; Context : in out Context_Type) is procedure Print (Position : in Command_Maps.Cursor); procedure Print (Position : in Command_Maps.Cursor) is Name : constant String := Command_Maps.Key (Position); begin Put_Line (" " & Name); end Print; begin Logs.Debug ("Execute command {0}", Name); if Args.Get_Count = 0 then Usage (Command.Driver.all, Args); New_Line; Put ("Type '"); Put (Args.Get_Command_Name); Put_Line (" help {command}' for help on a specific command."); New_Line; Put_Line ("Available subcommands:"); Command.Driver.List.Iterate (Process => Print'Access); else declare Cmd_Name : constant String := Args.Get_Argument (1); Target_Cmd : constant Command_Access := Command.Driver.Find_Command (Cmd_Name); begin if Target_Cmd = null then Logs.Error ("Unknown command {0}", Cmd_Name); else Target_Cmd.Help (Context); end if; end; end if; end Execute; -- ------------------------------ -- Write the help associated with the command. -- ------------------------------ procedure Help (Command : in Help_Command_Type; Context : in out Context_Type) is begin null; end Help; -- ------------------------------ -- Report the command usage. -- ------------------------------ procedure Usage (Driver : in Driver_Type; Args : in Argument_List'Class) is begin Put_Line (To_String (Driver.Desc)); New_Line; Put ("Usage: "); Put (Args.Get_Command_Name); Put (" "); Put_Line (To_String (Driver.Usage)); end Usage; -- ------------------------------ -- Set the driver description printed in the usage. -- ------------------------------ procedure Set_Description (Driver : in out Driver_Type; Description : in String) is begin Driver.Desc := Ada.Strings.Unbounded.To_Unbounded_String (Description); end Set_Description; -- ------------------------------ -- Set the driver usage printed in the usage. -- ------------------------------ procedure Set_Usage (Driver : in out Driver_Type; Usage : in String) is begin Driver.Usage := Ada.Strings.Unbounded.To_Unbounded_String (Usage); end Set_Usage; -- ------------------------------ -- Register the command under the given name. -- ------------------------------ procedure Add_Command (Driver : in out Driver_Type; Name : in String; Command : in Command_Access) is begin Command.Driver := Driver'Unchecked_Access; Driver.List.Include (Name, Command); end Add_Command; -- ------------------------------ -- Register the command under the given name. -- ------------------------------ procedure Add_Command (Driver : in out Driver_Type; Name : in String; Handler : in Command_Handler) is begin Driver.List.Include (Name, new Handler_Command_Type '(Driver => Driver'Unchecked_Access, Handler => Handler)); end Add_Command; -- ------------------------------ -- Find the command having the given name. -- Returns null if the command was not found. -- ------------------------------ function Find_Command (Driver : in Driver_Type; Name : in String) return Command_Access is Pos : constant Command_Maps.Cursor := Driver.List.Find (Name); begin if Command_Maps.Has_Element (Pos) then return Command_Maps.Element (Pos); else return null; end if; end Find_Command; -- ------------------------------ -- Execute the command registered under the given name. -- ------------------------------ procedure Execute (Driver : in Driver_Type; Name : in String; Args : in Argument_List'Class; Context : in out Context_Type) is Command : constant Command_Access := Driver.Find_Command (Name); begin if Command /= null then Command.Execute (Name, Args, Context); else Logs.Error ("Unkown command {0}", Name); end if; end Execute; -- ------------------------------ -- Print a message for the command. The level indicates whether the message is an error, -- warning or informational. The command name can be used to known the originator. -- ------------------------------ procedure Log (Driver : in Driver_Type; Level : in Util.Log.Level_Type; Name : in String; Message : in String) is begin Logs.Print (Level, "{0}: {1}", Name, Message); end Log; -- ------------------------------ -- Execute the command with the arguments. -- ------------------------------ overriding procedure Execute (Command : in Handler_Command_Type; Name : in String; Args : in Argument_List'Class; Context : in out Context_Type) is begin Command.Handler (Name, Args, Context); end Execute; -- ------------------------------ -- Write the help associated with the command. -- ------------------------------ overriding procedure Help (Command : in Handler_Command_Type; Context : in out Context_Type) is begin null; end Help; end Util.Commands.Drivers;
Implement the Usage procedure
Implement the Usage procedure
Ada
apache-2.0
stcarrez/ada-util,stcarrez/ada-util
5982c26676b4d76e89c0a4cfe6799834b13cbd55
src/sqlite/ado-statements-sqlite.ads
src/sqlite/ado-statements-sqlite.ads
----------------------------------------------------------------------- -- ado-statements-sqlite -- SQLite database statements -- Copyright (C) 2009, 2010, 2011, 2012, 2013, 2015 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES 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 ADO.Drivers.Connections.Sqlite; package ADO.Statements.Sqlite is type Handle is null record; -- ------------------------------ -- Delete statement -- ------------------------------ type Sqlite_Delete_Statement is new Delete_Statement with private; type Sqlite_Delete_Statement_Access is access all Sqlite_Delete_Statement'Class; -- Execute the query overriding procedure Execute (Stmt : in out Sqlite_Delete_Statement; Result : out Natural); -- Create the delete statement function Create_Statement (Database : in ADO.Drivers.Connections.Sqlite.Sqlite_Access; Table : in ADO.Schemas.Class_Mapping_Access) return Delete_Statement_Access; -- ------------------------------ -- Update statement -- ------------------------------ type Sqlite_Update_Statement is new Update_Statement with private; type Sqlite_Update_Statement_Access is access all Sqlite_Update_Statement'Class; -- Execute the query overriding procedure Execute (Stmt : in out Sqlite_Update_Statement); -- Execute the query overriding procedure Execute (Stmt : in out Sqlite_Update_Statement; Result : out Integer); -- Create an update statement function Create_Statement (Database : in ADO.Drivers.Connections.Sqlite.Sqlite_Access; Table : in ADO.Schemas.Class_Mapping_Access) return Update_Statement_Access; -- ------------------------------ -- Insert statement -- ------------------------------ type Sqlite_Insert_Statement is new Insert_Statement with private; type Sqlite_Insert_Statement_Access is access all Sqlite_Insert_Statement'Class; -- Execute the query overriding procedure Execute (Stmt : in out Sqlite_Insert_Statement; Result : out Integer); -- Create an insert statement. function Create_Statement (Database : in ADO.Drivers.Connections.Sqlite.Sqlite_Access; Table : in ADO.Schemas.Class_Mapping_Access) return Insert_Statement_Access; -- ------------------------------ -- Query statement for SQLite -- ------------------------------ type Sqlite_Query_Statement is new Query_Statement with private; type Sqlite_Query_Statement_Access is access all Sqlite_Query_Statement'Class; -- Execute the query overriding procedure Execute (Query : in out Sqlite_Query_Statement); -- Get the number of rows returned by the query overriding function Get_Row_Count (Query : in Sqlite_Query_Statement) return Natural; -- Returns True if there is more data (row) to fetch overriding function Has_Elements (Query : in Sqlite_Query_Statement) return Boolean; -- Fetch the next row overriding procedure Next (Query : in out Sqlite_Query_Statement); -- Returns true if the column <b>Column</b> is null. overriding function Is_Null (Query : in Sqlite_Query_Statement; Column : in Natural) return Boolean; -- Get the column value at position <b>Column</b> and -- return it as an <b>Int64</b>. -- Raises <b>Invalid_Type</b> if the value cannot be converted. -- Raises <b>Invalid_Column</b> if the column does not exist. overriding function Get_Int64 (Query : Sqlite_Query_Statement; Column : Natural) return Int64; -- Get the column value at position <b>Column</b> and -- return it as an <b>Unbounded_String</b>. -- Raises <b>Invalid_Type</b> if the value cannot be converted. -- Raises <b>Invalid_Column</b> if the column does not exist. overriding function Get_Unbounded_String (Query : Sqlite_Query_Statement; Column : Natural) return Unbounded_String; -- Get the column value at position <b>Column</b> and -- return it as an <b>Unbounded_String</b>. -- Raises <b>Invalid_Type</b> if the value cannot be converted. -- Raises <b>Invalid_Column</b> if the column does not exist. overriding function Get_String (Query : Sqlite_Query_Statement; Column : Natural) return String; -- Get the column value at position <b>Column</b> and -- return it as a <b>Blob</b> reference. overriding function Get_Blob (Query : in Sqlite_Query_Statement; Column : in Natural) return ADO.Blob_Ref; -- Get the column value at position <b>Column</b> and -- return it as an <b>Time</b>. -- Raises <b>Invalid_Type</b> if the value cannot be converted. -- Raises <b>Invalid_Column</b> if the column does not exist. function Get_Time (Query : Sqlite_Query_Statement; Column : Natural) return Ada.Calendar.Time; -- Get the column type -- Raises <b>Invalid_Column</b> if the column does not exist. overriding function Get_Column_Type (Query : Sqlite_Query_Statement; Column : Natural) return ADO.Schemas.Column_Type; -- Get the column name. -- Raises <b>Invalid_Column</b> if the column does not exist. overriding function Get_Column_Name (Query : in Sqlite_Query_Statement; Column : in Natural) return String; -- Get the number of columns in the result. overriding function Get_Column_Count (Query : in Sqlite_Query_Statement) return Natural; -- Deletes the query statement. overriding procedure Finalize (Query : in out Sqlite_Query_Statement); -- Create the query statement. function Create_Statement (Database : in ADO.Drivers.Connections.Sqlite.Sqlite_Access; Table : in ADO.Schemas.Class_Mapping_Access) return Query_Statement_Access; -- Create the query statement. function Create_Statement (Database : in ADO.Drivers.Connections.Sqlite.Sqlite_Access; Query : in String) return Query_Statement_Access; private type State is (HAS_ROW, HAS_MORE, DONE, ERROR); type Sqlite_Query_Statement is new Query_Statement with record This_Query : aliased ADO.SQL.Query; Connection : ADO.Drivers.Connections.Sqlite.Sqlite_Access; Stmt : ADO.Drivers.Connections.Sqlite.Sqlite_Access := System.Null_Address; Counter : Natural := 1; Status : State := DONE; Max_Column : Natural; end record; type Sqlite_Delete_Statement is new Delete_Statement with record Connection : ADO.Drivers.Connections.Sqlite.Sqlite_Access; Table : ADO.Schemas.Class_Mapping_Access; Delete_Query : aliased ADO.SQL.Query; end record; type Sqlite_Update_Statement is new Update_Statement with record Connection : ADO.Drivers.Connections.Sqlite.Sqlite_Access; This_Query : aliased ADO.SQL.Update_Query; Table : ADO.Schemas.Class_Mapping_Access; end record; type Sqlite_Insert_Statement is new Insert_Statement with record Connection : ADO.Drivers.Connections.Sqlite.Sqlite_Access; This_Query : aliased ADO.SQL.Update_Query; Table : ADO.Schemas.Class_Mapping_Access; end record; end ADO.Statements.Sqlite;
----------------------------------------------------------------------- -- ado-statements-sqlite -- SQLite database statements -- Copyright (C) 2009, 2010, 2011, 2012, 2013, 2015, 2018 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Sqlite3_H; with ADO.Drivers.Connections.Sqlite; package ADO.Statements.Sqlite is type Handle is null record; -- ------------------------------ -- Delete statement -- ------------------------------ type Sqlite_Delete_Statement is new Delete_Statement with private; type Sqlite_Delete_Statement_Access is access all Sqlite_Delete_Statement'Class; -- Execute the query overriding procedure Execute (Stmt : in out Sqlite_Delete_Statement; Result : out Natural); -- Create the delete statement function Create_Statement (Database : access ADO.Drivers.Connections.Sqlite.Sqlite3; Table : in ADO.Schemas.Class_Mapping_Access) return Delete_Statement_Access; -- ------------------------------ -- Update statement -- ------------------------------ type Sqlite_Update_Statement is new Update_Statement with private; type Sqlite_Update_Statement_Access is access all Sqlite_Update_Statement'Class; -- Execute the query overriding procedure Execute (Stmt : in out Sqlite_Update_Statement); -- Execute the query overriding procedure Execute (Stmt : in out Sqlite_Update_Statement; Result : out Integer); -- Create an update statement function Create_Statement (Database : access ADO.Drivers.Connections.Sqlite.Sqlite3; Table : in ADO.Schemas.Class_Mapping_Access) return Update_Statement_Access; -- ------------------------------ -- Insert statement -- ------------------------------ type Sqlite_Insert_Statement is new Insert_Statement with private; type Sqlite_Insert_Statement_Access is access all Sqlite_Insert_Statement'Class; -- Execute the query overriding procedure Execute (Stmt : in out Sqlite_Insert_Statement; Result : out Integer); -- Create an insert statement. function Create_Statement (Database : access ADO.Drivers.Connections.Sqlite.Sqlite3; Table : in ADO.Schemas.Class_Mapping_Access) return Insert_Statement_Access; -- ------------------------------ -- Query statement for SQLite -- ------------------------------ type Sqlite_Query_Statement is new Query_Statement with private; type Sqlite_Query_Statement_Access is access all Sqlite_Query_Statement'Class; -- Execute the query overriding procedure Execute (Query : in out Sqlite_Query_Statement); -- Get the number of rows returned by the query overriding function Get_Row_Count (Query : in Sqlite_Query_Statement) return Natural; -- Returns True if there is more data (row) to fetch overriding function Has_Elements (Query : in Sqlite_Query_Statement) return Boolean; -- Fetch the next row overriding procedure Next (Query : in out Sqlite_Query_Statement); -- Returns true if the column <b>Column</b> is null. overriding function Is_Null (Query : in Sqlite_Query_Statement; Column : in Natural) return Boolean; -- Get the column value at position <b>Column</b> and -- return it as an <b>Int64</b>. -- Raises <b>Invalid_Type</b> if the value cannot be converted. -- Raises <b>Invalid_Column</b> if the column does not exist. overriding function Get_Int64 (Query : Sqlite_Query_Statement; Column : Natural) return Int64; -- Get the column value at position <b>Column</b> and -- return it as an <b>Unbounded_String</b>. -- Raises <b>Invalid_Type</b> if the value cannot be converted. -- Raises <b>Invalid_Column</b> if the column does not exist. overriding function Get_Unbounded_String (Query : Sqlite_Query_Statement; Column : Natural) return Unbounded_String; -- Get the column value at position <b>Column</b> and -- return it as an <b>Unbounded_String</b>. -- Raises <b>Invalid_Type</b> if the value cannot be converted. -- Raises <b>Invalid_Column</b> if the column does not exist. overriding function Get_String (Query : Sqlite_Query_Statement; Column : Natural) return String; -- Get the column value at position <b>Column</b> and -- return it as a <b>Blob</b> reference. overriding function Get_Blob (Query : in Sqlite_Query_Statement; Column : in Natural) return ADO.Blob_Ref; -- Get the column value at position <b>Column</b> and -- return it as an <b>Time</b>. -- Raises <b>Invalid_Type</b> if the value cannot be converted. -- Raises <b>Invalid_Column</b> if the column does not exist. function Get_Time (Query : Sqlite_Query_Statement; Column : Natural) return Ada.Calendar.Time; -- Get the column type -- Raises <b>Invalid_Column</b> if the column does not exist. overriding function Get_Column_Type (Query : Sqlite_Query_Statement; Column : Natural) return ADO.Schemas.Column_Type; -- Get the column name. -- Raises <b>Invalid_Column</b> if the column does not exist. overriding function Get_Column_Name (Query : in Sqlite_Query_Statement; Column : in Natural) return String; -- Get the number of columns in the result. overriding function Get_Column_Count (Query : in Sqlite_Query_Statement) return Natural; -- Deletes the query statement. overriding procedure Finalize (Query : in out Sqlite_Query_Statement); -- Create the query statement. function Create_Statement (Database : access ADO.Drivers.Connections.Sqlite.Sqlite3; Table : in ADO.Schemas.Class_Mapping_Access) return Query_Statement_Access; -- Create the query statement. function Create_Statement (Database : access ADO.Drivers.Connections.Sqlite.Sqlite3; Query : in String) return Query_Statement_Access; private type State is (HAS_ROW, HAS_MORE, DONE, ERROR); type Sqlite_Query_Statement is new Query_Statement with record This_Query : aliased ADO.SQL.Query; Connection : access ADO.Drivers.Connections.Sqlite.Sqlite3; Stmt : access Sqlite3_H.sqlite3_stmt; Counter : Natural := 1; Status : State := DONE; Max_Column : Natural; end record; type Sqlite_Delete_Statement is new Delete_Statement with record Connection : access ADO.Drivers.Connections.Sqlite.Sqlite3; Table : ADO.Schemas.Class_Mapping_Access; Delete_Query : aliased ADO.SQL.Query; end record; type Sqlite_Update_Statement is new Update_Statement with record Connection : access ADO.Drivers.Connections.Sqlite.Sqlite3; This_Query : aliased ADO.SQL.Update_Query; Table : ADO.Schemas.Class_Mapping_Access; end record; type Sqlite_Insert_Statement is new Insert_Statement with record Connection : access ADO.Drivers.Connections.Sqlite.Sqlite3; This_Query : aliased ADO.SQL.Update_Query; Table : ADO.Schemas.Class_Mapping_Access; end record; end ADO.Statements.Sqlite;
Replace Sqlite_Access and System.Address with the access Sqlite3 type
Replace Sqlite_Access and System.Address with the access Sqlite3 type
Ada
apache-2.0
stcarrez/ada-ado
796b573cdf77b1ecdbfb9a2017b0c6612cae45b0
awa/plugins/awa-wikis/regtests/awa-wikis-modules-tests.ads
awa/plugins/awa-wikis/regtests/awa-wikis-modules-tests.ads
----------------------------------------------------------------------- -- awa-wikis-modules-tests -- Unit tests for wikis service -- Copyright (C) 2015 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Tests; with AWA.Tests; package AWA.Wikis.Modules.Tests is procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite); type Test is new AWA.Tests.Test with record Manager : AWA.Wikis.Modules.Wiki_Module_Access; end record; -- Test creation of a wiki space. procedure Test_Create_Wiki_Space (T : in out Test); -- Test creation of a wiki page. procedure Test_Create_Wiki_Page (T : in out Test); -- Test creation of a wiki page content. procedure Test_Create_Wiki_Content (T : in out Test); end AWA.Wikis.Modules.Tests;
----------------------------------------------------------------------- -- awa-wikis-modules-tests -- Unit tests for wikis service -- Copyright (C) 2015, 2017 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Tests; with AWA.Tests; with ADO; package AWA.Wikis.Modules.Tests is procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite); type Test is new AWA.Tests.Test with record Manager : AWA.Wikis.Modules.Wiki_Module_Access; Wiki_Id : ADO.Identifier := ADO.NO_IDENTIFIER; Public_Id : ADO.Identifier := ADO.NO_IDENTIFIER; Private_Id : ADO.Identifier := ADO.NO_IDENTIFIER; end record; -- Test creation of a wiki space. procedure Test_Create_Wiki_Space (T : in out Test); -- Test creation of a wiki page. procedure Test_Create_Wiki_Page (T : in out Test); -- Test creation of a wiki page content. procedure Test_Create_Wiki_Content (T : in out Test); procedure Test_Wiki_Page (T : in out Test); end AWA.Wikis.Modules.Tests;
Declare the Test_Wiki_Page procedure to simulate HTTP requests on wiki page
Declare the Test_Wiki_Page procedure to simulate HTTP requests on wiki page
Ada
apache-2.0
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
f602f26a2598841a8494bc8735fa137914911b18
src/asf-components-widgets-likes.adb
src/asf-components-widgets-likes.adb
----------------------------------------------------------------------- -- components-widgets-likes -- Social Likes Components -- Copyright (C) 2013 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Locales; with Util.Beans.Objects; with Util.Strings.Tokenizers; with ASF.Requests; with ASF.Contexts.Writer; package body ASF.Components.Widgets.Likes is FB_LAYOUT_ATTR : aliased constant String := "data-layout"; FB_SHOW_FACES_ATTR : aliased constant String := "data-show-faces"; FB_WIDTH_ATTR : aliased constant String := "data-width"; FB_ACTION_ATTR : aliased constant String := "data-action"; FB_FONT_ATTR : aliased constant String := "data-font"; FB_COlORSCHEME_ATTR : aliased constant String := "data-colorscheme"; FB_REF_ATTR : aliased constant String := "data-ref"; FB_KIDS_ATTR : aliased constant String := "data-kid_directed_site"; TW_VIA_ATTR : aliased constant String := "data-via"; TW_COUNT_ATTR : aliased constant String := "data-count"; TW_SIZE_ATTR : aliased constant String := "data-size"; FACEBOOK_ATTRIBUTE_NAMES : Util.Strings.String_Set.Set; FACEBOOK_SCRIPT_ATTRIBUTE : constant String := "asf.widgets.facebook.script"; GOOGLE_ATTRIBUTE_NAMES : Util.Strings.String_Set.Set; GOOGLE_SCRIPT_ATTRIBUTE : constant String := "asf.widgets.google.script"; TWEETER_ATTRIBUTE_NAMES : Util.Strings.String_Set.Set; TWEETER_SCRIPT_ATTRIBUTE : constant String := "asf.widgets.tweeter.script"; type Like_Generator_Binding is record Name : Util.Strings.Name_Access; Generator : Like_Generator_Access; end record; type Like_Generator_Array is array (1 .. MAX_LIKE_GENERATOR) of Like_Generator_Binding; FB_NAME : aliased constant String := "facebook"; FB_GENERATOR : aliased Facebook_Like_Generator; G_NAME : aliased constant String := "google+"; G_GENERATOR : aliased Google_Like_Generator; TWEETER_NAME : aliased constant String := "tweeter"; TWEETER_GENERATOR : aliased Tweeter_Like_Generator; Generators : Like_Generator_Array := (1 => (FB_NAME'Access, FB_GENERATOR'Access), 2 => (G_NAME'Access, G_GENERATOR'Access), 3 => (TWEETER_NAME'Access, TWEETER_GENERATOR'Access), others => (null, null)); -- ------------------------------ -- Render the facebook like button according to the component attributes. -- ------------------------------ overriding procedure Render_Like (Generator : in Facebook_Like_Generator; UI : in UILike'Class; Href : in String; Context : in out ASF.Contexts.Faces.Faces_Context'Class) is Writer : constant Contexts.Writer.Response_Writer_Access := Context.Get_Response_Writer; Request : constant ASF.Requests.Request_Access := Context.Get_Request; begin if not Context.Is_Ajax_Request and then Util.Beans.Objects.Is_Null (Request.Get_Attribute (FACEBOOK_SCRIPT_ATTRIBUTE)) then Request.Set_Attribute (FACEBOOK_SCRIPT_ATTRIBUTE, Util.Beans.Objects.To_Object (True)); Writer.Queue_Script ("(function(d, s, id) { var js, fjs = d.getElementsByTagName(s)[0];" & "if (d.getElementById(id)) return;" & "js = d.createElement(s); js.id = id;" & "js.src = ""//connect.facebook.net/"); Writer.Queue_Script (Util.Locales.To_String (Context.Get_Locale)); Writer.Queue_Script ("/all.js#xfbml=1&;appId=116337738505130"); Writer.Queue_Script (Generator.App_Id); Writer.Queue_Script (""";fjs.parentNode.insertBefore(js, fjs);" & "}(document, 'script', 'facebook-jssdk'));"); Writer.Start_Element ("div"); Writer.Write_Attribute ("id", "fb-root"); Writer.End_Element ("div"); end if; Writer.Start_Element ("div"); Writer.Write_Attribute ("class", "fb-like"); Writer.Write_Attribute ("data-href", Href); Writer.Write_Attribute ("data-send", "true"); UI.Render_Attributes (Context, FACEBOOK_ATTRIBUTE_NAMES, Writer); Writer.End_Element ("div"); end Render_Like; -- ------------------------------ -- Google like generator -- ------------------------------ overriding procedure Render_Like (Generator : in Google_Like_Generator; UI : in UILike'Class; Href : in String; Context : in out ASF.Contexts.Faces.Faces_Context'Class) is pragma Unreferenced (Generator); Writer : constant Contexts.Writer.Response_Writer_Access := Context.Get_Response_Writer; Request : constant ASF.Requests.Request_Access := Context.Get_Request; begin if not Context.Is_Ajax_Request and then Util.Beans.Objects.Is_Null (Request.Get_Attribute (GOOGLE_SCRIPT_ATTRIBUTE)) then Request.Set_Attribute (GOOGLE_SCRIPT_ATTRIBUTE, Util.Beans.Objects.To_Object (True)); Writer.Queue_Include_Script ("https://apis.google.com/js/plusone.js"); end if; Writer.Start_Element ("div"); Writer.Write_Attribute ("class", "g-plusone"); Writer.Write_Attribute ("data-href", Href); Writer.Write_Attribute ("data-send", "true"); UI.Render_Attributes (Context, GOOGLE_ATTRIBUTE_NAMES, Writer); Writer.End_Element ("div"); end Render_Like; overriding procedure Render_Like (Generator : in Tweeter_Like_Generator; UI : in UILike'Class; Href : in String; Context : in out ASF.Contexts.Faces.Faces_Context'Class) is pragma Unreferenced (Generator); Writer : constant Contexts.Writer.Response_Writer_Access := Context.Get_Response_Writer; Request : constant ASF.Requests.Request_Access := Context.Get_Request; Lang : constant String := Util.Locales.Get_ISO3_Language (Context.Get_Locale); begin if not Context.Is_Ajax_Request and then Util.Beans.Objects.Is_Null (Request.Get_Attribute (TWEETER_SCRIPT_ATTRIBUTE)) then Request.Set_Attribute (TWEETER_SCRIPT_ATTRIBUTE, Util.Beans.Objects.To_Object (True)); Writer.Queue_Script ("!function(d,s,id){var js,fjs=d.getElementsByTagName(s)[0]," & "p=/^http:/.test(d.location)?'http':'https';" & "if(!d.getElementById(id)){js=d.createElement(s);js.id=id;" & "js.src=p+'://platform.twitter.com/widgets.js';" & "fjs.parentNode.insertBefore(js,fjs);}}" & "(document, 'script', 'twitter-wjs');"); end if; Writer.Start_Element ("a"); Writer.Write_Attribute ("href", "https://twitter.com/share"); Writer.Write_Attribute ("class", "twitter-share-button"); Writer.Write_Attribute ("data-url", Href); Writer.Write_Attribute ("data-lang", Lang); UI.Render_Attributes (Context, TWEETER_ATTRIBUTE_NAMES, Writer); Writer.Write_Text ("Tweet"); Writer.End_Element ("a"); end Render_Like; -- ------------------------------ -- Get the link to submit in the like action. -- ------------------------------ function Get_Link (UI : in UILike; Context : in ASF.Contexts.Faces.Faces_Context'Class) return String is Href : constant String := UI.Get_Attribute ("href", Context, ""); begin if Href'Length > 0 then return Href; else return Context.Get_Request.Get_Request_URI; end if; end Get_Link; -- ------------------------------ -- Render an image with the source link created from an email address to the Gravatars service. -- ------------------------------ overriding procedure Encode_Begin (UI : in UILike; Context : in out ASF.Contexts.Faces.Faces_Context'Class) is begin if UI.Is_Rendered (Context) then declare Kind : constant String := UI.Get_Attribute ("type", Context, ""); Href : constant String := UILike'Class (UI).Get_Link (Context); procedure Render (Name : in String; Done : out Boolean); procedure Render (Name : in String; Done : out Boolean) is use type Util.Strings.Name_Access; begin Done := False; for I in Generators'Range loop exit when Generators (I).Name = null; if Generators (I).Name.all = Name then Generators (I).Generator.Render_Like (UI, Href, Context); return; end if; end loop; UI.Log_Error ("Like type {0} is not recognized", Name); end Render; begin if Kind'Length = 0 then UI.Log_Error ("The like type is empty."); else Util.Strings.Tokenizers.Iterate_Tokens (Content => Kind, Pattern => ",", Process => Render'Access); end if; end; end if; end Encode_Begin; -- ------------------------------ -- Register the like generator under the given name. -- ------------------------------ procedure Register_Like (Name : in Util.Strings.Name_Access; Generator : in Like_Generator_Access) is use type Util.Strings.Name_Access; begin for I in Generators'Range loop if Generators (I).Name = null then Generators (I).Name := Name; Generators (I).Generator := Generator; return; end if; end loop; end Register_Like; begin FACEBOOK_ATTRIBUTE_NAMES.Insert (FB_LAYOUT_ATTR'Access); FACEBOOK_ATTRIBUTE_NAMES.Insert (FB_SHOW_FACES_ATTR'Access); FACEBOOK_ATTRIBUTE_NAMES.Insert (FB_WIDTH_ATTR'Access); FACEBOOK_ATTRIBUTE_NAMES.Insert (FB_ACTION_ATTR'Access); FACEBOOK_ATTRIBUTE_NAMES.Insert (FB_FONT_ATTR'Access); FACEBOOK_ATTRIBUTE_NAMES.Insert (FB_COlORSCHEME_ATTR'Access); FACEBOOK_ATTRIBUTE_NAMES.Insert (FB_REF_ATTR'Access); FACEBOOK_ATTRIBUTE_NAMES.Insert (FB_KIDS_ATTR'Access); TWEETER_ATTRIBUTE_NAMES.Insert (TW_SIZE_ATTR'Access); TWEETER_ATTRIBUTE_NAMES.Insert (TW_COUNT_ATTR'Access); TWEETER_ATTRIBUTE_NAMES.Insert (TW_VIA_ATTR'Access); end ASF.Components.Widgets.Likes;
----------------------------------------------------------------------- -- components-widgets-likes -- Social Likes Components -- Copyright (C) 2013 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Locales; with Util.Beans.Objects; with Util.Strings.Tokenizers; with ASF.Requests; with ASF.Contexts.Writer; package body ASF.Components.Widgets.Likes is FB_LAYOUT_ATTR : aliased constant String := "data-layout"; FB_SHOW_FACES_ATTR : aliased constant String := "data-show-faces"; FB_WIDTH_ATTR : aliased constant String := "data-width"; FB_ACTION_ATTR : aliased constant String := "data-action"; FB_FONT_ATTR : aliased constant String := "data-font"; FB_COlORSCHEME_ATTR : aliased constant String := "data-colorscheme"; FB_REF_ATTR : aliased constant String := "data-ref"; FB_KIDS_ATTR : aliased constant String := "data-kid_directed_site"; FB_SEND_ATTR : aliased constant String := "data-send"; TW_VIA_ATTR : aliased constant String := "data-via"; TW_COUNT_ATTR : aliased constant String := "data-count"; TW_SIZE_ATTR : aliased constant String := "data-size"; G_ANNOTATION_ATTR : aliased constant String := "data-annotation"; G_WIDTH_ATTR : aliased constant String := "data-width"; FACEBOOK_ATTRIBUTE_NAMES : Util.Strings.String_Set.Set; FACEBOOK_SCRIPT_ATTRIBUTE : constant String := "asf.widgets.facebook.script"; GOOGLE_ATTRIBUTE_NAMES : Util.Strings.String_Set.Set; GOOGLE_SCRIPT_ATTRIBUTE : constant String := "asf.widgets.google.script"; TWEETER_ATTRIBUTE_NAMES : Util.Strings.String_Set.Set; TWEETER_SCRIPT_ATTRIBUTE : constant String := "asf.widgets.tweeter.script"; type Like_Generator_Binding is record Name : Util.Strings.Name_Access; Generator : Like_Generator_Access; end record; type Like_Generator_Array is array (1 .. MAX_LIKE_GENERATOR) of Like_Generator_Binding; FB_NAME : aliased constant String := "facebook"; FB_GENERATOR : aliased Facebook_Like_Generator; G_NAME : aliased constant String := "google+"; G_GENERATOR : aliased Google_Like_Generator; TWEETER_NAME : aliased constant String := "tweeter"; TWEETER_GENERATOR : aliased Tweeter_Like_Generator; Generators : Like_Generator_Array := (1 => (FB_NAME'Access, FB_GENERATOR'Access), 2 => (G_NAME'Access, G_GENERATOR'Access), 3 => (TWEETER_NAME'Access, TWEETER_GENERATOR'Access), others => (null, null)); -- ------------------------------ -- Render the facebook like button according to the component attributes. -- ------------------------------ overriding procedure Render_Like (Generator : in Facebook_Like_Generator; UI : in UILike'Class; Href : in String; Context : in out ASF.Contexts.Faces.Faces_Context'Class) is Writer : constant Contexts.Writer.Response_Writer_Access := Context.Get_Response_Writer; Request : constant ASF.Requests.Request_Access := Context.Get_Request; begin if not Context.Is_Ajax_Request and then Util.Beans.Objects.Is_Null (Request.Get_Attribute (FACEBOOK_SCRIPT_ATTRIBUTE)) then Request.Set_Attribute (FACEBOOK_SCRIPT_ATTRIBUTE, Util.Beans.Objects.To_Object (True)); Writer.Queue_Script ("(function(d, s, id) { var js, fjs = d.getElementsByTagName(s)[0];" & "if (d.getElementById(id)) return;" & "js = d.createElement(s); js.id = id;" & "js.src = ""//connect.facebook.net/"); Writer.Queue_Script (Util.Locales.To_String (Context.Get_Locale)); Writer.Queue_Script ("/all.js#xfbml=1&;appId=116337738505130"); Writer.Queue_Script (Generator.App_Id); Writer.Queue_Script (""";fjs.parentNode.insertBefore(js, fjs);" & "}(document, 'script', 'facebook-jssdk'));"); Writer.Start_Element ("div"); Writer.Write_Attribute ("id", "fb-root"); Writer.End_Element ("div"); end if; Writer.Start_Element ("div"); Writer.Write_Attribute ("class", "fb-like"); Writer.Write_Attribute ("data-href", Href); UI.Render_Attributes (Context, FACEBOOK_ATTRIBUTE_NAMES, Writer); Writer.End_Element ("div"); end Render_Like; -- ------------------------------ -- Google like generator -- ------------------------------ overriding procedure Render_Like (Generator : in Google_Like_Generator; UI : in UILike'Class; Href : in String; Context : in out ASF.Contexts.Faces.Faces_Context'Class) is pragma Unreferenced (Generator); Writer : constant Contexts.Writer.Response_Writer_Access := Context.Get_Response_Writer; Request : constant ASF.Requests.Request_Access := Context.Get_Request; begin if not Context.Is_Ajax_Request and then Util.Beans.Objects.Is_Null (Request.Get_Attribute (GOOGLE_SCRIPT_ATTRIBUTE)) then Request.Set_Attribute (GOOGLE_SCRIPT_ATTRIBUTE, Util.Beans.Objects.To_Object (True)); Writer.Queue_Include_Script ("https://apis.google.com/js/plusone.js"); end if; Writer.Start_Element ("div"); Writer.Write_Attribute ("class", "g-plusone"); Writer.Write_Attribute ("data-href", Href); UI.Render_Attributes (Context, GOOGLE_ATTRIBUTE_NAMES, Writer); Writer.End_Element ("div"); end Render_Like; -- ------------------------------ -- Tweeter like generator -- ------------------------------ overriding procedure Render_Like (Generator : in Tweeter_Like_Generator; UI : in UILike'Class; Href : in String; Context : in out ASF.Contexts.Faces.Faces_Context'Class) is pragma Unreferenced (Generator); Writer : constant Contexts.Writer.Response_Writer_Access := Context.Get_Response_Writer; Request : constant ASF.Requests.Request_Access := Context.Get_Request; Lang : constant String := Util.Locales.Get_ISO3_Language (Context.Get_Locale); begin if not Context.Is_Ajax_Request and then Util.Beans.Objects.Is_Null (Request.Get_Attribute (TWEETER_SCRIPT_ATTRIBUTE)) then Request.Set_Attribute (TWEETER_SCRIPT_ATTRIBUTE, Util.Beans.Objects.To_Object (True)); Writer.Queue_Script ("!function(d,s,id){var js,fjs=d.getElementsByTagName(s)[0]," & "p=/^http:/.test(d.location)?'http':'https';" & "if(!d.getElementById(id)){js=d.createElement(s);js.id=id;" & "js.src=p+'://platform.twitter.com/widgets.js';" & "fjs.parentNode.insertBefore(js,fjs);}}" & "(document, 'script', 'twitter-wjs');"); end if; Writer.Start_Element ("a"); Writer.Write_Attribute ("href", "https://twitter.com/share"); Writer.Write_Attribute ("class", "twitter-share-button"); Writer.Write_Attribute ("data-url", Href); Writer.Write_Attribute ("data-lang", Lang); UI.Render_Attributes (Context, TWEETER_ATTRIBUTE_NAMES, Writer); Writer.Write_Text ("Tweet"); Writer.End_Element ("a"); end Render_Like; -- ------------------------------ -- Get the link to submit in the like action. -- ------------------------------ function Get_Link (UI : in UILike; Context : in ASF.Contexts.Faces.Faces_Context'Class) return String is Href : constant String := UI.Get_Attribute ("href", Context, ""); begin if Href'Length > 0 then return Href; else return Context.Get_Request.Get_Request_URI; end if; end Get_Link; -- ------------------------------ -- Render an image with the source link created from an email address to the Gravatars service. -- ------------------------------ overriding procedure Encode_Begin (UI : in UILike; Context : in out ASF.Contexts.Faces.Faces_Context'Class) is begin if UI.Is_Rendered (Context) then declare Kind : constant String := UI.Get_Attribute ("type", Context, ""); Href : constant String := UILike'Class (UI).Get_Link (Context); procedure Render (Name : in String; Done : out Boolean); procedure Render (Name : in String; Done : out Boolean) is use type Util.Strings.Name_Access; begin Done := False; for I in Generators'Range loop exit when Generators (I).Name = null; if Generators (I).Name.all = Name then Generators (I).Generator.Render_Like (UI, Href, Context); return; end if; end loop; UI.Log_Error ("Like type {0} is not recognized", Name); end Render; begin if Kind'Length = 0 then UI.Log_Error ("The like type is empty."); else Util.Strings.Tokenizers.Iterate_Tokens (Content => Kind, Pattern => ",", Process => Render'Access); end if; end; end if; end Encode_Begin; -- ------------------------------ -- Register the like generator under the given name. -- ------------------------------ procedure Register_Like (Name : in Util.Strings.Name_Access; Generator : in Like_Generator_Access) is use type Util.Strings.Name_Access; begin for I in Generators'Range loop if Generators (I).Name = null then Generators (I).Name := Name; Generators (I).Generator := Generator; return; end if; end loop; end Register_Like; begin FACEBOOK_ATTRIBUTE_NAMES.Insert (FB_LAYOUT_ATTR'Access); FACEBOOK_ATTRIBUTE_NAMES.Insert (FB_SHOW_FACES_ATTR'Access); FACEBOOK_ATTRIBUTE_NAMES.Insert (FB_WIDTH_ATTR'Access); FACEBOOK_ATTRIBUTE_NAMES.Insert (FB_ACTION_ATTR'Access); FACEBOOK_ATTRIBUTE_NAMES.Insert (FB_FONT_ATTR'Access); FACEBOOK_ATTRIBUTE_NAMES.Insert (FB_COlORSCHEME_ATTR'Access); FACEBOOK_ATTRIBUTE_NAMES.Insert (FB_REF_ATTR'Access); FACEBOOK_ATTRIBUTE_NAMES.Insert (FB_KIDS_ATTR'Access); FACEBOOK_ATTRIBUTE_NAMES.Insert (FB_SEND_ATTR'Access); TWEETER_ATTRIBUTE_NAMES.Insert (TW_SIZE_ATTR'Access); TWEETER_ATTRIBUTE_NAMES.Insert (TW_COUNT_ATTR'Access); TWEETER_ATTRIBUTE_NAMES.Insert (TW_VIA_ATTR'Access); GOOGLE_ATTRIBUTE_NAMES.Insert (G_ANNOTATION_ATTR'Access); GOOGLE_ATTRIBUTE_NAMES.Insert (G_WIDTH_ATTR'Access); end ASF.Components.Widgets.Likes;
Add control attributes for Google+ and Facebook buttons
Add control attributes for Google+ and Facebook buttons
Ada
apache-2.0
Letractively/ada-asf,Letractively/ada-asf,Letractively/ada-asf
d32debbf01a83eabe6ce50972c7e3147c57923a2
src/ado-sessions-factory.adb
src/ado-sessions-factory.adb
----------------------------------------------------------------------- -- factory -- Session Factory -- Copyright (C) 2009, 2010, 2011, 2012, 2017, 2018 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with ADO.Sequences.Hilo; with ADO.Schemas.Entities; with ADO.Queries.Loaders; package body ADO.Sessions.Factory is -- ------------------------------ -- Get a read-only session from the factory. -- ------------------------------ function Get_Session (Factory : in Session_Factory) return Session is R : Session; S : constant Session_Record_Access := new Session_Record; begin R.Impl := S; S.Entities := Factory.Entities; S.Values := Factory.Cache_Values; S.Queries := Factory.Queries'Unrestricted_Access; Factory.Source.Create_Connection (S.Database); return R; end Get_Session; -- ------------------------------ -- Get a read-only session from the session proxy. -- If the session has been invalidated, raise the Session_Error exception. -- ------------------------------ function Get_Session (Proxy : in Session_Record_Access) return Session is R : Session; begin if Proxy = null then raise Session_Error; end if; R.Impl := Proxy; Util.Concurrent.Counters.Increment (R.Impl.Counter); return R; end Get_Session; -- ------------------------------ -- Get a read-write session from the factory. -- ------------------------------ function Get_Master_Session (Factory : in Session_Factory) return Master_Session is R : Master_Session; S : constant Session_Record_Access := new Session_Record; begin R.Impl := S; R.Sequences := Factory.Sequences; S.Entities := Factory.Entities; S.Values := Factory.Cache_Values; S.Queries := Factory.Queries'Unrestricted_Access; Factory.Source.Create_Connection (S.Database); return R; end Get_Master_Session; -- ------------------------------ -- Initialize the sequence factory associated with the session factory. -- ------------------------------ procedure Initialize_Sequences (Factory : in out Session_Factory) is use ADO.Sequences; begin Factory.Sequences := Factory.Seq_Factory'Unchecked_Access; Set_Default_Generator (Factory.Seq_Factory, ADO.Sequences.Hilo.Create_HiLo_Generator'Access, Factory'Unchecked_Access); end Initialize_Sequences; -- ------------------------------ -- Create the session factory to connect to the database represented -- by the data source. -- ------------------------------ procedure Create (Factory : out Session_Factory; Source : in ADO.Sessions.Sources.Data_Source) is begin Factory.Source := Source; Factory.Entities := new ADO.Schemas.Entities.Entity_Cache; Factory.Cache_Values := Factory.Cache'Unchecked_Access; Factory.Cache.Add_Cache (ENTITY_CACHE_NAME, Factory.Entities.all'Access); ADO.Queries.Loaders.Initialize (Factory.Queries, Factory.Source); Initialize_Sequences (Factory); if Factory.Source.Get_Database /= "" and not Drivers.Is_On (Configs.NO_ENTITY_LOAD) then declare S : Session := Factory.Get_Session; begin ADO.Schemas.Entities.Initialize (Factory.Entities.all, S); end; end if; end Create; -- ------------------------------ -- Create the session factory to connect to the database identified -- by the URI. -- ------------------------------ procedure Create (Factory : out Session_Factory; URI : in String) is begin Factory.Source.Set_Connection (URI); Factory.Entities := new ADO.Schemas.Entities.Entity_Cache; Factory.Cache_Values := Factory.Cache'Unchecked_Access; Factory.Cache.Add_Cache (ENTITY_CACHE_NAME, Factory.Entities.all'Access); ADO.Queries.Loaders.Initialize (Factory.Queries, Factory.Source); Initialize_Sequences (Factory); if Factory.Source.Get_Database /= "" and not Drivers.Is_On (Configs.NO_ENTITY_LOAD) then declare S : Session := Factory.Get_Session; begin ADO.Schemas.Entities.Initialize (Factory.Entities.all, S); end; end if; end Create; end ADO.Sessions.Factory;
----------------------------------------------------------------------- -- ado-sessions-factory -- Session Factory -- Copyright (C) 2009, 2010, 2011, 2012, 2017, 2018 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with ADO.Sequences.Hilo; with ADO.Schemas.Entities; with ADO.Queries.Loaders; package body ADO.Sessions.Factory is -- ------------------------------ -- Get a read-only session from the factory. -- ------------------------------ function Get_Session (Factory : in Session_Factory) return Session is R : Session; S : constant Session_Record_Access := new Session_Record; begin R.Impl := S; S.Entities := Factory.Entities; S.Values := Factory.Cache_Values; S.Queries := Factory.Queries'Unrestricted_Access; Factory.Source.Create_Connection (S.Database); return R; end Get_Session; -- ------------------------------ -- Get a read-only session from the session proxy. -- If the session has been invalidated, raise the Session_Error exception. -- ------------------------------ function Get_Session (Proxy : in Session_Record_Access) return Session is R : Session; begin if Proxy = null then raise Session_Error; end if; R.Impl := Proxy; Util.Concurrent.Counters.Increment (R.Impl.Counter); return R; end Get_Session; -- ------------------------------ -- Get a read-write session from the factory. -- ------------------------------ function Get_Master_Session (Factory : in Session_Factory) return Master_Session is R : Master_Session; S : constant Session_Record_Access := new Session_Record; begin R.Impl := S; R.Sequences := Factory.Sequences; R.Audit := Factory.Audit; S.Entities := Factory.Entities; S.Values := Factory.Cache_Values; S.Queries := Factory.Queries'Unrestricted_Access; Factory.Source.Create_Connection (S.Database); return R; end Get_Master_Session; -- ------------------------------ -- Initialize the sequence factory associated with the session factory. -- ------------------------------ procedure Initialize_Sequences (Factory : in out Session_Factory) is use ADO.Sequences; begin Factory.Sequences := Factory.Seq_Factory'Unchecked_Access; Set_Default_Generator (Factory.Seq_Factory, ADO.Sequences.Hilo.Create_HiLo_Generator'Access, Factory'Unchecked_Access); end Initialize_Sequences; -- ------------------------------ -- Create the session factory to connect to the database represented -- by the data source. -- ------------------------------ procedure Create (Factory : out Session_Factory; Source : in ADO.Sessions.Sources.Data_Source) is begin Factory.Source := Source; Factory.Entities := new ADO.Schemas.Entities.Entity_Cache; Factory.Cache_Values := Factory.Cache'Unchecked_Access; Factory.Cache.Add_Cache (ENTITY_CACHE_NAME, Factory.Entities.all'Access); ADO.Queries.Loaders.Initialize (Factory.Queries, Factory.Source); Initialize_Sequences (Factory); if Factory.Source.Get_Database /= "" and not Drivers.Is_On (Configs.NO_ENTITY_LOAD) then declare S : Session := Factory.Get_Session; begin ADO.Schemas.Entities.Initialize (Factory.Entities.all, S); end; end if; end Create; -- ------------------------------ -- Create the session factory to connect to the database identified -- by the URI. -- ------------------------------ procedure Create (Factory : out Session_Factory; URI : in String) is begin Factory.Source.Set_Connection (URI); Factory.Entities := new ADO.Schemas.Entities.Entity_Cache; Factory.Cache_Values := Factory.Cache'Unchecked_Access; Factory.Cache.Add_Cache (ENTITY_CACHE_NAME, Factory.Entities.all'Access); ADO.Queries.Loaders.Initialize (Factory.Queries, Factory.Source); Initialize_Sequences (Factory); if Factory.Source.Get_Database /= "" and not Drivers.Is_On (Configs.NO_ENTITY_LOAD) then declare S : Session := Factory.Get_Session; begin ADO.Schemas.Entities.Initialize (Factory.Entities.all, S); end; end if; end Create; -- ------------------------------ -- Set the audit manager to be used for the object auditing support. -- ------------------------------ procedure Set_Audit_Manager (Factory : in out Session_Factory; Manager : in ADO.Audits.Audit_Manager_Access) is begin Factory.Audit := Manager; end Set_Audit_Manager; end ADO.Sessions.Factory;
Implement the Set_Audit_Manager procedure
Implement the Set_Audit_Manager procedure
Ada
apache-2.0
stcarrez/ada-ado
1abc77603bb3fbc02f541a6f3f146ef10fb57bad
awa/plugins/awa-mail/src/aws/awa-mail-clients-aws_smtp.ads
awa/plugins/awa-mail/src/aws/awa-mail-clients-aws_smtp.ads
----------------------------------------------------------------------- -- awa-mail-clients-aws_smtp -- Mail client implementation on top of AWS SMTP client -- 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 Ada.Strings.Unbounded; with Ada.Finalization; with Util.Properties; with AWS.SMTP; with AWS.SMTP.Authentication.Plain; -- The <b>AWA.Mail.Clients.AWS_SMTP</b> package provides an implementation of the -- mail client interfaces on top of AWS SMTP client API. package AWA.Mail.Clients.AWS_SMTP is NAME : constant String := "smtp"; -- ------------------------------ -- Mail Message -- ------------------------------ -- The <b>Mail_Message</b> represents an abstract mail message that can be initialized -- before being sent. type AWS_Mail_Message is new Ada.Finalization.Limited_Controlled and Mail_Message with private; type AWS_Mail_Message_Access is access all AWS_Mail_Message'Class; -- Set the <tt>From</tt> part of the message. overriding procedure Set_From (Message : in out AWS_Mail_Message; Name : in String; Address : in String); -- Add a recipient for the message. overriding procedure Add_Recipient (Message : in out AWS_Mail_Message; Kind : in Recipient_Type; Name : in String; Address : in String); -- Set the subject of the message. overriding procedure Set_Subject (Message : in out AWS_Mail_Message; Subject : in String); -- Set the body of the message. overriding procedure Set_Body (Message : in out AWS_Mail_Message; Content : in String); -- Send the email message. overriding procedure Send (Message : in out AWS_Mail_Message); -- Deletes the mail message. overriding procedure Finalize (Message : in out AWS_Mail_Message); -- ------------------------------ -- Mail Manager -- ------------------------------ -- The <b>Mail_Manager</b> is the entry point to create a new mail message -- and be able to send it. type AWS_Mail_Manager is new Mail_Manager with private; type AWS_Mail_Manager_Access is access all AWS_Mail_Manager'Class; -- Create a SMTP based mail manager and configure it according to the properties. function Create_Manager (Props : in Util.Properties.Manager'Class) return Mail_Manager_Access; -- Create a new mail message. overriding function Create_Message (Manager : in AWS_Mail_Manager) return Mail_Message_Access; private type Recipients_Access is access all AWS.SMTP.Recipients; type AWS_Mail_Message is new Ada.Finalization.Limited_Controlled and Mail_Message with record Manager : AWS_Mail_Manager_Access; From : AWS.SMTP.E_Mail_Data; Subject : Ada.Strings.Unbounded.Unbounded_String; Content : Ada.Strings.Unbounded.Unbounded_String; To : Recipients_Access := null; end record; type AWS_Mail_Manager is new Mail_Manager with record Self : AWS_Mail_Manager_Access; Server : AWS.SMTP.Receiver; Creds : aliased AWS.SMTP.Authentication.Plain.Credential; Enable : Boolean := True; Secure : Boolean := False; Auth : Boolean := False; end record; end AWA.Mail.Clients.AWS_SMTP;
----------------------------------------------------------------------- -- awa-mail-clients-aws_smtp -- Mail client implementation on top of AWS SMTP client -- 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 Ada.Strings.Unbounded; with Ada.Finalization; with Util.Properties; with AWS.SMTP; with AWS.SMTP.Authentication.Plain; -- The <b>AWA.Mail.Clients.AWS_SMTP</b> package provides an implementation of the -- mail client interfaces on top of AWS SMTP client API. package AWA.Mail.Clients.AWS_SMTP is NAME : constant String := "smtp"; -- ------------------------------ -- Mail Message -- ------------------------------ -- The <b>Mail_Message</b> represents an abstract mail message that can be initialized -- before being sent. type AWS_Mail_Message is new Ada.Finalization.Limited_Controlled and Mail_Message with private; type AWS_Mail_Message_Access is access all AWS_Mail_Message'Class; -- Set the <tt>From</tt> part of the message. overriding procedure Set_From (Message : in out AWS_Mail_Message; Name : in String; Address : in String); -- Add a recipient for the message. overriding procedure Add_Recipient (Message : in out AWS_Mail_Message; Kind : in Recipient_Type; Name : in String; Address : in String); -- Set the subject of the message. overriding procedure Set_Subject (Message : in out AWS_Mail_Message; Subject : in String); -- Set the body of the message. overriding procedure Set_Body (Message : in out AWS_Mail_Message; Content : in String); -- Send the email message. overriding procedure Send (Message : in out AWS_Mail_Message); -- Deletes the mail message. overriding procedure Finalize (Message : in out AWS_Mail_Message); -- ------------------------------ -- Mail Manager -- ------------------------------ -- The <b>Mail_Manager</b> is the entry point to create a new mail message -- and be able to send it. type AWS_Mail_Manager is new Mail_Manager with private; type AWS_Mail_Manager_Access is access all AWS_Mail_Manager'Class; -- Create a SMTP based mail manager and configure it according to the properties. function Create_Manager (Props : in Util.Properties.Manager'Class) return Mail_Manager_Access; -- Create a new mail message. overriding function Create_Message (Manager : in AWS_Mail_Manager) return Mail_Message_Access; private type Recipients_Access is access all AWS.SMTP.Recipients; type AWS_Mail_Message is new Ada.Finalization.Limited_Controlled and Mail_Message with record Manager : AWS_Mail_Manager_Access; From : AWS.SMTP.E_Mail_Data; Subject : Ada.Strings.Unbounded.Unbounded_String; Content : Ada.Strings.Unbounded.Unbounded_String; To : Recipients_Access := null; end record; type AWS_Mail_Manager is new Mail_Manager with record Self : AWS_Mail_Manager_Access; Server : AWS.SMTP.Receiver; Creds : aliased AWS.SMTP.Authentication.Plain.Credential; Port : Positive := 25; Enable : Boolean := True; Secure : Boolean := False; Auth : Boolean := False; end record; procedure Initialize (Client : in out AWS_Mail_Manager'Class; Props : in Util.Properties.Manager'Class); end AWA.Mail.Clients.AWS_SMTP;
Declare the Initialize procedure
Declare the Initialize procedure
Ada
apache-2.0
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
1574dc0e79311b5245fd7230bd99f45aa0938afb
src/asf-rest.ads
src/asf-rest.ads
----------------------------------------------------------------------- -- asf-rest -- REST Support -- 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 Util.Strings; with ASF.Requests; with ASF.Responses; with Security.Permissions; -- == REST == -- The <tt>ASF.Rest</tt> package provides support to implement easily some RESTful API. package ASF.Rest is type Request is abstract new ASF.Requests.Request with null record; type Response is abstract new ASF.Responses.Response with null record; -- The HTTP rest method. type Method_Type is (GET, HEAD, POST, PUT, DELETE, OPTIONS); type Descriptor is abstract tagged limited private; type Descriptor_Access is access all Descriptor'Class; -- Get the permission index associated with the REST operation. function Get_Permission (Handler : in Descriptor) return Security.Permissions.Permission_Index; -- Dispatch the request to the API handler. procedure Dispatch (Handler : in Descriptor; Req : in out ASF.Rest.Request'Class; Reply : in out ASF.Rest.Response'Class) is abstract; private type Descriptor is abstract tagged limited record Next : Descriptor_Access; Method : Method_Type; Pattern : Util.Strings.Name_Access; Permission : Security.Permissions.Permission_Index := 0; end record; -- Register the API descriptor in a list. procedure Register (List : in out Descriptor_Access; Item : in Descriptor_Access); end ASF.Rest;
----------------------------------------------------------------------- -- asf-rest -- REST Support -- 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 Util.Strings; with Util.Serialize.IO; with ASF.Requests; with ASF.Responses; with ASF.Servlets; with EL.Contexts; with Security.Permissions; -- == REST == -- The <tt>ASF.Rest</tt> package provides support to implement easily some RESTful API. package ASF.Rest is subtype Request is ASF.Requests.Request; subtype Response is ASF.Responses.Response; subtype Output_Stream is Util.Serialize.IO.Output_Stream; -- The HTTP rest method. type Method_Type is (GET, HEAD, POST, PUT, DELETE, TRACE, CONNECT, OPTIONS); type Descriptor is abstract tagged limited private; type Descriptor_Access is access all Descriptor'Class; -- Get the permission index associated with the REST operation. function Get_Permission (Handler : in Descriptor) return Security.Permissions.Permission_Index; -- Dispatch the request to the API handler. procedure Dispatch (Handler : in Descriptor; Req : in out ASF.Rest.Request'Class; Reply : in out ASF.Rest.Response'Class; Stream : in out Output_Stream'Class) is abstract; private type Descriptor is abstract tagged limited record Next : Descriptor_Access; Method : Method_Type; Pattern : Util.Strings.Name_Access; Permission : Security.Permissions.Permission_Index := 0; end record; -- Register the API descriptor in a list. procedure Register (List : in out Descriptor_Access; Item : in Descriptor_Access); -- Register the list of API descriptors for a given servlet and a root path. procedure Register (Registry : in out ASF.Servlets.Servlet_Registry; Name : in String; URI : in String; ELContext : in EL.Contexts.ELContext'Class; List : in Descriptor_Access); end ASF.Rest;
Add the TRACE and CONNECT http methods Define the Output_Stream type Add a Stream in out parameter to the Dispatch procedure Declare the private Register procedure used by the ASF.Rest.Definition generic to register the list of APIs
Add the TRACE and CONNECT http methods Define the Output_Stream type Add a Stream in out parameter to the Dispatch procedure Declare the private Register procedure used by the ASF.Rest.Definition generic to register the list of APIs
Ada
apache-2.0
stcarrez/ada-asf,stcarrez/ada-asf,stcarrez/ada-asf
d5de50b115233ec0964e727ef61512d130514725
examples/functions_example.adb
examples/functions_example.adb
-- Functions_Example -- A example of using the Ada 2012 interface to Lua for functions / closures etc -- Copyright (c) 2015, James Humphry -- Permission is hereby granted, free of charge, to any person obtaining -- a copy of this software and associated documentation files (the -- "Software"), to deal in the Software without restriction, including -- without limitation the rights to use, copy, modify, merge, publish, -- distribute, sublicense, and/or sell copies of the Software, and to -- permit persons to whom the Software is furnished to do so, subject to -- the following conditions: -- -- The above copyright notice and this permission notice shall be -- included in all copies or substantial portions of the Software. -- -- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -- EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -- MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. -- IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY -- CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, -- TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE -- SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. with Ada.Text_IO; use Ada.Text_IO; with Ada.Long_Float_Text_IO; use Ada.Long_Float_Text_IO; with Ada.Integer_Text_IO; use Ada.Integer_Text_IO; with Ada.Characters.Latin_1; with Lua; use Lua; with Lua.Util; use Lua.Util; with Example_AdaFunctions; procedure Functions_Example is L : State; Success : Thread_Status; LF : Character renames Ada.Characters.Latin_1.LF; Coroutine_Source : String := "" & "co = coroutine.create( function (x) " & LF & " for i = 1, x do " & LF & " coroutine.yield(i) " & LF & " end " & LF & " return -1 " & LF & " end " & LF & ")"; begin Put_Line("A simple example of using Lua and Ada functions together"); Put("Lua version: "); Put(Item => L.Version, Aft => 0, Exp => 0); New_Line; New_Line; Put_Line("Loading chunk: function f (x) return 2*x end"); Success := L.LoadString("function f (x) return 2*x end"); Put_Line("Load" & (if Success /= OK then " not" else "") & " successful."); L.Call(0, 0); Put_Line("Compiled chunk."); Put("Result of calling f (3): "); L.GetGlobal("f"); L.PushNumber(3.0); L.Call(1, 1); Put(L.ToNumber(-1), Aft => 0, Exp => 0); New_Line; L.Pop(1); New_Line; L.Pop(L.GetTop); Put_Line("Registering an AdaFunction foobar in Lua"); L.Register("foobar", AdaFunction'(Example_AdaFunctions.Foobar'Access)); Success := L.LoadString("baz = foobar(5.0)"); Put_Line("Loading code snippet 'baz = foobar(5.0)'" & (if Success /= OK then " not" else "") & " successful."); Put_Line("Calling 'baz = foobar(5.0)' from Lua"); L.Call(0, 0); Put("baz = "); L.GetGlobal("baz"); Put(L.ToNumber(-1), Aft => 0, Exp => 0); New_Line; New_Line; L.Pop(L.GetTop); Put_Line("Registering an AdaFunction multret in Lua"); L.Register("multret", AdaFunction'(Example_AdaFunctions.Multret'Access)); Put_Line("Calling 'multret(5)' from Lua"); L.GetGlobal("multret"); L.PushInteger(5); L.Call(1, MultRet_Sentinel); Put_Line("Stack now contains:"); Print_Stack(L); New_Line; L.Pop(L.GetTop); Put_Line("Registering an AdaFunction closure (with upvalue 2.0) in Lua"); L.PushNumber(2.0); L.PushAdaClosure(AdaFunction'(Example_AdaFunctions.Closure'Access), 1); L.SetGlobal("closure"); Put_Line("Calling 'closure(3.5)' from Lua"); L.GetGlobal("closure"); L.PushNumber(3.5); L.Call(1, MultRet_Sentinel); Put_Line("Stack now contains:"); Print_Stack(L); New_Line; L.Pop(L.GetTop); Put_Line("Adding standard libraries..."); L.OpenLibs; Put_Line("Loading coroutine: " & Coroutine_Source); New_Line; Success := L.LoadString(Coroutine_Source); Put_Line("Load" & (if Success /= OK then " not" else "") & " successful."); L.Call(0, 0); L.GetGlobal("co"); pragma Assert (L.TypeInfo(-1) = TTHREAD); Put_Line("Compiled chunk. Resuming coroutine with parameter 3"); declare Coroutine : Thread := L.ToThread(-1); Coroutine_Status : Thread_Status; begin Coroutine.PushInteger(3); Coroutine_Status := Coroutine.resume(L, 1); Put_Line("Coroutine status : " & Thread_Status'Image(Coroutine_Status)); Print_Stack(Coroutine); while Coroutine_Status = YIELD loop Coroutine_Status := Coroutine.resume(L, 1); Put_Line("Coroutine status : " & Thread_Status'Image(Coroutine_Status)); Print_Stack(Coroutine); end loop; end; New_Line; end Functions_Example;
-- Functions_Example -- A example of using the Ada 2012 interface to Lua for functions / closures etc -- Copyright (c) 2015, James Humphry -- Permission is hereby granted, free of charge, to any person obtaining -- a copy of this software and associated documentation files (the -- "Software"), to deal in the Software without restriction, including -- without limitation the rights to use, copy, modify, merge, publish, -- distribute, sublicense, and/or sell copies of the Software, and to -- permit persons to whom the Software is furnished to do so, subject to -- the following conditions: -- -- The above copyright notice and this permission notice shall be -- included in all copies or substantial portions of the Software. -- -- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -- EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -- MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. -- IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY -- CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, -- TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE -- SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. with Ada.Text_IO; use Ada.Text_IO; with Ada.Long_Float_Text_IO; use Ada.Long_Float_Text_IO; with Ada.Integer_Text_IO; use Ada.Integer_Text_IO; with Ada.Characters.Latin_1; with Lua; use Lua; with Lua.Util; use Lua.Util; with Example_AdaFunctions; procedure Functions_Example is L : State; Success : Thread_Status; LF : Character renames Ada.Characters.Latin_1.LF; Coroutine_Source : String := "" & "function co (x) " & LF & " for i = 1, x do " & LF & " coroutine.yield(i) " & LF & " end " & LF & " return -1 " & LF & " end " & LF & ""; begin Put_Line("A simple example of using Lua and Ada functions together"); Put("Lua version: "); Put(Item => L.Version, Aft => 0, Exp => 0); New_Line; New_Line; Put_Line("Loading chunk: function f (x) return 2*x end"); Success := L.LoadString("function f (x) return 2*x end"); Put_Line("Load" & (if Success /= OK then " not" else "") & " successful."); L.Call(0, 0); Put_Line("Compiled chunk."); Put("Result of calling f (3): "); L.GetGlobal("f"); L.PushNumber(3.0); L.Call(1, 1); Put(L.ToNumber(-1), Aft => 0, Exp => 0); New_Line; L.Pop(1); New_Line; L.Pop(L.GetTop); Put_Line("Registering an AdaFunction foobar in Lua"); L.Register("foobar", AdaFunction'(Example_AdaFunctions.Foobar'Access)); Success := L.LoadString("baz = foobar(5.0)"); Put_Line("Loading code snippet 'baz = foobar(5.0)'" & (if Success /= OK then " not" else "") & " successful."); Put_Line("Calling 'baz = foobar(5.0)' from Lua"); L.Call(0, 0); Put("baz = "); L.GetGlobal("baz"); Put(L.ToNumber(-1), Aft => 0, Exp => 0); New_Line; New_Line; L.Pop(L.GetTop); Put_Line("Registering an AdaFunction multret in Lua"); L.Register("multret", AdaFunction'(Example_AdaFunctions.Multret'Access)); Put_Line("Calling 'multret(5)' from Lua"); L.GetGlobal("multret"); L.PushInteger(5); L.Call(1, MultRet_Sentinel); Put_Line("Stack now contains:"); Print_Stack(L); New_Line; L.Pop(L.GetTop); Put_Line("Registering an AdaFunction closure (with upvalue 2.0) in Lua"); L.PushNumber(2.0); L.PushAdaClosure(AdaFunction'(Example_AdaFunctions.Closure'Access), 1); L.SetGlobal("closure"); Put_Line("Calling 'closure(3.5)' from Lua"); L.GetGlobal("closure"); L.PushNumber(3.5); L.Call(1, MultRet_Sentinel); Put_Line("Stack now contains:"); Print_Stack(L); New_Line; L.Pop(L.GetTop); Put_Line("Now to look at using coroutines"); Put_Line("Adding standard libraries..."); L.OpenLibs; Put_Line("Loading coroutine source: "); Put_Line(Coroutine_Source); Success := L.LoadString(Coroutine_Source); Put_Line("Load" & (if Success /= OK then " not" else "") & " successful."); L.Call(0, 0); Put_Line("Compiled coroutine code."); declare Coroutine : Thread := L.NewThread; Coroutine_Status : Thread_Status; begin Put_Line("New thread created"); Put_Line("Resuming coroutine with parameter 3 in this thread:"); Coroutine.GetGlobal("co"); Coroutine.PushInteger(3); Coroutine_Status := Coroutine.resume(L, 1); Put("Coroutine status : " & Thread_Status'Image(Coroutine_Status)); Put(" Result: "); Put(Coroutine.ToNumber(-1)); New_Line; while Coroutine_Status = YIELD loop Coroutine_Status := Coroutine.resume(L, 1); Put("Coroutine status : " & Thread_Status'Image(Coroutine_Status)); Put(" Result: "); Put(Coroutine.ToNumber(-1)); New_Line; end loop; end; New_Line; end Functions_Example;
Improve example of using a Lua coroutine from Ada
Improve example of using a Lua coroutine from Ada Create the new thread in Ada rather than in the Lua source.
Ada
mit
jhumphry/aLua
d1445cd4a82d11e176831c44c84ca0f563a32ac7
src/util-beans-objects-datasets.adb
src/util-beans-objects-datasets.adb
----------------------------------------------------------------------- -- Util.Beans.Objects.Datasets -- Datasets -- Copyright (C) 2013 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Unchecked_Deallocation; package body Util.Beans.Objects.Datasets is procedure Free is new Ada.Unchecked_Deallocation (Object => Object_Array, Name => Object_Array_Access); procedure Free is new Ada.Unchecked_Deallocation (Object => Dataset_Array, Name => Dataset_Array_Access); -- ------------------------------ -- Get the number of elements in the list. -- ------------------------------ overriding function Get_Count (From : in Dataset) return Natural is begin return From.Count; end Get_Count; -- ------------------------------ -- Set the current row index. Valid row indexes start at 1. -- ------------------------------ overriding procedure Set_Row_Index (From : in out Dataset; Index : in Natural) is begin From.Current_Pos := Index; From.Current.Data := From.Data (Index); end Set_Row_Index; -- ------------------------------ -- Get the element at the current row index. -- ------------------------------ overriding function Get_Row (From : in Dataset) return Util.Beans.Objects.Object is begin return From.Row; end Get_Row; -- ------------------------------ -- Get the value identified by the name. -- If the name cannot be found, the method should return the Null object. -- ------------------------------ overriding function Get_Value (From : in Dataset; Name : in String) return Util.Beans.Objects.Object is begin if Name = "count" then return Util.Beans.Objects.To_Object (From.Count); elsif Name = "rowIndex" then return Util.Beans.Objects.To_Object (From.Current_Pos); else return Util.Beans.Objects.Null_Object; end if; end Get_Value; -- ------------------------------ -- Append a row in the dataset and call the fill procedure to populate -- the row content. -- ------------------------------ procedure Append (Into : in out Dataset; Fill : not null access procedure (Data : in out Object_Array)) is Data : constant Object_Array_Access := new Object_Array (1 .. Into.Columns); begin if Into.Data = null then Into.Data := new Dataset_Array (1 .. 10); elsif Into.Count >= Into.Data'Last then declare -- Sun's Java ArrayList use a 2/3 grow factor. -- Python's array use 8/9. Grow : constant Positive := (Into.Count * 2) / 3; Set : constant Dataset_Array_Access := new Dataset_Array (1 .. Grow); begin Set (Into.Data'Range) := Into.Data.all; Free (Into.Data); Into.Data := Set; end; end if; Into.Count := Into.Count + 1; Into.Data (Into.Count) := Data; Fill (Data.all); end Append; -- ------------------------------ -- Add a column to the dataset. If the position is not specified, -- the column count is incremented and the name associated with the last column. -- Raises Invalid_State exception if the dataset contains some rows, -- ------------------------------ procedure Add_Column (Into : in out Dataset; Name : in String; Pos : in Natural := 0) is Col : Positive; begin if Into.Count /= 0 then raise Invalid_State with "The dataset contains some rows."; end if; if Pos = 0 then Col := Into.Columns + 1; else Col := Pos; end if; Into.Map.Insert (Name, Col); if Into.Columns < Col then Into.Columns := Col; end if; end Add_Column; -- ------------------------------ -- Clear the content of the dataset. -- ------------------------------ procedure Clear (Set : in out Dataset) is begin for I in 1 .. Set.Count loop Free (Set.Data (I)); end loop; Set.Count := 0; Set.Current_Pos := 0; Set.Current.Data := null; end Clear; -- ------------------------------ -- Get the value identified by the name. -- If the name cannot be found, the method should return the Null object. -- ------------------------------ overriding function Get_Value (From : in Row; Name : in String) return Util.Beans.Objects.Object is Pos : constant Dataset_Map.Cursor := From.Map.Find (Name); begin if From.Data /= null and then Dataset_Map.Has_Element (Pos) then return From.Data (Dataset_Map.Element (Pos)); else return Null_Object; end if; end Get_Value; -- ------------------------------ -- Set the value identified by the name. -- If the name cannot be found, the method should raise the No_Value -- exception. -- ------------------------------ overriding procedure Set_Value (From : in out Row; Name : in String; Value : in Util.Beans.Objects.Object) is Pos : constant Dataset_Map.Cursor := From.Map.Find (Name); begin if From.Data /= null and then Dataset_Map.Has_Element (Pos) then From.Data (Dataset_Map.Element (Pos)) := Value; end if; end Set_Value; -- ------------------------------ -- Initialize the dataset and the row bean instance. -- ------------------------------ overriding procedure Initialize (Set : in out Dataset) is begin Set.Row := To_Object (Value => Set.Current'Unchecked_Access, Storage => STATIC); Set.Current.Map := Set.Map'Unchecked_Access; end Initialize; -- ------------------------------ -- Release the dataset storage. -- ------------------------------ overriding procedure Finalize (Set : in out Dataset) is begin Set.Clear; Free (Set.Data); end Finalize; end Util.Beans.Objects.Datasets;
----------------------------------------------------------------------- -- Util.Beans.Objects.Datasets -- Datasets -- Copyright (C) 2013 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Unchecked_Deallocation; package body Util.Beans.Objects.Datasets is procedure Free is new Ada.Unchecked_Deallocation (Object => Object_Array, Name => Object_Array_Access); procedure Free is new Ada.Unchecked_Deallocation (Object => Dataset_Array, Name => Dataset_Array_Access); -- ------------------------------ -- Get the number of elements in the list. -- ------------------------------ overriding function Get_Count (From : in Dataset) return Natural is begin return From.Count; end Get_Count; -- ------------------------------ -- Set the current row index. Valid row indexes start at 1. -- ------------------------------ overriding procedure Set_Row_Index (From : in out Dataset; Index : in Natural) is begin From.Current_Pos := Index; From.Current.Data := From.Data (Index); end Set_Row_Index; -- ------------------------------ -- Get the element at the current row index. -- ------------------------------ overriding function Get_Row (From : in Dataset) return Util.Beans.Objects.Object is begin return From.Row; end Get_Row; -- ------------------------------ -- Get the value identified by the name. -- If the name cannot be found, the method should return the Null object. -- ------------------------------ overriding function Get_Value (From : in Dataset; Name : in String) return Util.Beans.Objects.Object is begin if Name = "count" then return Util.Beans.Objects.To_Object (From.Count); elsif Name = "rowIndex" then return Util.Beans.Objects.To_Object (From.Current_Pos); else return Util.Beans.Objects.Null_Object; end if; end Get_Value; -- ------------------------------ -- Append a row in the dataset and call the fill procedure to populate -- the row content. -- ------------------------------ procedure Append (Into : in out Dataset; Fill : not null access procedure (Data : in out Object_Array)) is Data : constant Object_Array_Access := new Object_Array (1 .. Into.Columns); begin if Into.Data = null then Into.Data := new Dataset_Array (1 .. 10); elsif Into.Count >= Into.Data'Length then declare -- Sun's Java ArrayList use a 2/3 grow factor. -- Python's array use 8/9. Grow : constant Positive := Into.Count + (Into.Count * 2) / 3; Set : constant Dataset_Array_Access := new Dataset_Array (1 .. Grow); begin Set (Into.Data'Range) := Into.Data.all; Free (Into.Data); Into.Data := Set; end; end if; Into.Count := Into.Count + 1; Into.Data (Into.Count) := Data; Fill (Data.all); end Append; -- ------------------------------ -- Add a column to the dataset. If the position is not specified, -- the column count is incremented and the name associated with the last column. -- Raises Invalid_State exception if the dataset contains some rows, -- ------------------------------ procedure Add_Column (Into : in out Dataset; Name : in String; Pos : in Natural := 0) is Col : Positive; begin if Into.Count /= 0 then raise Invalid_State with "The dataset contains some rows."; end if; if Pos = 0 then Col := Into.Columns + 1; else Col := Pos; end if; Into.Map.Insert (Name, Col); if Into.Columns < Col then Into.Columns := Col; end if; end Add_Column; -- ------------------------------ -- Clear the content of the dataset. -- ------------------------------ procedure Clear (Set : in out Dataset) is begin for I in 1 .. Set.Count loop Free (Set.Data (I)); end loop; Set.Count := 0; Set.Current_Pos := 0; Set.Current.Data := null; end Clear; -- ------------------------------ -- Get the value identified by the name. -- If the name cannot be found, the method should return the Null object. -- ------------------------------ overriding function Get_Value (From : in Row; Name : in String) return Util.Beans.Objects.Object is Pos : constant Dataset_Map.Cursor := From.Map.Find (Name); begin if From.Data /= null and then Dataset_Map.Has_Element (Pos) then return From.Data (Dataset_Map.Element (Pos)); else return Null_Object; end if; end Get_Value; -- ------------------------------ -- Set the value identified by the name. -- If the name cannot be found, the method should raise the No_Value -- exception. -- ------------------------------ overriding procedure Set_Value (From : in out Row; Name : in String; Value : in Util.Beans.Objects.Object) is Pos : constant Dataset_Map.Cursor := From.Map.Find (Name); begin if From.Data /= null and then Dataset_Map.Has_Element (Pos) then From.Data (Dataset_Map.Element (Pos)) := Value; end if; end Set_Value; -- ------------------------------ -- Initialize the dataset and the row bean instance. -- ------------------------------ overriding procedure Initialize (Set : in out Dataset) is begin Set.Row := To_Object (Value => Set.Current'Unchecked_Access, Storage => STATIC); Set.Current.Map := Set.Map'Unchecked_Access; end Initialize; -- ------------------------------ -- Release the dataset storage. -- ------------------------------ overriding procedure Finalize (Set : in out Dataset) is begin Set.Clear; Free (Set.Data); end Finalize; end Util.Beans.Objects.Datasets;
Fix growth factor of the dataset
Fix growth factor of the dataset
Ada
apache-2.0
stcarrez/ada-util,stcarrez/ada-util
7cde44a93080064a3bb6fdeca95a95bf9c326f14
src/sys/streams/util-streams-files.ads
src/sys/streams/util-streams-files.ads
----------------------------------------------------------------------- -- util-streams-files -- File Stream utilities -- Copyright (C) 2010, 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 Ada.Streams.Stream_IO; -- == File streams == -- The <tt>Util.Streams.Files</tt> package provides input and output streams that access -- files on top of the Ada <tt>Stream_IO</tt> standard package. package Util.Streams.Files is -- ----------------------- -- File stream -- ----------------------- -- The <b>File_Stream</b> is an output/input stream that reads or writes -- into a file-based stream. type File_Stream is limited new Output_Stream and Input_Stream with private; -- Open the file and initialize the stream for reading or writing. procedure Open (Stream : in out File_Stream; Mode : in Ada.Streams.Stream_IO.File_Mode; Name : in String := ""; Form : in String := ""); -- Create the file and initialize the stream for writing. procedure Create (Stream : in out File_Stream; Mode : in Ada.Streams.Stream_IO.File_Mode; Name : in String := ""; Form : in String := ""); -- Close the stream. overriding procedure Close (Stream : in out File_Stream); -- Write the buffer array to the output stream. overriding procedure Write (Stream : in out File_Stream; Buffer : in Ada.Streams.Stream_Element_Array); -- 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 File_Stream; Into : out Ada.Streams.Stream_Element_Array; Last : out Ada.Streams.Stream_Element_Offset); private type File_Stream is limited new Ada.Finalization.Limited_Controlled and Output_Stream and Input_Stream with record File : Ada.Streams.Stream_IO.File_Type; end record; -- Flush the stream and release the buffer. overriding procedure Finalize (Object : in out File_Stream); end Util.Streams.Files;
----------------------------------------------------------------------- -- util-streams-files -- File Stream utilities -- Copyright (C) 2010, 2013, 2015, 2017, 2018, 2019 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Finalization; with Ada.Streams.Stream_IO; -- == File streams == -- The `Util.Streams.Files` package provides input and output streams that access -- files on top of the Ada `Stream_IO` standard package. package Util.Streams.Files is -- ----------------------- -- File stream -- ----------------------- -- The <b>File_Stream</b> is an output/input stream that reads or writes -- into a file-based stream. type File_Stream is limited new Output_Stream and Input_Stream with private; -- Open the file and initialize the stream for reading or writing. procedure Open (Stream : in out File_Stream; Mode : in Ada.Streams.Stream_IO.File_Mode; Name : in String := ""; Form : in String := ""); -- Create the file and initialize the stream for writing. procedure Create (Stream : in out File_Stream; Mode : in Ada.Streams.Stream_IO.File_Mode; Name : in String := ""; Form : in String := ""); -- Close the stream. overriding procedure Close (Stream : in out File_Stream); -- Write the buffer array to the output stream. overriding procedure Write (Stream : in out File_Stream; Buffer : in Ada.Streams.Stream_Element_Array); -- 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 File_Stream; Into : out Ada.Streams.Stream_Element_Array; Last : out Ada.Streams.Stream_Element_Offset); private type File_Stream is limited new Ada.Finalization.Limited_Controlled and Output_Stream and Input_Stream with record File : Ada.Streams.Stream_IO.File_Type; end record; -- Flush the stream and release the buffer. overriding procedure Finalize (Object : in out File_Stream); end Util.Streams.Files;
Fix the stream documentation
Fix the stream documentation
Ada
apache-2.0
stcarrez/ada-util,stcarrez/ada-util
f2048d0b7a2a8c7602f6d519416e768b5682329a
ARM/Nordic/drivers/nrf51-gpio.adb
ARM/Nordic/drivers/nrf51-gpio.adb
------------------------------------------------------------------------------ -- -- -- Copyright (C) 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. -- -- -- ------------------------------------------------------------------------------ with NRF51_SVD.GPIO; use NRF51_SVD.GPIO; package body nRF51.GPIO is overriding function Mode (This : GPIO_Point) return HAL.GPIO.GPIO_Mode is CNF : PIN_CNF_Register renames GPIO_Periph.PIN_CNF (This.Pin); begin case CNF.DIR is when Input => return HAL.GPIO.Input; when Output => return HAL.GPIO.Output; end case; end Mode; -------------- -- Set_Mode -- -------------- overriding function Set_Mode (This : in out GPIO_Point; Mode : HAL.GPIO.GPIO_Config_Mode) return Boolean is CNF : PIN_CNF_Register renames GPIO_Periph.PIN_CNF (This.Pin); begin CNF.DIR := (case Mode is when HAL.GPIO.Input => Input, when HAL.GPIO.Output => Output); return True; end Set_Mode; --------- -- Set -- --------- overriding function Set (This : GPIO_Point) return Boolean is begin return GPIO_Periph.IN_k.Arr (This.Pin) = High; end Set; ------------------- -- Pull_Resistor -- ------------------- overriding function Pull_Resistor (This : GPIO_Point) return HAL.GPIO.GPIO_Pull_Resistor is begin case GPIO_Periph.PIN_CNF (This.Pin).PULL is when Disabled => return HAL.GPIO.Floating; when Pulldown => return HAL.GPIO.Pull_Down; when Pullup => return HAL.GPIO.Pull_Up; end case; end Pull_Resistor; ----------------------- -- Set_Pull_Resistor -- ----------------------- overriding function Set_Pull_Resistor (This : in out GPIO_Point; Pull : HAL.GPIO.GPIO_Pull_Resistor) return Boolean is begin GPIO_Periph.PIN_CNF (This.Pin).PULL := (case Pull is when HAL.GPIO.Floating => Disabled, when HAL.GPIO.Pull_Down => Pulldown, when HAL.GPIO.Pull_Up => Pullup); return True; end Set_Pull_Resistor; --------- -- Set -- --------- overriding procedure Set (This : in out GPIO_Point) is begin GPIO_Periph.OUT_k.Arr (This.Pin) := High; end Set; ----------- -- Clear -- ----------- overriding procedure Clear (This : in out GPIO_Point) is begin GPIO_Periph.OUT_k.Arr (This.Pin) := Low; end Clear; ------------ -- Toggle -- ------------ overriding procedure Toggle (This : in out GPIO_Point) is begin if This.Set then This.Clear; else This.Set; end if; end Toggle; ------------------ -- Configure_IO -- ------------------ procedure Configure_IO (This : GPIO_Point; Config : GPIO_Configuration) is CNF : PIN_CNF_Register renames GPIO_Periph.PIN_CNF (This.Pin); begin CNF.DIR := (case Config.Mode is when Mode_In => Input, when Mode_Out => Output); CNF.INPUT := (case Config.Input_Buffer is when Input_Buffer_Connect => Connect, when Input_Buffer_Disconnect => Disconnect); CNF.PULL := (case Config.Resistors is when No_Pull => Disabled, when Pull_Up => Pullup, when Pull_Down => Pulldown); CNF.DRIVE := (case Config.Drive is when Drive_S0S1 => S0S1, when Drive_H0S1 => H0S1, when Drive_S0H1 => S0H1, when Drive_H0H1 => H0H1, when Drive_D0S1 => D0S1, when Drive_D0H1 => D0H1, when Drive_S0D1 => S0D1, when Drive_H0D1 => H0D1); CNF.SENSE := (case Config.Sense is when Sense_Disabled => Disabled, when Sense_For_High_Level => High, when Sense_For_Low_Level => Low); end Configure_IO; end nRF51.GPIO;
------------------------------------------------------------------------------ -- -- -- Copyright (C) 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. -- -- -- ------------------------------------------------------------------------------ with NRF51_SVD.GPIO; use NRF51_SVD.GPIO; package body nRF51.GPIO is overriding function Mode (This : GPIO_Point) return HAL.GPIO.GPIO_Mode is CNF : PIN_CNF_Register renames GPIO_Periph.PIN_CNF (This.Pin); begin case CNF.DIR is when Input => return HAL.GPIO.Input; when Output => return HAL.GPIO.Output; end case; end Mode; -------------- -- Set_Mode -- -------------- overriding function Set_Mode (This : in out GPIO_Point; Mode : HAL.GPIO.GPIO_Config_Mode) return Boolean is CNF : PIN_CNF_Register renames GPIO_Periph.PIN_CNF (This.Pin); begin CNF.DIR := (case Mode is when HAL.GPIO.Input => Input, when HAL.GPIO.Output => Output); CNF.INPUT := (case Mode is when HAL.GPIO.Input => Connect, when HAL.GPIO.Output => Disconnect); return True; end Set_Mode; --------- -- Set -- --------- overriding function Set (This : GPIO_Point) return Boolean is begin return GPIO_Periph.IN_k.Arr (This.Pin) = High; end Set; ------------------- -- Pull_Resistor -- ------------------- overriding function Pull_Resistor (This : GPIO_Point) return HAL.GPIO.GPIO_Pull_Resistor is begin case GPIO_Periph.PIN_CNF (This.Pin).PULL is when Disabled => return HAL.GPIO.Floating; when Pulldown => return HAL.GPIO.Pull_Down; when Pullup => return HAL.GPIO.Pull_Up; end case; end Pull_Resistor; ----------------------- -- Set_Pull_Resistor -- ----------------------- overriding function Set_Pull_Resistor (This : in out GPIO_Point; Pull : HAL.GPIO.GPIO_Pull_Resistor) return Boolean is begin GPIO_Periph.PIN_CNF (This.Pin).PULL := (case Pull is when HAL.GPIO.Floating => Disabled, when HAL.GPIO.Pull_Down => Pulldown, when HAL.GPIO.Pull_Up => Pullup); return True; end Set_Pull_Resistor; --------- -- Set -- --------- overriding procedure Set (This : in out GPIO_Point) is begin GPIO_Periph.OUT_k.Arr (This.Pin) := High; end Set; ----------- -- Clear -- ----------- overriding procedure Clear (This : in out GPIO_Point) is begin GPIO_Periph.OUT_k.Arr (This.Pin) := Low; end Clear; ------------ -- Toggle -- ------------ overriding procedure Toggle (This : in out GPIO_Point) is begin if This.Set then This.Clear; else This.Set; end if; end Toggle; ------------------ -- Configure_IO -- ------------------ procedure Configure_IO (This : GPIO_Point; Config : GPIO_Configuration) is CNF : PIN_CNF_Register renames GPIO_Periph.PIN_CNF (This.Pin); begin CNF.DIR := (case Config.Mode is when Mode_In => Input, when Mode_Out => Output); CNF.INPUT := (case Config.Input_Buffer is when Input_Buffer_Connect => Connect, when Input_Buffer_Disconnect => Disconnect); CNF.PULL := (case Config.Resistors is when No_Pull => Disabled, when Pull_Up => Pullup, when Pull_Down => Pulldown); CNF.DRIVE := (case Config.Drive is when Drive_S0S1 => S0S1, when Drive_H0S1 => H0S1, when Drive_S0H1 => S0H1, when Drive_H0H1 => H0H1, when Drive_D0S1 => D0S1, when Drive_D0H1 => D0H1, when Drive_S0D1 => S0D1, when Drive_H0D1 => H0D1); CNF.SENSE := (case Config.Sense is when Sense_Disabled => Disabled, when Sense_For_High_Level => High, when Sense_For_Low_Level => Low); end Configure_IO; end nRF51.GPIO;
Connect the input buffer when the point is set as input
nRF51.GPIO: Connect the input buffer when the point is set as input
Ada
bsd-3-clause
simonjwright/Ada_Drivers_Library,ellamosi/Ada_BMP_Library,AdaCore/Ada_Drivers_Library,Fabien-Chouteau/Ada_Drivers_Library,simonjwright/Ada_Drivers_Library,AdaCore/Ada_Drivers_Library,Fabien-Chouteau/Ada_Drivers_Library
07c9c2b8167d6cfc8da406cba3672d3691d28b02
regtests/security-openid-tests.adb
regtests/security-openid-tests.adb
----------------------------------------------------------------------- -- security-openid - Tests for OpenID -- 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 Util.Http.Clients.Mockups; with Util.Http.Clients.Files; with Util.Test_Caller; with Ada.Text_IO; package body Security.Openid.Tests is use Util.Tests; package Caller is new Util.Test_Caller (Test, "Security.Openid"); procedure Check_Discovery (T : in out Test; Name : in String; URI : in String); procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is begin Caller.Add_Test (Suite, "Test Security.OpenID.Discover", Test_Discovery'Access); Caller.Add_Test (Suite, "Test Security.OpenID.Verify_Signature", Test_Verify_Signature'Access); end Add_Tests; procedure Check_Discovery (T : in out Test; Name : in String; URI : in String) is pragma Unreferenced (URI, T); M : Manager; Dir : constant String := "regtests/files/discover/"; Path : constant String := Util.Tests.Get_Path (Dir); Result : End_Point; begin ASF.Clients.Files.Register; ASF.Clients.Files.Set_File (Path & Name & ".xrds"); M.Discover (Name => Name, Result => Result); Ada.Text_IO.Put_Line ("Result: " & To_String (Result)); end Check_Discovery; -- ------------------------------ -- Test Yadis discovery using static files -- ------------------------------ procedure Test_Discovery (T : in out Test) is begin Check_Discovery (T, "google", "https://www.google.com/accounts/o8/ud"); Check_Discovery (T, "yahoo", "https://open.login.yahooapis.com/openid/op/auth"); Check_Discovery (T, "claimid", ""); Check_Discovery (T, "livejournal", ""); Check_Discovery (T, "myopenid", ""); Check_Discovery (T, "myspace", ""); Check_Discovery (T, "orange", ""); Check_Discovery (T, "verisign", ""); Check_Discovery (T, "steamcommunity", ""); end Test_Discovery; -- ------------------------------ -- Test the OpenID verify signature process -- ------------------------------ procedure Test_Verify_Signature (T : in out Test) is Assoc : Association; Req : ASF.Requests.Mockup.Request; M : Manager; Result : Authentication; begin M.Return_To := To_Unbounded_String ("http://localhost/openId"); -- Below is a part of the authentication process on Google OpenId. -- In theory, you cannot use the following information to authenticate again... Assoc.Session_Type := To_Unbounded_String ("no-encryption"); Assoc.Assoc_Type := To_Unbounded_String ("HMAC-SHA1"); Assoc.Assoc_Handle := To_Unbounded_String ("AOQobUdTfNDRSgJLi_0mQQnCCstOsefQadOiW9LNSp4JFO815iHCHsRk"); Assoc.Mac_Key := To_Unbounded_String ("NGFpR6vWfe7O8YIhhnXQMjL0goI="); Req.Set_Parameter ("openid.ns", "http://specs.openid.net/auth/2.0"); Req.Set_Parameter ("openid.mode", "id_res"); Req.Set_Parameter ("openid.op_endpoint", "https://www.google.com/accounts/o8/ud"); Req.Set_Parameter ("openid.response_nonce", "2011-04-26T20:08:22ZJ_neiVqR0e1wZw"); Req.Set_Parameter ("openid.return_to", "http://localhost/openId"); Req.Set_Parameter ("openid.assoc_handle", "AOQobUdTfNDRSgJLi_0mQQnCCstOsefQadOiW9LNSp4JFO815iHCHsRk"); Req.Set_Parameter ("openid.signed", "op_endpoint,claimed_id,identity,return_to,response_nonce,assoc_handle,ns.ext1,ext1.mode,ext1.type.firstname,ext1.value.firstname,ext1.type.email,ext1.value.email,ext1.type.language,ext1.value.language,ext1.type.lastname,ext1.value.lastname"); Req.Set_Parameter ("openid.sig", "pV8cmScjrmgKvFn2F6Wxh/qBiIE="); Req.Set_Parameter ("openid.identity", "https://www.google.com/accounts/o8/id?id=AItOawm4O6C695XlWrS7MUWC-_V_R2zC-Ol993E"); Req.Set_Parameter ("openid.claimed_id", "https://www.google.com/accounts/o8/id?id=AItOawm4O6C695XlWrS7MUWC-_V_R2zC-Ol993E"); Req.Set_Parameter ("openid.ns.ext1", "http://openid.net/srv/ax/1.0"); Req.Set_Parameter ("openid.ext1.mode", "fetch_response"); Req.Set_Parameter ("openid.ext1.type.firstname", "http://axschema.org/namePerson/first"); Req.Set_Parameter ("openid.ext1.value.firstname", "Stephane"); Req.Set_Parameter ("openid.ext1.type.email", "http://axschema.org/contact/email"); Req.Set_Parameter ("openid.ext1.value.email", "[email protected]"); Req.Set_Parameter ("openid.ext1.type.language", "http://axschema.org/pref/language"); Req.Set_Parameter ("openid.ext1.value.language", "fr"); Req.Set_Parameter ("openid.ext1.type.lastname", "http://axschema.org/namePerson/last"); Req.Set_Parameter ("openid.ext1.value.lastname", "Carrez"); M.Verify (Assoc, Req, Result); -- If the verification is succeeds, the signature is correct, we should be authenticated. T.Assert (Get_Status (Result) = AUTHENTICATED, "Authentication status is not authenticated"); Assert_Equals (T, "[email protected]", Get_Email (Result), "Invalid email"); end Test_Verify_Signature; end Security.Openid.Tests;
----------------------------------------------------------------------- -- security-openid - Tests for OpenID -- 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 Util.Http.Mockups; with Util.Http.Clients.Mockups; with Util.Test_Caller; with Ada.Text_IO; package body Security.Openid.Tests is use Util.Tests; package Caller is new Util.Test_Caller (Test, "Security.Openid"); procedure Check_Discovery (T : in out Test; Name : in String; URI : in String); procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is begin Caller.Add_Test (Suite, "Test Security.OpenID.Discover", Test_Discovery'Access); Caller.Add_Test (Suite, "Test Security.OpenID.Verify_Signature", Test_Verify_Signature'Access); end Add_Tests; procedure Check_Discovery (T : in out Test; Name : in String; URI : in String) is pragma Unreferenced (URI, T); M : Manager; Dir : constant String := "regtests/files/discover/"; Path : constant String := Util.Tests.Get_Path (Dir); Result : End_Point; begin Util.Http.Clients.Mockups.Register; Util.Http.Clients.Mockups.Set_File (Path & Name & ".xrds"); M.Discover (Name => Name, Result => Result); Ada.Text_IO.Put_Line ("Result: " & To_String (Result)); end Check_Discovery; -- ------------------------------ -- Test Yadis discovery using static files -- ------------------------------ procedure Test_Discovery (T : in out Test) is begin Check_Discovery (T, "google", "https://www.google.com/accounts/o8/ud"); Check_Discovery (T, "yahoo", "https://open.login.yahooapis.com/openid/op/auth"); Check_Discovery (T, "claimid", ""); Check_Discovery (T, "livejournal", ""); Check_Discovery (T, "myopenid", ""); Check_Discovery (T, "myspace", ""); Check_Discovery (T, "orange", ""); Check_Discovery (T, "verisign", ""); Check_Discovery (T, "steamcommunity", ""); end Test_Discovery; -- ------------------------------ -- Test the OpenID verify signature process -- ------------------------------ procedure Test_Verify_Signature (T : in out Test) is Assoc : Association; Req : Util.Http.Mockups.Mockup_Request; M : Manager; Result : Authentication; begin M.Return_To := To_Unbounded_String ("http://localhost/openId"); -- Below is a part of the authentication process on Google OpenId. -- In theory, you cannot use the following information to authenticate again... Assoc.Session_Type := To_Unbounded_String ("no-encryption"); Assoc.Assoc_Type := To_Unbounded_String ("HMAC-SHA1"); Assoc.Assoc_Handle := To_Unbounded_String ("AOQobUdTfNDRSgJLi_0mQQnCCstOsefQadOiW9LNSp4JFO815iHCHsRk"); Assoc.Mac_Key := To_Unbounded_String ("NGFpR6vWfe7O8YIhhnXQMjL0goI="); Req.Set_Parameter ("openid.ns", "http://specs.openid.net/auth/2.0"); Req.Set_Parameter ("openid.mode", "id_res"); Req.Set_Parameter ("openid.op_endpoint", "https://www.google.com/accounts/o8/ud"); Req.Set_Parameter ("openid.response_nonce", "2011-04-26T20:08:22ZJ_neiVqR0e1wZw"); Req.Set_Parameter ("openid.return_to", "http://localhost/openId"); Req.Set_Parameter ("openid.assoc_handle", "AOQobUdTfNDRSgJLi_0mQQnCCstOsefQadOiW9LNSp4JFO815iHCHsRk"); Req.Set_Parameter ("openid.signed", "op_endpoint,claimed_id,identity,return_to,response_nonce,assoc_handle,ns.ext1,ext1.mode,ext1.type.firstname,ext1.value.firstname,ext1.type.email,ext1.value.email,ext1.type.language,ext1.value.language,ext1.type.lastname,ext1.value.lastname"); Req.Set_Parameter ("openid.sig", "pV8cmScjrmgKvFn2F6Wxh/qBiIE="); Req.Set_Parameter ("openid.identity", "https://www.google.com/accounts/o8/id?id=AItOawm4O6C695XlWrS7MUWC-_V_R2zC-Ol993E"); Req.Set_Parameter ("openid.claimed_id", "https://www.google.com/accounts/o8/id?id=AItOawm4O6C695XlWrS7MUWC-_V_R2zC-Ol993E"); Req.Set_Parameter ("openid.ns.ext1", "http://openid.net/srv/ax/1.0"); Req.Set_Parameter ("openid.ext1.mode", "fetch_response"); Req.Set_Parameter ("openid.ext1.type.firstname", "http://axschema.org/namePerson/first"); Req.Set_Parameter ("openid.ext1.value.firstname", "Stephane"); Req.Set_Parameter ("openid.ext1.type.email", "http://axschema.org/contact/email"); Req.Set_Parameter ("openid.ext1.value.email", "[email protected]"); Req.Set_Parameter ("openid.ext1.type.language", "http://axschema.org/pref/language"); Req.Set_Parameter ("openid.ext1.value.language", "fr"); Req.Set_Parameter ("openid.ext1.type.lastname", "http://axschema.org/namePerson/last"); Req.Set_Parameter ("openid.ext1.value.lastname", "Carrez"); M.Verify (Assoc, Req, Result); -- If the verification is succeeds, the signature is correct, we should be authenticated. T.Assert (Get_Status (Result) = AUTHENTICATED, "Authentication status is not authenticated"); Assert_Equals (T, "[email protected]", Get_Email (Result), "Invalid email"); end Test_Verify_Signature; end Security.Openid.Tests;
Use the new util HTTP mockups
Use the new util HTTP mockups
Ada
apache-2.0
Letractively/ada-security
9ab7ea46d7734188195a9a04d9e74567101c4eb0
regtests/util-processes-tests.adb
regtests/util-processes-tests.adb
----------------------------------------------------------------------- -- util-processes-tests - Test for processes -- Copyright (C) 2011, 2012, 2016 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Log.Loggers; with Util.Test_Caller; with Util.Files; with Util.Streams.Pipes; with Util.Streams.Buffered; with Util.Streams.Texts; with Util.Systems.Os; package body Util.Processes.Tests is use Util.Log; -- The logger Log : constant Loggers.Logger := Loggers.Create ("Util.Processes.Tests"); package Caller is new Util.Test_Caller (Test, "Processes"); procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is begin Caller.Add_Test (Suite, "Test Util.Processes.Is_Running", Test_No_Process'Access); Caller.Add_Test (Suite, "Test Util.Processes.Spawn/Wait/Get_Exit_Status", Test_Spawn'Access); Caller.Add_Test (Suite, "Test Util.Processes.Spawn(READ pipe)", Test_Output_Pipe'Access); Caller.Add_Test (Suite, "Test Util.Processes.Spawn(WRITE pipe)", Test_Input_Pipe'Access); Caller.Add_Test (Suite, "Test Util.Processes.Spawn/Shell(WRITE pipe)", Test_Shell_Splitting_Pipe'Access); pragma Warnings (Off); if Util.Systems.Os.Directory_Separator /= '\' then Caller.Add_Test (Suite, "Test Util.Processes.Spawn(OUTPUT redirect)", Test_Output_Redirect'Access); end if; pragma Warnings (On); Caller.Add_Test (Suite, "Test Util.Streams.Pipes.Open/Read/Close (Multi spawn)", Test_Multi_Spawn'Access); end Add_Tests; -- ------------------------------ -- Tests when the process is not launched -- ------------------------------ procedure Test_No_Process (T : in out Test) is P : Process; begin T.Assert (not P.Is_Running, "Process should not be running"); T.Assert (P.Get_Pid < 0, "Invalid process id"); end Test_No_Process; -- ------------------------------ -- Test executing a process -- ------------------------------ procedure Test_Spawn (T : in out Test) is P : Process; begin -- Launch the test process => exit code 2 P.Spawn ("bin/util_test_process"); T.Assert (P.Is_Running, "Process is running"); P.Wait; T.Assert (not P.Is_Running, "Process has stopped"); T.Assert (P.Get_Pid > 0, "Invalid process id"); Util.Tests.Assert_Equals (T, 2, P.Get_Exit_Status, "Invalid exit status"); -- Launch the test process => exit code 0 P.Spawn ("bin/util_test_process 0 write b c d e f"); T.Assert (P.Is_Running, "Process is running"); P.Wait; T.Assert (not P.Is_Running, "Process has stopped"); T.Assert (P.Get_Pid > 0, "Invalid process id"); Util.Tests.Assert_Equals (T, 0, P.Get_Exit_Status, "Invalid exit status"); end Test_Spawn; -- ------------------------------ -- Test output pipe redirection: read the process standard output -- ------------------------------ procedure Test_Output_Pipe (T : in out Test) is P : aliased Util.Streams.Pipes.Pipe_Stream; begin P.Open ("bin/util_test_process 0 write b c d e f test_marker"); declare Buffer : Util.Streams.Buffered.Input_Buffer_Stream; Content : Ada.Strings.Unbounded.Unbounded_String; begin Buffer.Initialize (P'Unchecked_Access, 19); Buffer.Read (Content); P.Close; Util.Tests.Assert_Matches (T, "b\s+c\s+d\s+e\s+f\s+test_marker\s+", Content, "Invalid content"); end; T.Assert (not P.Is_Running, "Process has stopped"); Util.Tests.Assert_Equals (T, 0, P.Get_Exit_Status, "Invalid exit status"); end Test_Output_Pipe; -- ------------------------------ -- Test shell splitting. -- ------------------------------ procedure Test_Shell_Splitting_Pipe (T : in out Test) is P : aliased Util.Streams.Pipes.Pipe_Stream; begin P.Open ("bin/util_test_process 0 write 'b c d e f' test_marker"); declare Buffer : Util.Streams.Buffered.Input_Buffer_Stream; Content : Ada.Strings.Unbounded.Unbounded_String; begin Buffer.Initialize (P'Unchecked_Access, 19); Buffer.Read (Content); P.Close; Util.Tests.Assert_Matches (T, "b c d e f\s+test_marker\s+", Content, "Invalid content"); end; T.Assert (not P.Is_Running, "Process has stopped"); Util.Tests.Assert_Equals (T, 0, P.Get_Exit_Status, "Invalid exit status"); end Test_Shell_Splitting_Pipe; -- ------------------------------ -- Test input pipe redirection: write the process standard input -- At the same time, read the process standard output. -- ------------------------------ procedure Test_Input_Pipe (T : in out Test) is P : aliased Util.Streams.Pipes.Pipe_Stream; begin P.Open ("bin/util_test_process 0 read -", READ_WRITE); declare Buffer : Util.Streams.Buffered.Input_Buffer_Stream; Content : Ada.Strings.Unbounded.Unbounded_String; Print : Util.Streams.Texts.Print_Stream; begin -- Write on the process input stream. Print.Initialize (P'Unchecked_Access); Print.Write ("Write test on the input pipe"); Print.Close; -- Read the output. Buffer.Initialize (P'Unchecked_Access, 19); Buffer.Read (Content); -- Wait for the process to finish. P.Close; Util.Tests.Assert_Matches (T, "Write test on the input pipe-\s", Content, "Invalid content"); end; T.Assert (not P.Is_Running, "Process has stopped"); Util.Tests.Assert_Equals (T, 0, P.Get_Exit_Status, "Invalid exit status"); end Test_Input_Pipe; -- ------------------------------ -- Test launching several processes through pipes in several threads. -- ------------------------------ procedure Test_Multi_Spawn (T : in out Test) is Task_Count : constant Natural := 8; Count_By_Task : constant Natural := 10; type State_Array is array (1 .. Task_Count) of Boolean; States : State_Array; begin declare task type Worker is entry Start (Count : in Natural); entry Result (Status : out Boolean); end Worker; task body Worker is Cnt : Natural; State : Boolean := True; begin accept Start (Count : in Natural) do Cnt := Count; end Start; declare type Pipe_Array is array (1 .. Cnt) of aliased Util.Streams.Pipes.Pipe_Stream; Pipes : Pipe_Array; begin -- Launch the processes. -- They will print their arguments on stdout, one by one on each line. -- The expected exit status is the first argument. for I in 1 .. Cnt loop Pipes (I).Open ("bin/util_test_process 0 write b c d e f test_marker"); end loop; -- Read their output for I in 1 .. Cnt loop declare Buffer : Util.Streams.Buffered.Input_Buffer_Stream; Content : Ada.Strings.Unbounded.Unbounded_String; begin Buffer.Initialize (Pipes (I)'Unchecked_Access, 19); Buffer.Read (Content); Pipes (I).Close; -- Check status and output. State := State and Pipes (I).Get_Exit_Status = 0; State := State and Ada.Strings.Unbounded.Index (Content, "test_marker") > 0; end; end loop; exception when E : others => Log.Error ("Exception raised", E); State := False; end; accept Result (Status : out Boolean) do Status := State; end Result; end Worker; type Worker_Array is array (1 .. Task_Count) of Worker; Tasks : Worker_Array; begin for I in Tasks'Range loop Tasks (I).Start (Count_By_Task); end loop; -- Get the results (do not raise any assertion here because we have to call -- 'Result' to ensure the thread terminates. for I in Tasks'Range loop Tasks (I).Result (States (I)); end loop; -- Leaving the Worker task scope means we are waiting for our tasks to finish. end; for I in States'Range loop T.Assert (States (I), "Task " & Natural'Image (I) & " failed"); end loop; end Test_Multi_Spawn; -- ------------------------------ -- Test output file redirection. -- ------------------------------ procedure Test_Output_Redirect (T : in out Test) is P : Process; Path : constant String := Util.Tests.Get_Test_Path ("proc-output.txt"); Content : Ada.Strings.Unbounded.Unbounded_String; begin Util.Processes.Set_Output_Stream (P, Path); Util.Processes.Spawn (P, "bin/util_test_process 0 write b c d e f test_marker"); Util.Processes.Wait (P); T.Assert (not P.Is_Running, "Process has stopped"); Util.Tests.Assert_Equals (T, 0, P.Get_Exit_Status, "Process failed"); Util.Files.Read_File (Path, Content); Util.Tests.Assert_Matches (T, ".*test_marker", Content, "Invalid content"); Util.Processes.Set_Output_Stream (P, Path, True); Util.Processes.Spawn (P, "bin/util_test_process 0 write appended_text"); Util.Processes.Wait (P); Content := Ada.Strings.Unbounded.Null_Unbounded_String; Util.Files.Read_File (Path, Content); Util.Tests.Assert_Matches (T, ".*appended_text", Content, "Invalid content"); Util.Tests.Assert_Matches (T, ".*test_marker.*", Content, "Invalid content"); end Test_Output_Redirect; end Util.Processes.Tests;
----------------------------------------------------------------------- -- util-processes-tests - Test for processes -- Copyright (C) 2011, 2012, 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 Util.Log.Loggers; with Util.Test_Caller; with Util.Files; with Util.Strings.Vectors; with Util.Streams.Pipes; with Util.Streams.Buffered; with Util.Streams.Texts; with Util.Systems.Os; with Util.Processes.Tools; package body Util.Processes.Tests is -- The logger Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("Util.Processes.Tests"); package Caller is new Util.Test_Caller (Test, "Processes"); procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is begin Caller.Add_Test (Suite, "Test Util.Processes.Is_Running", Test_No_Process'Access); Caller.Add_Test (Suite, "Test Util.Processes.Spawn/Wait/Get_Exit_Status", Test_Spawn'Access); Caller.Add_Test (Suite, "Test Util.Processes.Spawn(READ pipe)", Test_Output_Pipe'Access); Caller.Add_Test (Suite, "Test Util.Processes.Spawn(WRITE pipe)", Test_Input_Pipe'Access); Caller.Add_Test (Suite, "Test Util.Processes.Spawn/Shell(WRITE pipe)", Test_Shell_Splitting_Pipe'Access); pragma Warnings (Off); if Util.Systems.Os.Directory_Separator /= '\' then Caller.Add_Test (Suite, "Test Util.Processes.Spawn(OUTPUT redirect)", Test_Output_Redirect'Access); end if; pragma Warnings (On); Caller.Add_Test (Suite, "Test Util.Streams.Pipes.Open/Read/Close (Multi spawn)", Test_Multi_Spawn'Access); Caller.Add_Test (Suite, "Test Util.Processes.Tools.Execute", Test_Tools_Execute'Access); end Add_Tests; -- ------------------------------ -- Tests when the process is not launched -- ------------------------------ procedure Test_No_Process (T : in out Test) is P : Process; begin T.Assert (not P.Is_Running, "Process should not be running"); T.Assert (P.Get_Pid < 0, "Invalid process id"); end Test_No_Process; -- ------------------------------ -- Test executing a process -- ------------------------------ procedure Test_Spawn (T : in out Test) is P : Process; begin -- Launch the test process => exit code 2 P.Spawn ("bin/util_test_process"); T.Assert (P.Is_Running, "Process is running"); P.Wait; T.Assert (not P.Is_Running, "Process has stopped"); T.Assert (P.Get_Pid > 0, "Invalid process id"); Util.Tests.Assert_Equals (T, 2, P.Get_Exit_Status, "Invalid exit status"); -- Launch the test process => exit code 0 P.Spawn ("bin/util_test_process 0 write b c d e f"); T.Assert (P.Is_Running, "Process is running"); P.Wait; T.Assert (not P.Is_Running, "Process has stopped"); T.Assert (P.Get_Pid > 0, "Invalid process id"); Util.Tests.Assert_Equals (T, 0, P.Get_Exit_Status, "Invalid exit status"); end Test_Spawn; -- ------------------------------ -- Test output pipe redirection: read the process standard output -- ------------------------------ procedure Test_Output_Pipe (T : in out Test) is P : aliased Util.Streams.Pipes.Pipe_Stream; begin P.Open ("bin/util_test_process 0 write b c d e f test_marker"); declare Buffer : Util.Streams.Buffered.Input_Buffer_Stream; Content : Ada.Strings.Unbounded.Unbounded_String; begin Buffer.Initialize (P'Unchecked_Access, 19); Buffer.Read (Content); P.Close; Util.Tests.Assert_Matches (T, "b\s+c\s+d\s+e\s+f\s+test_marker\s+", Content, "Invalid content"); end; T.Assert (not P.Is_Running, "Process has stopped"); Util.Tests.Assert_Equals (T, 0, P.Get_Exit_Status, "Invalid exit status"); end Test_Output_Pipe; -- ------------------------------ -- Test shell splitting. -- ------------------------------ procedure Test_Shell_Splitting_Pipe (T : in out Test) is P : aliased Util.Streams.Pipes.Pipe_Stream; begin P.Open ("bin/util_test_process 0 write 'b c d e f' test_marker"); declare Buffer : Util.Streams.Buffered.Input_Buffer_Stream; Content : Ada.Strings.Unbounded.Unbounded_String; begin Buffer.Initialize (P'Unchecked_Access, 19); Buffer.Read (Content); P.Close; Util.Tests.Assert_Matches (T, "b c d e f\s+test_marker\s+", Content, "Invalid content"); end; T.Assert (not P.Is_Running, "Process has stopped"); Util.Tests.Assert_Equals (T, 0, P.Get_Exit_Status, "Invalid exit status"); end Test_Shell_Splitting_Pipe; -- ------------------------------ -- Test input pipe redirection: write the process standard input -- At the same time, read the process standard output. -- ------------------------------ procedure Test_Input_Pipe (T : in out Test) is P : aliased Util.Streams.Pipes.Pipe_Stream; begin P.Open ("bin/util_test_process 0 read -", READ_WRITE); declare Buffer : Util.Streams.Buffered.Input_Buffer_Stream; Content : Ada.Strings.Unbounded.Unbounded_String; Print : Util.Streams.Texts.Print_Stream; begin -- Write on the process input stream. Print.Initialize (P'Unchecked_Access); Print.Write ("Write test on the input pipe"); Print.Close; -- Read the output. Buffer.Initialize (P'Unchecked_Access, 19); Buffer.Read (Content); -- Wait for the process to finish. P.Close; Util.Tests.Assert_Matches (T, "Write test on the input pipe-\s", Content, "Invalid content"); end; T.Assert (not P.Is_Running, "Process has stopped"); Util.Tests.Assert_Equals (T, 0, P.Get_Exit_Status, "Invalid exit status"); end Test_Input_Pipe; -- ------------------------------ -- Test launching several processes through pipes in several threads. -- ------------------------------ procedure Test_Multi_Spawn (T : in out Test) is Task_Count : constant Natural := 8; Count_By_Task : constant Natural := 10; type State_Array is array (1 .. Task_Count) of Boolean; States : State_Array; begin declare task type Worker is entry Start (Count : in Natural); entry Result (Status : out Boolean); end Worker; task body Worker is Cnt : Natural; State : Boolean := True; begin accept Start (Count : in Natural) do Cnt := Count; end Start; declare type Pipe_Array is array (1 .. Cnt) of aliased Util.Streams.Pipes.Pipe_Stream; Pipes : Pipe_Array; begin -- Launch the processes. -- They will print their arguments on stdout, one by one on each line. -- The expected exit status is the first argument. for I in 1 .. Cnt loop Pipes (I).Open ("bin/util_test_process 0 write b c d e f test_marker"); end loop; -- Read their output for I in 1 .. Cnt loop declare Buffer : Util.Streams.Buffered.Input_Buffer_Stream; Content : Ada.Strings.Unbounded.Unbounded_String; begin Buffer.Initialize (Pipes (I)'Unchecked_Access, 19); Buffer.Read (Content); Pipes (I).Close; -- Check status and output. State := State and Pipes (I).Get_Exit_Status = 0; State := State and Ada.Strings.Unbounded.Index (Content, "test_marker") > 0; end; end loop; exception when E : others => Log.Error ("Exception raised", E); State := False; end; accept Result (Status : out Boolean) do Status := State; end Result; end Worker; type Worker_Array is array (1 .. Task_Count) of Worker; Tasks : Worker_Array; begin for I in Tasks'Range loop Tasks (I).Start (Count_By_Task); end loop; -- Get the results (do not raise any assertion here because we have to call -- 'Result' to ensure the thread terminates. for I in Tasks'Range loop Tasks (I).Result (States (I)); end loop; -- Leaving the Worker task scope means we are waiting for our tasks to finish. end; for I in States'Range loop T.Assert (States (I), "Task " & Natural'Image (I) & " failed"); end loop; end Test_Multi_Spawn; -- ------------------------------ -- Test output file redirection. -- ------------------------------ procedure Test_Output_Redirect (T : in out Test) is P : Process; Path : constant String := Util.Tests.Get_Test_Path ("proc-output.txt"); Content : Ada.Strings.Unbounded.Unbounded_String; begin Util.Processes.Set_Output_Stream (P, Path); Util.Processes.Spawn (P, "bin/util_test_process 0 write b c d e f test_marker"); Util.Processes.Wait (P); T.Assert (not P.Is_Running, "Process has stopped"); Util.Tests.Assert_Equals (T, 0, P.Get_Exit_Status, "Process failed"); Util.Files.Read_File (Path, Content); Util.Tests.Assert_Matches (T, ".*test_marker", Content, "Invalid content"); Util.Processes.Set_Output_Stream (P, Path, True); Util.Processes.Spawn (P, "bin/util_test_process 0 write appended_text"); Util.Processes.Wait (P); Content := Ada.Strings.Unbounded.Null_Unbounded_String; Util.Files.Read_File (Path, Content); Util.Tests.Assert_Matches (T, ".*appended_text", Content, "Invalid content"); Util.Tests.Assert_Matches (T, ".*test_marker.*", Content, "Invalid content"); end Test_Output_Redirect; -- ------------------------------ -- Test the Tools.Execute operation. -- ------------------------------ procedure Test_Tools_Execute (T : in out Test) is List : Util.Strings.Vectors.Vector; Status : Integer; begin Tools.Execute (Command => "bin/util_test_process 23 write 'b c d e f' test_marker", Output => List, Status => Status); Util.Tests.Assert_Equals (T, 23, Status, "Invalid exit status"); Util.Tests.Assert_Equals (T, 2, Integer (List.Length), "Invalid output collected by Execute"); Util.Tests.Assert_Equals (T, "b c d e f", List.Element (1), ""); Util.Tests.Assert_Equals (T, "test_marker", List.Element (2), ""); end Test_Tools_Execute; end Util.Processes.Tests;
Implement the Test_Execute procedure and register the new test
Implement the Test_Execute procedure and register the new test
Ada
apache-2.0
stcarrez/ada-util,stcarrez/ada-util
04a9db626ddffd706e8b235f5fe656189d627f75
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 MAT.Types; with MAT.Memory.Targets; with MAT.Symbols.Targets; with MAT.Readers; with MAT.Consoles; 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; Console : MAT.Consoles.Console_Access; 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;
----------------------------------------------------------------------- -- 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 MAT.Types; with MAT.Memory.Targets; with MAT.Symbols.Targets; with MAT.Readers; with MAT.Consoles; package MAT.Targets is type Target_Process_Type is tagged limited record Pid : MAT.Types.Target_Process_Ref; Memory : MAT.Memory.Targets.Target_Memory; 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 record Pid : MAT.Types.Target_Process_Ref; Memory : MAT.Memory.Targets.Target_Memory; Symbols : MAT.Symbols.Targets.Target_Symbols; Console : MAT.Consoles.Console_Access; 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;
Declare the Target_Process_Type type to hold everything about a process
Declare the Target_Process_Type type to hold everything about a process
Ada
apache-2.0
stcarrez/mat,stcarrez/mat,stcarrez/mat
c169382432ef306562a361b7bce1e8f09b336908
src/ado.ads
src/ado.ads
----------------------------------------------------------------------- -- ADO Databases -- Database Objects -- Copyright (C) 2009, 2010, 2011, 2012, 2015 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Strings.Unbounded; with Ada.Streams; with Ada.Calendar; with Util.Refs; package ADO is type Int64 is range -2**63 .. 2**63 - 1; for Int64'Size use 64; type Unsigned64 is mod 2**64; for Unsigned64'Size use 64; DEFAULT_TIME : constant Ada.Calendar.Time; -- ------------------------------ -- Database Identifier -- ------------------------------ -- type Identifier is range -2**47 .. 2**47 - 1; NO_IDENTIFIER : constant Identifier := -1; type Entity_Type is range 0 .. 2**16 - 1; NO_ENTITY_TYPE : constant Entity_Type := 0; type Object_Id is record Id : Identifier; Kind : Entity_Type; end record; pragma Pack (Object_Id); -- ------------------------------ -- Nullable Types -- ------------------------------ -- Most database allow to store a NULL instead of an actual integer, date or string value. -- Unlike Java, there is no easy way to distinguish between a NULL and an actual valid value. -- The <b>Nullable_T</b> types provide a way to specify and check whether a value is null -- or not. -- An integer which can be null. type Nullable_Integer is record Value : Integer := 0; Is_Null : Boolean := True; end record; -- A string which can be null. type Nullable_String is record Value : Ada.Strings.Unbounded.Unbounded_String; Is_Null : Boolean := True; end record; -- A date which can be null. type Nullable_Time is record Value : Ada.Calendar.Time; Is_Null : Boolean := True; end record; -- Return True if the two nullable times are identical (both null or both same time). function "=" (Left, Right : in Nullable_Time) return Boolean; type Nullable_Entity_Type is record Value : Entity_Type := 0; Is_Null : Boolean := True; end record; -- ------------------------------ -- Blob data type -- ------------------------------ -- The <b>Blob</b> type is used to represent database blobs. The data is stored -- in an <b>Ada.Streams.Stream_Element_Array</b> pointed to by the <b>Data</b> member. -- The query statement and bind parameter will use a <b>Blob_Ref</b> which represents -- a reference to the blob data. This is intended to minimize data copy. type Blob (Len : Ada.Streams.Stream_Element_Offset) is new Util.Refs.Ref_Entity with record Data : Ada.Streams.Stream_Element_Array (1 .. Len); end record; type Blob_Access is access all Blob; package Blob_References is new Util.Refs.Indefinite_References (Blob, Blob_Access); subtype Blob_Ref is Blob_References.Ref; -- Create a blob with an allocated buffer of <b>Size</b> bytes. function Create_Blob (Size : in Natural) return Blob_Ref; -- Create a blob initialized with the given data buffer. function Create_Blob (Data : in Ada.Streams.Stream_Element_Array) return Blob_Ref; -- Create a blob initialized with the content from the file whose path is <b>Path</b>. -- Raises an IO exception if the file does not exist. function Create_Blob (Path : in String) return Blob_Ref; -- Return a null blob. function Null_Blob return Blob_Ref; private DEFAULT_TIME : constant Ada.Calendar.Time := Ada.Calendar.Time_Of (Year => 1901, Month => 1, Day => 2, Seconds => 0.0); end ADO;
----------------------------------------------------------------------- -- ADO Databases -- Database Objects -- Copyright (C) 2009, 2010, 2011, 2012, 2015, 2018 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Strings.Unbounded; with Ada.Streams; with Ada.Calendar; with Util.Refs; package ADO is type Int64 is range -2**63 .. 2**63 - 1; for Int64'Size use 64; type Unsigned64 is mod 2**64; for Unsigned64'Size use 64; DEFAULT_TIME : constant Ada.Calendar.Time; -- ------------------------------ -- Database Identifier -- ------------------------------ -- type Identifier is range -2**47 .. 2**47 - 1; NO_IDENTIFIER : constant Identifier := -1; type Entity_Type is range 0 .. 2**16 - 1; NO_ENTITY_TYPE : constant Entity_Type := 0; type Object_Id is record Id : Identifier; Kind : Entity_Type; end record; pragma Pack (Object_Id); -- ------------------------------ -- Nullable Types -- ------------------------------ -- Most database allow to store a NULL instead of an actual integer, date or string value. -- Unlike Java, there is no easy way to distinguish between a NULL and an actual valid value. -- The <b>Nullable_T</b> types provide a way to specify and check whether a value is null -- or not. -- An integer which can be null. type Nullable_Integer is record Value : Integer := 0; Is_Null : Boolean := True; end record; Null_Integer : constant Nullable_Integer; -- A string which can be null. type Nullable_String is record Value : Ada.Strings.Unbounded.Unbounded_String; Is_Null : Boolean := True; end record; Null_String : constant Nullable_String; -- A date which can be null. type Nullable_Time is record Value : Ada.Calendar.Time; Is_Null : Boolean := True; end record; Null_Time : constant Nullable_Time; -- Return True if the two nullable times are identical (both null or both same time). function "=" (Left, Right : in Nullable_Time) return Boolean; type Nullable_Entity_Type is record Value : Entity_Type := 0; Is_Null : Boolean := True; end record; Null_Entity_Type : constant Nullable_Entity_Type; -- ------------------------------ -- Blob data type -- ------------------------------ -- The <b>Blob</b> type is used to represent database blobs. The data is stored -- in an <b>Ada.Streams.Stream_Element_Array</b> pointed to by the <b>Data</b> member. -- The query statement and bind parameter will use a <b>Blob_Ref</b> which represents -- a reference to the blob data. This is intended to minimize data copy. type Blob (Len : Ada.Streams.Stream_Element_Offset) is new Util.Refs.Ref_Entity with record Data : Ada.Streams.Stream_Element_Array (1 .. Len); end record; type Blob_Access is access all Blob; package Blob_References is new Util.Refs.Indefinite_References (Blob, Blob_Access); subtype Blob_Ref is Blob_References.Ref; -- Create a blob with an allocated buffer of <b>Size</b> bytes. function Create_Blob (Size : in Natural) return Blob_Ref; -- Create a blob initialized with the given data buffer. function Create_Blob (Data : in Ada.Streams.Stream_Element_Array) return Blob_Ref; -- Create a blob initialized with the content from the file whose path is <b>Path</b>. -- Raises an IO exception if the file does not exist. function Create_Blob (Path : in String) return Blob_Ref; -- Return a null blob. function Null_Blob return Blob_Ref; private DEFAULT_TIME : constant Ada.Calendar.Time := Ada.Calendar.Time_Of (Year => 1901, Month => 1, Day => 2, Seconds => 0.0); Null_Integer : constant Nullable_Integer := Nullable_Integer '(Is_Null => True, Value => 0); Null_String : constant Nullable_String := Nullable_String '(Is_Null => True, Value => Ada.Strings.Unbounded.Null_Unbounded_String); Null_Time : constant Nullable_Time := Nullable_Time '(Is_Null => True, Value => DEFAULT_TIME); Null_Entity_Type : constant Nullable_Entity_Type := Nullable_Entity_Type '(Is_Null => True, Value => 0); end ADO;
Define Null_Integer, Null_String, Null_Entity_Type, Null_Type constants
Define Null_Integer, Null_String, Null_Entity_Type, Null_Type constants
Ada
apache-2.0
stcarrez/ada-ado
fecfaa6ca77415dc6c415655487c6a248037aa34
src/util-serialize-mappers-record_mapper.ads
src/util-serialize-mappers-record_mapper.ads
----------------------------------------------------------------------- -- Util.Serialize.Mappers.Record_Mapper -- Mapper for record types -- 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.Beans.Objects; with Util.Serialize.IO; generic type Element_Type is limited private; type Element_Type_Access is access all Element_Type; type Fields is (<>); -- The <b>Set_Member</b> procedure will be called by the mapper when a mapping associated -- with <b>Field</b> is recognized. The <b>Value</b> holds the value that was extracted -- according to the mapping. The <b>Set_Member</b> procedure should save in the target -- object <b>Into</b> the value. If an error is detected, the procedure can raise the -- <b>Util.Serialize.Mappers.Field_Error</b> exception. The exception message will be -- reported by the IO reader as an error. with procedure Set_Member (Into : in out Element_Type; Field : in Fields; Value : in Util.Beans.Objects.Object); -- Adding a second function/procedure as generic parameter makes the -- Vector_Mapper generic package fail to instantiate a valid package. -- The failure occurs in Vector_Mapper in the 'with package Element_Mapper' instantiation. -- -- with function Get_Member (From : in Element_Type; -- Field : in Fields) return Util.Beans.Objects.Object; package Util.Serialize.Mappers.Record_Mapper is type Get_Member_Access is access function (From : in Element_Type; Field : in Fields) return Util.Beans.Objects.Object; -- Procedure to give access to the <b>Element_Type</b> object from the context. type Process_Object is not null access procedure (Ctx : in out Util.Serialize.Contexts.Context'Class; Attr : in Mapping'Class; Value : in Util.Beans.Objects.Object; Process : not null access procedure (Attr : in Mapping'Class; Item : in out Element_Type; Value : in Util.Beans.Objects.Object)); type Proxy_Object is not null access procedure (Attr : in Mapping'Class; Element : in out Element_Type; Value : in Util.Beans.Objects.Object); -- Set the attribute member described by the <b>Attr</b> mapping -- into the value passed in <b>Element</b>. This operation will call -- the package parameter function of the same name. procedure Set_Member (Attr : in Mapping'Class; Element : in out Element_Type; Value : in Util.Beans.Objects.Object); -- ----------------------- -- Data context -- ----------------------- -- Data context to get access to the target element. type Element_Data is new Util.Serialize.Contexts.Data with private; type Element_Data_Access is access all Element_Data'Class; -- Get the element object. function Get_Element (Data : in Element_Data) return Element_Type_Access; -- Set the element object. When <b>Release</b> is set, the element <b>Element</b> -- will be freed when the reader context is deleted (by <b>Finalize</b>). procedure Set_Element (Data : in out Element_Data; Element : in Element_Type_Access; Release : in Boolean := False); -- Finalize the object when it is removed from the reader context. -- If the <b>Release</b> parameter was set, the target element will be freed. overriding procedure Finalize (Data : in out Element_Data); -- ----------------------- -- Record mapper -- ----------------------- type Mapper is new Util.Serialize.Mappers.Mapper with private; type Mapper_Access is access all Mapper'Class; -- Execute the mapping operation on the object associated with the current context. -- The object is extracted from the context and the <b>Execute</b> operation is called. procedure Execute (Handler : in Mapper; Map : in Mapping'Class; Ctx : in out Util.Serialize.Contexts.Context'Class; Value : in Util.Beans.Objects.Object); -- Add a mapping for setting a member. When the attribute rule defined by <b>Path</b> -- is matched, the <b>Set_Member</b> procedure will be called with the value and the -- <b>Field</b> identification. procedure Add_Mapping (Into : in out Mapper; Path : in String; Field : in Fields); -- Add a mapping associated with the path and described by a mapper object. -- The <b>Proxy</b> procedure is in charge of giving access to the target -- object used by the <b>Map</b> mapper. procedure Add_Mapping (Into : in out Mapper; Path : in String; Map : in Util.Serialize.Mappers.Mapper_Access; Proxy : in Proxy_Object); -- Clone the <b>Handler</b> instance and get a copy of that single object. overriding function Clone (Handler : in Mapper) return Util.Serialize.Mappers.Mapper_Access; -- procedure Bind (Into : in out Mapper; Getter : in Get_Member_Access); procedure Bind (Into : in out Mapper; From : in Mapper_Access); function Get_Getter (From : in Mapper) return Get_Member_Access; -- Set the element in the context. When <b>Release</b> is set, the element <b>Element</b> -- will be freed when the reader context is deleted (by <b>Finalize</b>). procedure Set_Context (Ctx : in out Util.Serialize.Contexts.Context'Class; Element : in Element_Type_Access; Release : in Boolean := False); -- Build a default mapping based on the <b>Fields</b> enumeration. -- The enumeration name is used for the mapping name with the optional <b>FIELD_</b> -- prefix stripped. procedure Add_Default_Mapping (Into : in out Mapper); -- Write the element on the stream using the mapper description. procedure Write (Handler : in Mapper; Stream : in out Util.Serialize.IO.Output_Stream'Class; Element : in Element_Type); -- Write the element on the stream using the mapper description. procedure Write (Handler : in Util.Serialize.Mappers.Mapper'Class; Getter : in Get_Member_Access; Stream : in out Util.Serialize.IO.Output_Stream'Class; Element : in Element_Type); private type Element_Data is new Util.Serialize.Contexts.Data with record Element : Element_Type_Access; Release : Boolean; end record; type Mapper is new Util.Serialize.Mappers.Mapper with record Execute : Proxy_Object := Set_Member'Access; Get_Member : Get_Member_Access; end record; type Attribute_Mapping is new Mapping with record Index : Fields; end record; type Attribute_Mapping_Access is access all Attribute_Mapping'Class; procedure Set_Member (Attr : in Attribute_Mapping; Element : in out Element_Type; Value : in Util.Beans.Objects.Object); type Proxy_Mapper is new Mapper with null record; type Proxy_Mapper_Access is access all Proxy_Mapper'Class; -- Find the mapper associated with the given name. -- Returns null if there is no mapper. overriding function Find_Mapper (Controller : in Proxy_Mapper; Name : in String; Attribute : in Boolean := False) return Util.Serialize.Mappers.Mapper_Access; end Util.Serialize.Mappers.Record_Mapper;
----------------------------------------------------------------------- -- Util.Serialize.Mappers.Record_Mapper -- Mapper for record types -- 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.Beans.Objects; with Util.Serialize.IO; generic type Element_Type (<>) is limited private; type Element_Type_Access is access all Element_Type; type Fields is (<>); -- The <b>Set_Member</b> procedure will be called by the mapper when a mapping associated -- with <b>Field</b> is recognized. The <b>Value</b> holds the value that was extracted -- according to the mapping. The <b>Set_Member</b> procedure should save in the target -- object <b>Into</b> the value. If an error is detected, the procedure can raise the -- <b>Util.Serialize.Mappers.Field_Error</b> exception. The exception message will be -- reported by the IO reader as an error. with procedure Set_Member (Into : in out Element_Type; Field : in Fields; Value : in Util.Beans.Objects.Object); -- Adding a second function/procedure as generic parameter makes the -- Vector_Mapper generic package fail to instantiate a valid package. -- The failure occurs in Vector_Mapper in the 'with package Element_Mapper' instantiation. -- -- with function Get_Member (From : in Element_Type; -- Field : in Fields) return Util.Beans.Objects.Object; package Util.Serialize.Mappers.Record_Mapper is type Get_Member_Access is access function (From : in Element_Type; Field : in Fields) return Util.Beans.Objects.Object; -- Procedure to give access to the <b>Element_Type</b> object from the context. type Process_Object is not null access procedure (Ctx : in out Util.Serialize.Contexts.Context'Class; Attr : in Mapping'Class; Value : in Util.Beans.Objects.Object; Process : not null access procedure (Attr : in Mapping'Class; Item : in out Element_Type; Value : in Util.Beans.Objects.Object)); type Proxy_Object is not null access procedure (Attr : in Mapping'Class; Element : in out Element_Type; Value : in Util.Beans.Objects.Object); -- Set the attribute member described by the <b>Attr</b> mapping -- into the value passed in <b>Element</b>. This operation will call -- the package parameter function of the same name. procedure Set_Member (Attr : in Mapping'Class; Element : in out Element_Type; Value : in Util.Beans.Objects.Object); -- ----------------------- -- Data context -- ----------------------- -- Data context to get access to the target element. type Element_Data is new Util.Serialize.Contexts.Data with private; type Element_Data_Access is access all Element_Data'Class; -- Get the element object. function Get_Element (Data : in Element_Data) return Element_Type_Access; -- Set the element object. When <b>Release</b> is set, the element <b>Element</b> -- will be freed when the reader context is deleted (by <b>Finalize</b>). procedure Set_Element (Data : in out Element_Data; Element : in Element_Type_Access; Release : in Boolean := False); -- Finalize the object when it is removed from the reader context. -- If the <b>Release</b> parameter was set, the target element will be freed. overriding procedure Finalize (Data : in out Element_Data); -- ----------------------- -- Record mapper -- ----------------------- type Mapper is new Util.Serialize.Mappers.Mapper with private; type Mapper_Access is access all Mapper'Class; -- Execute the mapping operation on the object associated with the current context. -- The object is extracted from the context and the <b>Execute</b> operation is called. procedure Execute (Handler : in Mapper; Map : in Mapping'Class; Ctx : in out Util.Serialize.Contexts.Context'Class; Value : in Util.Beans.Objects.Object); -- Add a mapping for setting a member. When the attribute rule defined by <b>Path</b> -- is matched, the <b>Set_Member</b> procedure will be called with the value and the -- <b>Field</b> identification. procedure Add_Mapping (Into : in out Mapper; Path : in String; Field : in Fields); -- Add a mapping associated with the path and described by a mapper object. -- The <b>Proxy</b> procedure is in charge of giving access to the target -- object used by the <b>Map</b> mapper. procedure Add_Mapping (Into : in out Mapper; Path : in String; Map : in Util.Serialize.Mappers.Mapper_Access; Proxy : in Proxy_Object); -- Clone the <b>Handler</b> instance and get a copy of that single object. overriding function Clone (Handler : in Mapper) return Util.Serialize.Mappers.Mapper_Access; -- procedure Bind (Into : in out Mapper; Getter : in Get_Member_Access); procedure Bind (Into : in out Mapper; From : in Mapper_Access); function Get_Getter (From : in Mapper) return Get_Member_Access; -- Set the element in the context. When <b>Release</b> is set, the element <b>Element</b> -- will be freed when the reader context is deleted (by <b>Finalize</b>). procedure Set_Context (Ctx : in out Util.Serialize.Contexts.Context'Class; Element : in Element_Type_Access; Release : in Boolean := False); -- Build a default mapping based on the <b>Fields</b> enumeration. -- The enumeration name is used for the mapping name with the optional <b>FIELD_</b> -- prefix stripped. procedure Add_Default_Mapping (Into : in out Mapper); -- Write the element on the stream using the mapper description. procedure Write (Handler : in Mapper; Stream : in out Util.Serialize.IO.Output_Stream'Class; Element : in Element_Type); -- Write the element on the stream using the mapper description. procedure Write (Handler : in Util.Serialize.Mappers.Mapper'Class; Getter : in Get_Member_Access; Stream : in out Util.Serialize.IO.Output_Stream'Class; Element : in Element_Type); private type Element_Data is new Util.Serialize.Contexts.Data with record Element : Element_Type_Access; Release : Boolean; end record; type Mapper is new Util.Serialize.Mappers.Mapper with record Execute : Proxy_Object := Set_Member'Access; Get_Member : Get_Member_Access; end record; type Attribute_Mapping is new Mapping with record Index : Fields; end record; type Attribute_Mapping_Access is access all Attribute_Mapping'Class; procedure Set_Member (Attr : in Attribute_Mapping; Element : in out Element_Type; Value : in Util.Beans.Objects.Object); type Proxy_Mapper is new Mapper with null record; type Proxy_Mapper_Access is access all Proxy_Mapper'Class; -- Find the mapper associated with the given name. -- Returns null if there is no mapper. overriding function Find_Mapper (Controller : in Proxy_Mapper; Name : in String; Attribute : in Boolean := False) return Util.Serialize.Mappers.Mapper_Access; end Util.Serialize.Mappers.Record_Mapper;
Allow an indefinite type as Element_Type for the generic package
Allow an indefinite type as Element_Type for the generic package
Ada
apache-2.0
stcarrez/ada-util,stcarrez/ada-util
1f26fb5b1666e4d14b3b3e567536970ffa67319b
src/ado-queries-loaders.adb
src/ado-queries-loaders.adb
----------------------------------------------------------------------- -- ado-queries-loaders -- Loader for Database Queries -- Copyright (C) 2011, 2012, 2013, 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 Interfaces; with Ada.IO_Exceptions; with Ada.Directories; with Ada.Unchecked_Deallocation; with ADO.Drivers.Connections; with Util.Files; with Util.Log.Loggers; with Util.Beans.Objects; with Util.Serialize.IO.XML; with Util.Serialize.Mappers.Record_Mapper; package body ADO.Queries.Loaders is use Util.Log; use ADO.Drivers.Connections; use Interfaces; use Ada.Calendar; Log : constant Loggers.Logger := Loggers.Create ("ADO.Queries.Loaders"); Base_Time : constant Ada.Calendar.Time := Ada.Calendar.Time_Of (Year => 1970, Month => 1, Day => 1); -- Check for file modification time at most every 60 seconds. FILE_CHECK_DELTA_TIME : constant Unsigned_32 := 60; -- The list of query files defined by the application. Query_Files : Query_File_Access := null; Last_Query : Query_Index := 0; Last_File : File_Index := 0; -- Convert a Time to an Unsigned_32. function To_Unsigned_32 (T : in Ada.Calendar.Time) return Unsigned_32; pragma Inline_Always (To_Unsigned_32); -- Get the modification time of the XML query file associated with the query. function Modification_Time (File : in Query_File_Info) return Unsigned_32; -- Initialize the query SQL pattern with the value procedure Set_Query_Pattern (Into : in out Query_Pattern; Value : in Util.Beans.Objects.Object); -- ------------------------------ -- Register the query definition in the query file. Registration is done -- in the package elaboration phase. -- ------------------------------ procedure Register (File : in Query_File_Access; Query : in Query_Definition_Access) is begin Last_Query := Last_Query + 1; Query.File := File; Query.Next := File.Queries; Query.Query := Last_Query; File.Queries := Query; if File.Next = null and then Query_Files /= File then Last_File := Last_File + 1; File.Next := Query_Files; File.File := Last_File; Query_Files := File; end if; end Register; function Find_Driver (Name : in String) return Integer; function Find_Driver (Name : in String) return Integer is begin if Name'Length = 0 then return 0; end if; declare Driver : constant Drivers.Connections.Driver_Access := Drivers.Connections.Get_Driver (Name); begin if Driver = null then -- There is no problem to have an SQL query for unsupported drivers, but still -- report some warning. Log.Warn ("Database driver {0} not found", Name); return -1; end if; return Integer (Driver.Get_Driver_Index); end; end Find_Driver; -- ------------------------------ -- Convert a Time to an Unsigned_32. -- ------------------------------ function To_Unsigned_32 (T : in Ada.Calendar.Time) return Unsigned_32 is D : constant Duration := Duration '(T - Base_Time); begin return Unsigned_32 (D); end To_Unsigned_32; -- ------------------------------ -- Get the modification time of the XML query file associated with the query. -- ------------------------------ function Modification_Time (File : in Query_File_Info) return Unsigned_32 is Path : constant String := To_String (File.Path); begin return To_Unsigned_32 (Ada.Directories.Modification_Time (Path)); exception when Ada.IO_Exceptions.Name_Error => Log.Error ("XML query file '{0}' does not exist", Path); return 0; end Modification_Time; -- ------------------------------ -- Returns True if the XML query file must be reloaded. -- ------------------------------ function Is_Modified (File : in out Query_File_Info) return Boolean is Now : constant Unsigned_32 := To_Unsigned_32 (Ada.Calendar.Clock); begin -- Have we passed the next check time? if File.Next_Check > Now then return False; end if; -- Next check in N seconds (60 by default). File.Next_Check := Now + FILE_CHECK_DELTA_TIME; -- See if the file was changed. declare M : constant Unsigned_32 := Modification_Time (File); begin if File.Last_Modified = M then return False; end if; File.Last_Modified := M; return True; end; end Is_Modified; -- ------------------------------ -- Initialize the query SQL pattern with the value -- ------------------------------ procedure Set_Query_Pattern (Into : in out Query_Pattern; Value : in Util.Beans.Objects.Object) is begin Into.SQL := Util.Beans.Objects.To_Unbounded_String (Value); end Set_Query_Pattern; procedure Read_Query (Manager : in Query_Manager; File : in out Query_File_Info) is type Query_Info_Fields is (FIELD_CLASS_NAME, FIELD_PROPERTY_TYPE, FIELD_PROPERTY_NAME, FIELD_QUERY_NAME, FIELD_SQL_DRIVER, FIELD_SQL, FIELD_SQL_COUNT, FIELD_QUERY); -- The Query_Loader holds context and state information for loading -- the XML query file and initializing the Query_Definition. type Query_Loader is record -- File : Query_File_Access; Hash_Value : Unbounded_String; Query_Def : Query_Definition_Access; Query : Query_Info_Ref.Ref; Driver : Integer; end record; type Query_Loader_Access is access all Query_Loader; procedure Set_Member (Into : in out Query_Loader; Field : in Query_Info_Fields; Value : in Util.Beans.Objects.Object); -- ------------------------------ -- Called by the de-serialization when a given field is recognized. -- ------------------------------ procedure Set_Member (Into : in out Query_Loader; Field : in Query_Info_Fields; Value : in Util.Beans.Objects.Object) is use ADO.Drivers; begin case Field is when FIELD_CLASS_NAME => Append (Into.Hash_Value, " class="); Append (Into.Hash_Value, Util.Beans.Objects.To_Unbounded_String (Value)); when FIELD_PROPERTY_TYPE => Append (Into.Hash_Value, " type="); Append (Into.Hash_Value, Util.Beans.Objects.To_Unbounded_String (Value)); when FIELD_PROPERTY_NAME => Append (Into.Hash_Value, " name="); Append (Into.Hash_Value, Util.Beans.Objects.To_Unbounded_String (Value)); when FIELD_QUERY_NAME => Into.Query_Def := Find_Query (File, Util.Beans.Objects.To_String (Value)); Into.Driver := 0; if Into.Query_Def /= null then Into.Query := Query_Info_Ref.Create; end if; when FIELD_SQL_DRIVER => Into.Driver := Find_Driver (Util.Beans.Objects.To_String (Value)); when FIELD_SQL => if not Into.Query.Is_Null and Into.Driver >= 0 and Into.Query_Def /= null then Set_Query_Pattern (Into.Query.Value.Main_Query (Driver_Index (Into.Driver)), Value); end if; Into.Driver := 0; when FIELD_SQL_COUNT => if not Into.Query.Is_Null and Into.Driver >= 0 and Into.Query_Def /= null then Set_Query_Pattern (Into.Query.Value.Count_Query (Driver_Index (Into.Driver)), Value); end if; Into.Driver := 0; when FIELD_QUERY => if Into.Query_Def /= null then -- Now we can safely setup the query info associated with the query definition. Manager.Queries (Into.Query_Def.Query).Set (Into.Query); end if; Into.Query_Def := null; end case; end Set_Member; package Query_Mapper is new Util.Serialize.Mappers.Record_Mapper (Element_Type => Query_Loader, Element_Type_Access => Query_Loader_Access, Fields => Query_Info_Fields, Set_Member => Set_Member); Loader : aliased Query_Loader; Sql_Mapper : aliased Query_Mapper.Mapper; Reader : Util.Serialize.IO.XML.Parser; Mapper : Util.Serialize.Mappers.Processing; Path : constant String := To_String (File.Path); begin Log.Info ("Reading XML query {0}", Path); -- Loader.File := Into; Loader.Driver := 0; -- Create the mapping to load the XML query file. Sql_Mapper.Add_Mapping ("class/@name", FIELD_CLASS_NAME); Sql_Mapper.Add_Mapping ("class/property/@type", FIELD_PROPERTY_TYPE); Sql_Mapper.Add_Mapping ("class/property/@name", FIELD_PROPERTY_NAME); Sql_Mapper.Add_Mapping ("query/@name", FIELD_QUERY_NAME); Sql_Mapper.Add_Mapping ("query/sql", FIELD_SQL); Sql_Mapper.Add_Mapping ("query/sql/@driver", FIELD_SQL_DRIVER); Sql_Mapper.Add_Mapping ("query/sql-count", FIELD_SQL_COUNT); Sql_Mapper.Add_Mapping ("query", FIELD_QUERY); Mapper.Add_Mapping ("query-mapping", Sql_Mapper'Unchecked_Access); -- Set the context for Set_Member. Query_Mapper.Set_Context (Mapper, Loader'Access); -- Read the XML query file. Reader.Parse (Path, Mapper); File.Next_Check := To_Unsigned_32 (Ada.Calendar.Clock) + FILE_CHECK_DELTA_TIME; exception when Ada.IO_Exceptions.Name_Error => Log.Error ("XML query file '{0}' does not exist", Path); end Read_Query; -- ------------------------------ -- Read the query definition. -- ------------------------------ procedure Read_Query (Manager : in Query_Manager; Into : in Query_Definition_Access) is begin if Manager.Queries (Into.Query).Get.Is_Null or else Is_Modified (Manager.Files (Into.File.File)) then Read_Query (Manager, Manager.Files (Into.File.File)); end if; end Read_Query; -- ------------------------------ -- Initialize the queries to look in the list of directories specified by <b>Paths</b>. -- Each search directory is separated by ';' (yes, even on Unix). -- When <b>Load</b> is true, read the XML query file and initialize the query -- definitions from that file. -- ------------------------------ procedure Initialize (Manager : in out Query_Manager; Config : in ADO.Drivers.Connections.Configuration'Class) is procedure Free is new Ada.Unchecked_Deallocation (Object => String, Name => Ada.Strings.Unbounded.String_Access); Paths : constant String := Config.Get_Property ("ado.queries.paths"); Load : constant Boolean := Config.Get_Property ("ado.queries.load") = "true"; File : Query_File_Access := Query_Files; Pos : Query_Index_Table := 1; begin Log.Info ("Initializing query search paths to {0}", Paths); if Manager.Queries = null then Manager.Queries := new Query_Table (1 .. Last_Query); end if; if Manager.Files = null then Manager.Files := new File_Table (1 .. Last_File); end if; Manager.Driver := Config.Get_Driver; while File /= null loop declare Path : constant String := Util.Files.Find_File_Path (Name => File.Name.all, Paths => Paths); Query : Query_Definition_Access := File.Queries; begin Manager.Files (File.File).File := File; Manager.Files (File.File).Path := To_Unbounded_String (Path); if Load then Read_Query (Manager, Manager.Files (File.File)); end if; end; File := File.Next; end loop; end Initialize; -- ------------------------------ -- Find the query identified by the given name. -- ------------------------------ function Find_Query (Name : in String) return Query_Definition_Access is File : Query_File_Access := Query_Files; begin while File /= null loop declare Query : Query_Definition_Access := File.Queries; begin while Query /= null loop if Query.Name.all = Name then return Query; end if; Query := Query.Next; end loop; end; File := File.Next; end loop; Log.Warn ("Query {0} not found", Name); return null; end Find_Query; package body File is begin File.Name := Name'Access; File.Sha1_Map := Hash'Access; end File; package body Query is begin Query.Name := Query_Name'Access; Query.Query := 0; Query.File := File; Query.Next := null; Register (File => File, Query => Query'Access); end Query; end ADO.Queries.Loaders;
----------------------------------------------------------------------- -- ado-queries-loaders -- Loader for Database Queries -- Copyright (C) 2011, 2012, 2013, 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 Interfaces; with Ada.IO_Exceptions; with Ada.Directories; with Ada.Unchecked_Deallocation; with ADO.Drivers.Connections; with Util.Files; with Util.Log.Loggers; with Util.Beans.Objects; with Util.Serialize.IO.XML; with Util.Serialize.Mappers.Record_Mapper; package body ADO.Queries.Loaders is use Util.Log; use ADO.Drivers.Connections; use Interfaces; use Ada.Calendar; Log : constant Loggers.Logger := Loggers.Create ("ADO.Queries.Loaders"); Base_Time : constant Ada.Calendar.Time := Ada.Calendar.Time_Of (Year => 1970, Month => 1, Day => 1); -- Check for file modification time at most every 60 seconds. FILE_CHECK_DELTA_TIME : constant Unsigned_32 := 60; -- The list of query files defined by the application. Query_Files : Query_File_Access := null; Last_Query : Query_Index := 0; Last_File : File_Index := 0; -- Convert a Time to an Unsigned_32. function To_Unsigned_32 (T : in Ada.Calendar.Time) return Unsigned_32; pragma Inline_Always (To_Unsigned_32); -- Get the modification time of the XML query file associated with the query. function Modification_Time (File : in Query_File_Info) return Unsigned_32; -- Initialize the query SQL pattern with the value procedure Set_Query_Pattern (Into : in out Query_Pattern; Value : in Util.Beans.Objects.Object); -- ------------------------------ -- Register the query definition in the query file. Registration is done -- in the package elaboration phase. -- ------------------------------ procedure Register (File : in Query_File_Access; Query : in Query_Definition_Access) is begin Last_Query := Last_Query + 1; Query.File := File; Query.Next := File.Queries; Query.Query := Last_Query; File.Queries := Query; if File.Next = null and then Query_Files /= File then Last_File := Last_File + 1; File.Next := Query_Files; File.File := Last_File; Query_Files := File; end if; end Register; function Find_Driver (Name : in String) return Integer; function Find_Driver (Name : in String) return Integer is begin if Name'Length = 0 then return 0; end if; declare Driver : constant Drivers.Connections.Driver_Access := Drivers.Connections.Get_Driver (Name); begin if Driver = null then -- There is no problem to have an SQL query for unsupported drivers, but still -- report some warning. Log.Warn ("Database driver {0} not found", Name); return -1; end if; return Integer (Driver.Get_Driver_Index); end; end Find_Driver; -- ------------------------------ -- Convert a Time to an Unsigned_32. -- ------------------------------ function To_Unsigned_32 (T : in Ada.Calendar.Time) return Unsigned_32 is D : constant Duration := Duration '(T - Base_Time); begin return Unsigned_32 (D); end To_Unsigned_32; -- ------------------------------ -- Get the modification time of the XML query file associated with the query. -- ------------------------------ function Modification_Time (File : in Query_File_Info) return Unsigned_32 is Path : constant String := To_String (File.Path); begin return To_Unsigned_32 (Ada.Directories.Modification_Time (Path)); exception when Ada.IO_Exceptions.Name_Error => Log.Error ("XML query file '{0}' does not exist", Path); return 0; end Modification_Time; -- ------------------------------ -- Returns True if the XML query file must be reloaded. -- ------------------------------ function Is_Modified (File : in out Query_File_Info) return Boolean is Now : constant Unsigned_32 := To_Unsigned_32 (Ada.Calendar.Clock); begin -- Have we passed the next check time? if File.Next_Check > Now then return False; end if; -- Next check in N seconds (60 by default). File.Next_Check := Now + FILE_CHECK_DELTA_TIME; -- See if the file was changed. declare M : constant Unsigned_32 := Modification_Time (File); begin if File.Last_Modified = M then return False; end if; File.Last_Modified := M; return True; end; end Is_Modified; -- ------------------------------ -- Initialize the query SQL pattern with the value -- ------------------------------ procedure Set_Query_Pattern (Into : in out Query_Pattern; Value : in Util.Beans.Objects.Object) is begin Into.SQL := Util.Beans.Objects.To_Unbounded_String (Value); end Set_Query_Pattern; procedure Read_Query (Manager : in Query_Manager; File : in out Query_File_Info) is type Query_Info_Fields is (FIELD_CLASS_NAME, FIELD_PROPERTY_TYPE, FIELD_PROPERTY_NAME, FIELD_QUERY_NAME, FIELD_SQL_DRIVER, FIELD_SQL, FIELD_SQL_COUNT, FIELD_QUERY); -- The Query_Loader holds context and state information for loading -- the XML query file and initializing the Query_Definition. type Query_Loader is record -- File : Query_File_Access; Hash_Value : Unbounded_String; Query_Def : Query_Definition_Access; Query : Query_Info_Ref.Ref; Driver : Integer; end record; type Query_Loader_Access is access all Query_Loader; procedure Set_Member (Into : in out Query_Loader; Field : in Query_Info_Fields; Value : in Util.Beans.Objects.Object); -- ------------------------------ -- Called by the de-serialization when a given field is recognized. -- ------------------------------ procedure Set_Member (Into : in out Query_Loader; Field : in Query_Info_Fields; Value : in Util.Beans.Objects.Object) is use ADO.Drivers; begin case Field is when FIELD_CLASS_NAME => Append (Into.Hash_Value, " class="); Append (Into.Hash_Value, Util.Beans.Objects.To_Unbounded_String (Value)); when FIELD_PROPERTY_TYPE => Append (Into.Hash_Value, " type="); Append (Into.Hash_Value, Util.Beans.Objects.To_Unbounded_String (Value)); when FIELD_PROPERTY_NAME => Append (Into.Hash_Value, " name="); Append (Into.Hash_Value, Util.Beans.Objects.To_Unbounded_String (Value)); when FIELD_QUERY_NAME => Into.Query_Def := Find_Query (File, Util.Beans.Objects.To_String (Value)); Into.Driver := 0; if Into.Query_Def /= null then Into.Query := Query_Info_Ref.Create; end if; when FIELD_SQL_DRIVER => Into.Driver := Find_Driver (Util.Beans.Objects.To_String (Value)); when FIELD_SQL => if not Into.Query.Is_Null and Into.Driver >= 0 and Into.Query_Def /= null then Set_Query_Pattern (Into.Query.Value.Main_Query (Driver_Index (Into.Driver)), Value); end if; Into.Driver := 0; when FIELD_SQL_COUNT => if not Into.Query.Is_Null and Into.Driver >= 0 and Into.Query_Def /= null then Set_Query_Pattern (Into.Query.Value.Count_Query (Driver_Index (Into.Driver)), Value); end if; Into.Driver := 0; when FIELD_QUERY => if Into.Query_Def /= null then -- Now we can safely setup the query info associated with the query definition. Manager.Queries (Into.Query_Def.Query) := Into.Query; end if; Into.Query_Def := null; end case; end Set_Member; package Query_Mapper is new Util.Serialize.Mappers.Record_Mapper (Element_Type => Query_Loader, Element_Type_Access => Query_Loader_Access, Fields => Query_Info_Fields, Set_Member => Set_Member); Loader : aliased Query_Loader; Sql_Mapper : aliased Query_Mapper.Mapper; Reader : Util.Serialize.IO.XML.Parser; Mapper : Util.Serialize.Mappers.Processing; Path : constant String := To_String (File.Path); begin Log.Info ("Reading XML query {0}", Path); -- Loader.File := Into; Loader.Driver := 0; -- Create the mapping to load the XML query file. Sql_Mapper.Add_Mapping ("class/@name", FIELD_CLASS_NAME); Sql_Mapper.Add_Mapping ("class/property/@type", FIELD_PROPERTY_TYPE); Sql_Mapper.Add_Mapping ("class/property/@name", FIELD_PROPERTY_NAME); Sql_Mapper.Add_Mapping ("query/@name", FIELD_QUERY_NAME); Sql_Mapper.Add_Mapping ("query/sql", FIELD_SQL); Sql_Mapper.Add_Mapping ("query/sql/@driver", FIELD_SQL_DRIVER); Sql_Mapper.Add_Mapping ("query/sql-count", FIELD_SQL_COUNT); Sql_Mapper.Add_Mapping ("query", FIELD_QUERY); Mapper.Add_Mapping ("query-mapping", Sql_Mapper'Unchecked_Access); -- Set the context for Set_Member. Query_Mapper.Set_Context (Mapper, Loader'Access); -- Read the XML query file. Reader.Parse (Path, Mapper); File.Next_Check := To_Unsigned_32 (Ada.Calendar.Clock) + FILE_CHECK_DELTA_TIME; exception when Ada.IO_Exceptions.Name_Error => Log.Error ("XML query file '{0}' does not exist", Path); end Read_Query; -- ------------------------------ -- Read the query definition. -- ------------------------------ procedure Read_Query (Manager : in Query_Manager; Into : in Query_Definition_Access) is begin if Manager.Queries (Into.Query).Is_Null or else Is_Modified (Manager.Files (Into.File.File)) then Read_Query (Manager, Manager.Files (Into.File.File)); end if; end Read_Query; -- ------------------------------ -- Initialize the queries to look in the list of directories specified by <b>Paths</b>. -- Each search directory is separated by ';' (yes, even on Unix). -- When <b>Load</b> is true, read the XML query file and initialize the query -- definitions from that file. -- ------------------------------ procedure Initialize (Manager : in out Query_Manager; Config : in ADO.Drivers.Connections.Configuration'Class) is procedure Free is new Ada.Unchecked_Deallocation (Object => String, Name => Ada.Strings.Unbounded.String_Access); Paths : constant String := Config.Get_Property ("ado.queries.paths"); Load : constant Boolean := Config.Get_Property ("ado.queries.load") = "true"; File : Query_File_Access := Query_Files; Pos : Query_Index_Table := 1; begin Log.Info ("Initializing query search paths to {0}", Paths); if Manager.Queries = null then Manager.Queries := new Query_Table (1 .. Last_Query); end if; if Manager.Files = null then Manager.Files := new File_Table (1 .. Last_File); end if; Manager.Driver := Config.Get_Driver; while File /= null loop declare Path : constant String := Util.Files.Find_File_Path (Name => File.Name.all, Paths => Paths); Query : Query_Definition_Access := File.Queries; begin Manager.Files (File.File).File := File; Manager.Files (File.File).Path := To_Unbounded_String (Path); if Load then Read_Query (Manager, Manager.Files (File.File)); end if; end; File := File.Next; end loop; end Initialize; -- ------------------------------ -- Find the query identified by the given name. -- ------------------------------ function Find_Query (Name : in String) return Query_Definition_Access is File : Query_File_Access := Query_Files; begin while File /= null loop declare Query : Query_Definition_Access := File.Queries; begin while Query /= null loop if Query.Name.all = Name then return Query; end if; Query := Query.Next; end loop; end; File := File.Next; end loop; Log.Warn ("Query {0} not found", Name); return null; end Find_Query; package body File is begin File.Name := Name'Access; File.Sha1_Map := Hash'Access; end File; package body Query is begin Query.Name := Query_Name'Access; Query.Query := 0; Query.File := File; Query.Next := null; Register (File => File, Query => Query'Access); end Query; end ADO.Queries.Loaders;
Update to use the simple reference
Update to use the simple reference
Ada
apache-2.0
stcarrez/ada-ado
20dc1ac50007216c72df5e103450ff773d2fcd79
regtests/ado-drivers-tests.ads
regtests/ado-drivers-tests.ads
----------------------------------------------------------------------- -- 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 Util.Tests; package ADO.Drivers.Tests is procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite); type Test is new Util.Tests.Test with null record; -- Test the Initialize operation. procedure Test_Initialize (T : in out Test); -- Test the Get_Config operation. procedure Test_Get_Config (T : in out Test); -- Test the Get_Driver operation. procedure Test_Get_Driver (T : in out Test); -- Test loading some invalid database driver. procedure Test_Load_Invalid_Driver (T : in out Test); -- Test the Get_Driver_Index operation. procedure Test_Get_Driver_Index (T : in out Test); -- Test the Set_Connection procedure. procedure Test_Set_Connection (T : in out Test); -- Test the Set_Connection procedure with several error cases. procedure Test_Set_Connection_Error (T : in out Test); -- Test the Set_Server operation. procedure Test_Set_Connection_Server (T : in out Test); -- Test the connection operations on an empty connection. procedure Test_Empty_Connection (T : in out Test); end ADO.Drivers.Tests;
----------------------------------------------------------------------- -- 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 Util.Tests; package ADO.Drivers.Tests is procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite); type Test is new Util.Tests.Test with null record; -- Test the Initialize operation. procedure Test_Initialize (T : in out Test); -- Test the Get_Config operation. procedure Test_Get_Config (T : in out Test); -- Test the Get_Driver operation. procedure Test_Get_Driver (T : in out Test); -- Test loading some invalid database driver. procedure Test_Load_Invalid_Driver (T : in out Test); -- Test the Get_Driver_Index operation. procedure Test_Get_Driver_Index (T : in out Test); -- Test the Set_Connection procedure. procedure Test_Set_Connection (T : in out Test); -- Test the Set_Connection procedure with several error cases. procedure Test_Set_Connection_Error (T : in out Test); -- Test the Set_Server operation. procedure Test_Set_Connection_Server (T : in out Test); -- Test the Set_Port operation. procedure Test_Set_Connection_Port (T : in out Test); -- Test the connection operations on an empty connection. procedure Test_Empty_Connection (T : in out Test); end ADO.Drivers.Tests;
Declare Test_Set_Connection_Port procedure
Declare Test_Set_Connection_Port procedure
Ada
apache-2.0
stcarrez/ada-ado
e63562bd120455b97971a9401cd903523a0cf9d2
src/asf-contexts-facelets.adb
src/asf-contexts-facelets.adb
----------------------------------------------------------------------- -- contexts-facelets -- Contexts for facelets -- Copyright (C) 2009, 2010, 2011 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Directories; with Util.Files; with Util.Log.Loggers; with EL.Variables; with ASF.Applications.Main; with ASF.Views.Nodes.Facelets; package body ASF.Contexts.Facelets is use Util.Log; -- The logger Log : constant Loggers.Logger := Loggers.Create ("ASF.Contexts.Facelets"); -- ------------------------------ -- Get the EL context for evaluating expressions. -- ------------------------------ function Get_ELContext (Context : in Facelet_Context) return EL.Contexts.ELContext_Access is begin return Context.Context; end Get_ELContext; -- ------------------------------ -- Set the EL context for evaluating expressions. -- ------------------------------ procedure Set_ELContext (Context : in out Facelet_Context; ELContext : in EL.Contexts.ELContext_Access) is begin Context.Context := ELContext; end Set_ELContext; -- ------------------------------ -- Get the function mapper associated with the EL context. -- ------------------------------ function Get_Function_Mapper (Context : in Facelet_Context) return EL.Functions.Function_Mapper_Access is use EL.Contexts; begin if Context.Context = null then return null; else return Context.Context.Get_Function_Mapper; end if; end Get_Function_Mapper; -- ------------------------------ -- Set the attribute having given name with the value. -- ------------------------------ procedure Set_Attribute (Context : in out Facelet_Context; Name : in String; Value : in EL.Objects.Object) is begin null; end Set_Attribute; -- ------------------------------ -- Set the attribute having given name with the value. -- ------------------------------ procedure Set_Attribute (Context : in out Facelet_Context; Name : in Unbounded_String; Value : in EL.Objects.Object) is begin null; end Set_Attribute; -- ------------------------------ -- Set the attribute having given name with the expression. -- ------------------------------ procedure Set_Variable (Context : in out Facelet_Context; Name : in Unbounded_String; Value : in EL.Expressions.Expression) is Mapper : constant access EL.Variables.Variable_Mapper'Class := Context.Context.Get_Variable_Mapper; begin if Mapper /= null then Mapper.Set_Variable (Name, Value); end if; end Set_Variable; -- Set the attribute having given name with the expression. procedure Set_Variable (Context : in out Facelet_Context; Name : in String; Value : in EL.Expressions.Expression) is N : Unbounded_String := To_Unbounded_String (Name); begin Set_Variable (Context, N, Value); end Set_Variable; -- ------------------------------ -- Include the facelet from the given source file. -- The included views appended to the parent component tree. -- ------------------------------ procedure Include_Facelet (Context : in out Facelet_Context; Source : in String; Parent : in Base.UIComponent_Access) is begin null; end Include_Facelet; -- ------------------------------ -- Include the definition having the given name. -- ------------------------------ procedure Include_Definition (Context : in out Facelet_Context; Name : in Unbounded_String; Parent : in Base.UIComponent_Access; Found : out Boolean) is Node : Composition_Tag_Node; Iter : Defines_Vector.Cursor := Context.Defines.Last; The_Name : aliased constant String := To_String (Name); begin if Context.Inserts.Contains (The_Name'Unchecked_Access) then Found := True; return; end if; Context.Inserts.Insert (The_Name'Unchecked_Access); while Defines_Vector.Has_Element (Iter) loop Node := Defines_Vector.Element (Iter); Node.Include_Definition (Parent => Parent, Context => Context, Name => Name, Found => Found); if Found then Context.Inserts.Delete (The_Name'Unchecked_Access); return; end if; Defines_Vector.Previous (Iter); end loop; Found := False; Context.Inserts.Delete (The_Name'Unchecked_Access); end Include_Definition; -- ------------------------------ -- Push into the current facelet context the <ui:define> nodes contained in -- the composition/decorate tag. -- ------------------------------ procedure Push_Defines (Context : in out Facelet_Context; Node : access ASF.Views.Nodes.Facelets.Composition_Tag_Node) is begin Context.Defines.Append (Node.all'Access); end Push_Defines; -- ------------------------------ -- Pop from the current facelet context the <ui:define> nodes. -- ------------------------------ procedure Pop_Defines (Context : in out Facelet_Context) is use Ada.Containers; begin if Context.Defines.Length > 0 then Context.Defines.Delete_Last; end if; end Pop_Defines; -- ------------------------------ -- Set the path to resolve relative facelet paths and get the previous path. -- ------------------------------ procedure Set_Relative_Path (Context : in out Facelet_Context; Path : in String; Previous : out Unbounded_String) is begin Log.Debug ("Set facelet relative path: {0}", Path); Previous := Context.Path; Context.Path := To_Unbounded_String (Ada.Directories.Containing_Directory (Path)); end Set_Relative_Path; -- ------------------------------ -- Set the path to resolve relative facelet paths. -- ------------------------------ procedure Set_Relative_Path (Context : in out Facelet_Context; Path : in Unbounded_String) is begin Log.Debug ("Set facelet relative path: {0}", Path); Context.Path := Path; end Set_Relative_Path; -- ------------------------------ -- Resolve the facelet relative path -- ------------------------------ function Resolve_Path (Context : Facelet_Context; Path : String) return String is begin if Path (Path'First) = '/' then return Path; else Log.Debug ("Resolve {0} with context {1}", Path, To_String (Context.Path)); return Util.Files.Compose (To_String (Context.Path), Path); end if; end Resolve_Path; -- ------------------------------ -- Get a converter from a name. -- Returns the converter object or null if there is no converter. -- ------------------------------ function Get_Converter (Context : in Facelet_Context; Name : in EL.Objects.Object) return ASF.Converters.Converter_Access is begin return Facelet_Context'Class (Context).Get_Application.Find (Name); end Get_Converter; -- ------------------------------ -- Get a validator from a name. -- Returns the validator object or null if there is no validator. -- ------------------------------ function Get_Validator (Context : in Facelet_Context; Name : in EL.Objects.Object) return ASF.Validators.Validator_Access is begin return Facelet_Context'Class (Context).Get_Application.Find_Validator (Name); end Get_Validator; end ASF.Contexts.Facelets;
----------------------------------------------------------------------- -- contexts-facelets -- Contexts for facelets -- Copyright (C) 2009, 2010, 2011, 2013 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Directories; with Util.Files; with Util.Log.Loggers; with EL.Variables; with ASF.Applications.Main; with ASF.Views.Nodes.Facelets; package body ASF.Contexts.Facelets is use Util.Log; -- The logger Log : constant Loggers.Logger := Loggers.Create ("ASF.Contexts.Facelets"); -- ------------------------------ -- Get the EL context for evaluating expressions. -- ------------------------------ function Get_ELContext (Context : in Facelet_Context) return EL.Contexts.ELContext_Access is begin return Context.Context; end Get_ELContext; -- ------------------------------ -- Set the EL context for evaluating expressions. -- ------------------------------ procedure Set_ELContext (Context : in out Facelet_Context; ELContext : in EL.Contexts.ELContext_Access) is begin Context.Context := ELContext; end Set_ELContext; -- ------------------------------ -- Get the function mapper associated with the EL context. -- ------------------------------ function Get_Function_Mapper (Context : in Facelet_Context) return EL.Functions.Function_Mapper_Access is use EL.Contexts; begin if Context.Context = null then return null; else return Context.Context.Get_Function_Mapper; end if; end Get_Function_Mapper; -- ------------------------------ -- Set the attribute having given name with the value. -- ------------------------------ procedure Set_Attribute (Context : in out Facelet_Context; Name : in String; Value : in EL.Objects.Object) is begin null; end Set_Attribute; -- ------------------------------ -- Set the attribute having given name with the value. -- ------------------------------ procedure Set_Attribute (Context : in out Facelet_Context; Name : in Unbounded_String; Value : in EL.Objects.Object) is begin null; end Set_Attribute; -- ------------------------------ -- Set the attribute having given name with the expression. -- ------------------------------ procedure Set_Variable (Context : in out Facelet_Context; Name : in Unbounded_String; Value : in EL.Expressions.Expression) is Mapper : constant access EL.Variables.Variable_Mapper'Class := Context.Context.Get_Variable_Mapper; begin if Mapper /= null then Mapper.Set_Variable (Name, Value); end if; end Set_Variable; -- Set the attribute having given name with the expression. procedure Set_Variable (Context : in out Facelet_Context; Name : in String; Value : in EL.Expressions.Expression) is N : constant Unbounded_String := To_Unbounded_String (Name); begin Set_Variable (Context, N, Value); end Set_Variable; -- ------------------------------ -- Include the facelet from the given source file. -- The included views appended to the parent component tree. -- ------------------------------ procedure Include_Facelet (Context : in out Facelet_Context; Source : in String; Parent : in Base.UIComponent_Access) is begin null; end Include_Facelet; -- ------------------------------ -- Include the definition having the given name. -- ------------------------------ procedure Include_Definition (Context : in out Facelet_Context; Name : in Unbounded_String; Parent : in Base.UIComponent_Access; Found : out Boolean) is Node : Composition_Tag_Node; Iter : Defines_Vector.Cursor := Context.Defines.Last; The_Name : aliased constant String := To_String (Name); begin if Context.Inserts.Contains (The_Name'Unchecked_Access) then Found := True; return; end if; Context.Inserts.Insert (The_Name'Unchecked_Access); while Defines_Vector.Has_Element (Iter) loop Node := Defines_Vector.Element (Iter); Node.Include_Definition (Parent => Parent, Context => Context, Name => Name, Found => Found); if Found then Context.Inserts.Delete (The_Name'Unchecked_Access); return; end if; Defines_Vector.Previous (Iter); end loop; Found := False; Context.Inserts.Delete (The_Name'Unchecked_Access); end Include_Definition; -- ------------------------------ -- Push into the current facelet context the <ui:define> nodes contained in -- the composition/decorate tag. -- ------------------------------ procedure Push_Defines (Context : in out Facelet_Context; Node : access ASF.Views.Nodes.Facelets.Composition_Tag_Node) is begin Context.Defines.Append (Node.all'Access); end Push_Defines; -- ------------------------------ -- Pop from the current facelet context the <ui:define> nodes. -- ------------------------------ procedure Pop_Defines (Context : in out Facelet_Context) is use Ada.Containers; begin if Context.Defines.Length > 0 then Context.Defines.Delete_Last; end if; end Pop_Defines; -- ------------------------------ -- Set the path to resolve relative facelet paths and get the previous path. -- ------------------------------ procedure Set_Relative_Path (Context : in out Facelet_Context; Path : in String; Previous : out Unbounded_String) is begin Log.Debug ("Set facelet relative path: {0}", Path); Previous := Context.Path; Context.Path := To_Unbounded_String (Ada.Directories.Containing_Directory (Path)); end Set_Relative_Path; -- ------------------------------ -- Set the path to resolve relative facelet paths. -- ------------------------------ procedure Set_Relative_Path (Context : in out Facelet_Context; Path : in Unbounded_String) is begin Log.Debug ("Set facelet relative path: {0}", Path); Context.Path := Path; end Set_Relative_Path; -- ------------------------------ -- Resolve the facelet relative path -- ------------------------------ function Resolve_Path (Context : Facelet_Context; Path : String) return String is begin if Path (Path'First) = '/' then return Path; else Log.Debug ("Resolve {0} with context {1}", Path, To_String (Context.Path)); return Util.Files.Compose (To_String (Context.Path), Path); end if; end Resolve_Path; -- ------------------------------ -- Get a converter from a name. -- Returns the converter object or null if there is no converter. -- ------------------------------ function Get_Converter (Context : in Facelet_Context; Name : in EL.Objects.Object) return ASF.Converters.Converter_Access is begin return Facelet_Context'Class (Context).Get_Application.Find (Name); end Get_Converter; -- ------------------------------ -- Get a validator from a name. -- Returns the validator object or null if there is no validator. -- ------------------------------ function Get_Validator (Context : in Facelet_Context; Name : in EL.Objects.Object) return ASF.Validators.Validator_Access is begin return Facelet_Context'Class (Context).Get_Application.Find_Validator (Name); end Get_Validator; end ASF.Contexts.Facelets;
Fix compilation warning
Fix compilation warning
Ada
apache-2.0
Letractively/ada-asf,Letractively/ada-asf,Letractively/ada-asf
bc21ed4de06c7d48dcaaab6eb8a6a1bd8a5dae46
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 := "43"; 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 := "50"; 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.50
Bump version to 1.50 The watchdog is a signficant feature that merits a tens bump.
Ada
isc
jrmarino/synth,jrmarino/synth,jrmarino/synth,jrmarino/synth
c331b907c3800e94c23fba5cabef53f4f30d2c72
src/os-linux/util-processes-os.adb
src/os-linux/util-processes-os.adb
----------------------------------------------------------------------- -- util-processes-os -- System specific and low level 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 Ada.Unchecked_Deallocation; package body Util.Processes.Os is use Util.Systems.Os; use type Interfaces.C.size_t; type Pipe_Type is array (0 .. 1) of File_Type; procedure Close (Pipes : in out Pipe_Type); -- ------------------------------ -- Create the output stream to read/write on the process input/output. -- Setup the file to be closed on exec. -- ------------------------------ function Create_Stream (File : in File_Type) return Util.Streams.Raw.Raw_Stream_Access is Stream : constant Util.Streams.Raw.Raw_Stream_Access := new Util.Streams.Raw.Raw_Stream; Status : constant Integer := Sys_Fcntl (File, F_SETFL, FD_CLOEXEC); pragma Unreferenced (Status); begin Stream.Initialize (File); return Stream; end Create_Stream; -- ------------------------------ -- Wait for the process to exit. -- ------------------------------ overriding procedure Wait (Sys : in out System_Process; Proc : in out Process'Class; Timeout : in Duration) is pragma Unreferenced (Sys, Timeout); use type Util.Streams.Output_Stream_Access; Result : Integer; Wpid : Integer; begin -- Close the input stream pipe if there is one. if Proc.Input /= null then Util.Streams.Raw.Raw_Stream'Class (Proc.Input.all).Close; end if; Wpid := Sys_Waitpid (Integer (Proc.Pid), Result'Address, 0); if Wpid = Integer (Proc.Pid) then Proc.Exit_Value := Result / 256; if Result mod 256 /= 0 then Proc.Exit_Value := (Result mod 256) * 1000; end if; end if; end Wait; -- ------------------------------ -- Terminate the process by sending a signal on Unix and exiting the process on Windows. -- This operation is not portable and has a different behavior between Unix and Windows. -- Its intent is to stop the process. -- ------------------------------ overriding procedure Stop (Sys : in out System_Process; Proc : in out Process'Class; Signal : in Positive := 15) is pragma Unreferenced (Sys); Result : Integer; pragma Unreferenced (Result); begin Result := Sys_Kill (Integer (Proc.Pid), Integer (Signal)); end Stop; -- ------------------------------ -- Close both ends of the pipe (used to cleanup in case or error). -- ------------------------------ procedure Close (Pipes : in out Pipe_Type) is Result : Integer; pragma Unreferenced (Result); begin if Pipes (0) /= NO_FILE then Result := Sys_Close (Pipes (0)); Pipes (0) := NO_FILE; end if; if Pipes (1) /= NO_FILE then Result := Sys_Close (Pipes (1)); Pipes (1) := NO_FILE; end if; end Close; -- ------------------------------ -- Spawn a new process. -- ------------------------------ overriding procedure Spawn (Sys : in out System_Process; Proc : in out Process'Class; Mode : in Pipe_Mode := NONE) is use Util.Streams.Raw; use Interfaces.C.Strings; use type Interfaces.C.int; procedure Cleanup; -- Suppress all checks to make sure the child process will not raise any exception. pragma Suppress (All_Checks); Result : Integer; pragma Unreferenced (Result); Stdin_Pipes : aliased Pipe_Type := (others => NO_FILE); Stdout_Pipes : aliased Pipe_Type := (others => NO_FILE); Stderr_Pipes : aliased Pipe_Type := (others => NO_FILE); procedure Cleanup is begin Close (Stdin_Pipes); Close (Stdout_Pipes); Close (Stderr_Pipes); end Cleanup; begin -- Since checks are disabled, verify by hand that the argv table is correct. if Sys.Argv = null or else Sys.Argc < 1 or else Sys.Argv (0) = Null_Ptr then raise Program_Error with "Invalid process argument list"; end if; -- Setup the pipes. if Mode = READ or Mode = READ_WRITE or Mode = READ_ALL then if Sys_Pipe (Stdout_Pipes'Address) /= 0 then raise Process_Error with "Cannot create stdout pipe"; end if; end if; if Mode = WRITE or Mode = READ_WRITE or Mode = READ_WRITE_ALL then if Sys_Pipe (Stdin_Pipes'Address) /= 0 then Cleanup; raise Process_Error with "Cannot create stdin pipe"; end if; end if; if Mode = READ_ERROR then if Sys_Pipe (Stderr_Pipes'Address) /= 0 then Cleanup; raise Process_Error with "Cannot create stderr pipe"; end if; end if; -- Create the new process by using vfork instead of fork. The parent process is blocked -- until the child executes the exec or exits. The child process uses the same stack -- as the parent. Proc.Pid := Sys_VFork; if Proc.Pid = 0 then -- Do not use any Ada type while in the child process. if Mode = READ_ALL or Mode = READ_WRITE_ALL then Result := Sys_Dup2 (Stdout_Pipes (1), STDERR_FILENO); end if; if Stderr_Pipes (1) /= NO_FILE then if Stderr_Pipes (1) /= STDERR_FILENO then Result := Sys_Dup2 (Stderr_Pipes (1), STDERR_FILENO); Result := Sys_Close (Stderr_Pipes (1)); end if; Result := Sys_Close (Stderr_Pipes (0)); elsif Sys.Err_File /= Null_Ptr then -- Redirect the process error to a file. declare Fd : File_Type; begin if Sys.Err_Append then Fd := Sys_Open (Sys.Err_File, O_CREAT + O_WRONLY + O_APPEND, 8#644#); else Fd := Sys_Open (Sys.Err_File, O_CREAT + O_WRONLY + O_TRUNC, 8#644#); end if; if Fd < 0 then Sys_Exit (254); end if; Result := Sys_Dup2 (Fd, STDOUT_FILENO); Result := Sys_Close (Fd); end; end if; if Stdout_Pipes (1) /= NO_FILE then if Stdout_Pipes (1) /= STDOUT_FILENO then Result := Sys_Dup2 (Stdout_Pipes (1), STDOUT_FILENO); Result := Sys_Close (Stdout_Pipes (1)); end if; Result := Sys_Close (Stdout_Pipes (0)); elsif Sys.Out_File /= Null_Ptr then -- Redirect the process output to a file. declare Fd : File_Type; begin if Sys.Out_Append then Fd := Sys_Open (Sys.Out_File, O_CREAT + O_WRONLY + O_APPEND, 8#644#); else Fd := Sys_Open (Sys.Out_File, O_CREAT + O_WRONLY + O_TRUNC, 8#644#); end if; if Fd < 0 then Sys_Exit (254); end if; Result := Sys_Dup2 (Fd, STDOUT_FILENO); Result := Sys_Close (Fd); end; end if; if Stdin_Pipes (0) /= NO_FILE then if Stdin_Pipes (0) /= STDIN_FILENO then Result := Sys_Dup2 (Stdin_Pipes (0), STDIN_FILENO); Result := Sys_Close (Stdin_Pipes (0)); end if; Result := Sys_Close (Stdin_Pipes (1)); elsif Sys.In_File /= Null_Ptr then -- Redirect the process input to a file. declare Fd : File_Type; begin Fd := Sys_Open (Sys.Out_File, O_RDONLY, 8#644#); if Fd < 0 then Sys_Exit (254); end if; Result := Sys_Dup2 (Fd, STDIN_FILENO); Result := Sys_Close (Fd); end; end if; Result := Sys_Execvp (Sys.Argv (0), Sys.Argv.all); Sys_Exit (255); end if; -- Process creation failed, cleanup and raise an exception. if Proc.Pid < 0 then Cleanup; raise Process_Error with "Cannot create process"; end if; if Stdin_Pipes (1) /= NO_FILE then Result := Sys_Close (Stdin_Pipes (0)); Proc.Input := Create_Stream (Stdin_Pipes (1)).all'Access; end if; if Stdout_Pipes (0) /= NO_FILE then Result := Sys_Close (Stdout_Pipes (1)); Proc.Output := Create_Stream (Stdout_Pipes (0)).all'Access; end if; if Stderr_Pipes (0) /= NO_FILE then Result := Sys_Close (Stderr_Pipes (1)); Proc.Error := Create_Stream (Stderr_Pipes (0)).all'Access; end if; end Spawn; procedure Free is new Ada.Unchecked_Deallocation (Name => Ptr_Ptr_Array, Object => Ptr_Array); -- ------------------------------ -- Append the argument to the process argument list. -- ------------------------------ overriding procedure Append_Argument (Sys : in out System_Process; Arg : in String) is begin if Sys.Argv = null then Sys.Argv := new Ptr_Array (0 .. 10); elsif Sys.Argc = Sys.Argv'Last - 1 then declare N : constant Ptr_Ptr_Array := new Ptr_Array (0 .. Sys.Argc + 32); begin N (0 .. Sys.Argc) := Sys.Argv (0 .. Sys.Argc); Free (Sys.Argv); Sys.Argv := N; end; end if; Sys.Argv (Sys.Argc) := Interfaces.C.Strings.New_String (Arg); Sys.Argc := Sys.Argc + 1; Sys.Argv (Sys.Argc) := Interfaces.C.Strings.Null_Ptr; end Append_Argument; -- ------------------------------ -- Set the process input, output and error streams to redirect and use specified files. -- ------------------------------ overriding procedure Set_Streams (Sys : in out System_Process; Input : in String; Output : in String; Error : in String; Append_Output : in Boolean; Append_Error : in Boolean) is begin if Input'Length > 0 then Sys.In_File := Interfaces.C.Strings.New_String (Input); end if; if Output'Length > 0 then Sys.Out_File := Interfaces.C.Strings.New_String (Output); Sys.Out_Append := Append_Output; end if; if Error'Length > 0 then Sys.Err_File := Interfaces.C.Strings.New_String (Error); Sys.Err_Append := Append_Error; end if; end Set_Streams; -- ------------------------------ -- Deletes the storage held by the system process. -- ------------------------------ overriding procedure Finalize (Sys : in out System_Process) is begin if Sys.Argv /= null then for I in Sys.Argv'Range loop Interfaces.C.Strings.Free (Sys.Argv (I)); end loop; Free (Sys.Argv); end if; Interfaces.C.Strings.Free (Sys.In_File); Interfaces.C.Strings.Free (Sys.Out_File); Interfaces.C.Strings.Free (Sys.Err_File); end Finalize; end Util.Processes.Os;
----------------------------------------------------------------------- -- util-processes-os -- System specific and low level operations -- 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.Unchecked_Deallocation; package body Util.Processes.Os is use Util.Systems.Os; use type Interfaces.C.size_t; type Pipe_Type is array (0 .. 1) of File_Type; procedure Close (Pipes : in out Pipe_Type); -- ------------------------------ -- Create the output stream to read/write on the process input/output. -- Setup the file to be closed on exec. -- ------------------------------ function Create_Stream (File : in File_Type) return Util.Streams.Raw.Raw_Stream_Access is Stream : constant Util.Streams.Raw.Raw_Stream_Access := new Util.Streams.Raw.Raw_Stream; Status : constant Integer := Sys_Fcntl (File, F_SETFL, FD_CLOEXEC); pragma Unreferenced (Status); begin Stream.Initialize (File); return Stream; end Create_Stream; -- ------------------------------ -- Wait for the process to exit. -- ------------------------------ overriding procedure Wait (Sys : in out System_Process; Proc : in out Process'Class; Timeout : in Duration) is pragma Unreferenced (Sys, Timeout); use type Util.Streams.Output_Stream_Access; Result : Integer; Wpid : Integer; begin -- Close the input stream pipe if there is one. if Proc.Input /= null then Util.Streams.Raw.Raw_Stream'Class (Proc.Input.all).Close; end if; Wpid := Sys_Waitpid (Integer (Proc.Pid), Result'Address, 0); if Wpid = Integer (Proc.Pid) then Proc.Exit_Value := Result / 256; if Result mod 256 /= 0 then Proc.Exit_Value := (Result mod 256) * 1000; end if; end if; end Wait; -- ------------------------------ -- Terminate the process by sending a signal on Unix and exiting the process on Windows. -- This operation is not portable and has a different behavior between Unix and Windows. -- Its intent is to stop the process. -- ------------------------------ overriding procedure Stop (Sys : in out System_Process; Proc : in out Process'Class; Signal : in Positive := 15) is pragma Unreferenced (Sys); Result : Integer; pragma Unreferenced (Result); begin Result := Sys_Kill (Integer (Proc.Pid), Integer (Signal)); end Stop; -- ------------------------------ -- Close both ends of the pipe (used to cleanup in case or error). -- ------------------------------ procedure Close (Pipes : in out Pipe_Type) is Result : Integer; pragma Unreferenced (Result); begin if Pipes (0) /= NO_FILE then Result := Sys_Close (Pipes (0)); Pipes (0) := NO_FILE; end if; if Pipes (1) /= NO_FILE then Result := Sys_Close (Pipes (1)); Pipes (1) := NO_FILE; end if; end Close; -- ------------------------------ -- Spawn a new process. -- ------------------------------ overriding procedure Spawn (Sys : in out System_Process; Proc : in out Process'Class; Mode : in Pipe_Mode := NONE) is use Util.Streams.Raw; use Interfaces.C.Strings; use type Interfaces.C.int; procedure Cleanup; -- Suppress all checks to make sure the child process will not raise any exception. pragma Suppress (All_Checks); Result : Integer; pragma Unreferenced (Result); Stdin_Pipes : aliased Pipe_Type := (others => NO_FILE); Stdout_Pipes : aliased Pipe_Type := (others => NO_FILE); Stderr_Pipes : aliased Pipe_Type := (others => NO_FILE); procedure Cleanup is begin Close (Stdin_Pipes); Close (Stdout_Pipes); Close (Stderr_Pipes); end Cleanup; begin -- Since checks are disabled, verify by hand that the argv table is correct. if Sys.Argv = null or else Sys.Argc < 1 or else Sys.Argv (0) = Null_Ptr then raise Program_Error with "Invalid process argument list"; end if; -- Setup the pipes. if Mode = READ or Mode = READ_WRITE or Mode = READ_ALL then if Sys_Pipe (Stdout_Pipes'Address) /= 0 then raise Process_Error with "Cannot create stdout pipe"; end if; end if; if Mode = WRITE or Mode = READ_WRITE or Mode = READ_WRITE_ALL then if Sys_Pipe (Stdin_Pipes'Address) /= 0 then Cleanup; raise Process_Error with "Cannot create stdin pipe"; end if; end if; if Mode = READ_ERROR then if Sys_Pipe (Stderr_Pipes'Address) /= 0 then Cleanup; raise Process_Error with "Cannot create stderr pipe"; end if; end if; -- Create the new process by using vfork instead of fork. The parent process is blocked -- until the child executes the exec or exits. The child process uses the same stack -- as the parent. Proc.Pid := Sys_VFork; if Proc.Pid = 0 then -- Do not use any Ada type while in the child process. if Mode = READ_ALL or Mode = READ_WRITE_ALL then Result := Sys_Dup2 (Stdout_Pipes (1), STDERR_FILENO); end if; if Stderr_Pipes (1) /= NO_FILE then if Stderr_Pipes (1) /= STDERR_FILENO then Result := Sys_Dup2 (Stderr_Pipes (1), STDERR_FILENO); Result := Sys_Close (Stderr_Pipes (1)); end if; Result := Sys_Close (Stderr_Pipes (0)); elsif Sys.Err_File /= Null_Ptr then -- Redirect the process error to a file. declare Fd : File_Type; begin if Sys.Err_Append then Fd := Sys_Open (Sys.Err_File, O_CREAT + O_WRONLY + O_APPEND, 8#644#); else Fd := Sys_Open (Sys.Err_File, O_CREAT + O_WRONLY + O_TRUNC, 8#644#); end if; if Fd < 0 then Sys_Exit (254); end if; Result := Sys_Dup2 (Fd, STDOUT_FILENO); Result := Sys_Close (Fd); end; end if; if Stdout_Pipes (1) /= NO_FILE then if Stdout_Pipes (1) /= STDOUT_FILENO then Result := Sys_Dup2 (Stdout_Pipes (1), STDOUT_FILENO); Result := Sys_Close (Stdout_Pipes (1)); end if; Result := Sys_Close (Stdout_Pipes (0)); elsif Sys.Out_File /= Null_Ptr then -- Redirect the process output to a file. declare Fd : File_Type; begin if Sys.Out_Append then Fd := Sys_Open (Sys.Out_File, O_CREAT + O_WRONLY + O_APPEND, 8#644#); else Fd := Sys_Open (Sys.Out_File, O_CREAT + O_WRONLY + O_TRUNC, 8#644#); end if; if Fd < 0 then Sys_Exit (254); end if; Result := Sys_Dup2 (Fd, STDOUT_FILENO); Result := Sys_Close (Fd); end; end if; if Stdin_Pipes (0) /= NO_FILE then if Stdin_Pipes (0) /= STDIN_FILENO then Result := Sys_Dup2 (Stdin_Pipes (0), STDIN_FILENO); Result := Sys_Close (Stdin_Pipes (0)); end if; Result := Sys_Close (Stdin_Pipes (1)); elsif Sys.In_File /= Null_Ptr then -- Redirect the process input from a file. declare Fd : File_Type; begin Fd := Sys_Open (Sys.In_File, O_RDONLY, 8#644#); if Fd < 0 then Sys_Exit (254); end if; Result := Sys_Dup2 (Fd, STDIN_FILENO); Result := Sys_Close (Fd); end; end if; Result := Sys_Execvp (Sys.Argv (0), Sys.Argv.all); Sys_Exit (255); end if; -- Process creation failed, cleanup and raise an exception. if Proc.Pid < 0 then Cleanup; raise Process_Error with "Cannot create process"; end if; if Stdin_Pipes (1) /= NO_FILE then Result := Sys_Close (Stdin_Pipes (0)); Proc.Input := Create_Stream (Stdin_Pipes (1)).all'Access; end if; if Stdout_Pipes (0) /= NO_FILE then Result := Sys_Close (Stdout_Pipes (1)); Proc.Output := Create_Stream (Stdout_Pipes (0)).all'Access; end if; if Stderr_Pipes (0) /= NO_FILE then Result := Sys_Close (Stderr_Pipes (1)); Proc.Error := Create_Stream (Stderr_Pipes (0)).all'Access; end if; end Spawn; procedure Free is new Ada.Unchecked_Deallocation (Name => Ptr_Ptr_Array, Object => Ptr_Array); -- ------------------------------ -- Append the argument to the process argument list. -- ------------------------------ overriding procedure Append_Argument (Sys : in out System_Process; Arg : in String) is begin if Sys.Argv = null then Sys.Argv := new Ptr_Array (0 .. 10); elsif Sys.Argc = Sys.Argv'Last - 1 then declare N : constant Ptr_Ptr_Array := new Ptr_Array (0 .. Sys.Argc + 32); begin N (0 .. Sys.Argc) := Sys.Argv (0 .. Sys.Argc); Free (Sys.Argv); Sys.Argv := N; end; end if; Sys.Argv (Sys.Argc) := Interfaces.C.Strings.New_String (Arg); Sys.Argc := Sys.Argc + 1; Sys.Argv (Sys.Argc) := Interfaces.C.Strings.Null_Ptr; end Append_Argument; -- ------------------------------ -- Set the process input, output and error streams to redirect and use specified files. -- ------------------------------ overriding procedure Set_Streams (Sys : in out System_Process; Input : in String; Output : in String; Error : in String; Append_Output : in Boolean; Append_Error : in Boolean) is begin if Input'Length > 0 then Sys.In_File := Interfaces.C.Strings.New_String (Input); end if; if Output'Length > 0 then Sys.Out_File := Interfaces.C.Strings.New_String (Output); Sys.Out_Append := Append_Output; end if; if Error'Length > 0 then Sys.Err_File := Interfaces.C.Strings.New_String (Error); Sys.Err_Append := Append_Error; end if; end Set_Streams; -- ------------------------------ -- Deletes the storage held by the system process. -- ------------------------------ overriding procedure Finalize (Sys : in out System_Process) is begin if Sys.Argv /= null then for I in Sys.Argv'Range loop Interfaces.C.Strings.Free (Sys.Argv (I)); end loop; Free (Sys.Argv); end if; Interfaces.C.Strings.Free (Sys.In_File); Interfaces.C.Strings.Free (Sys.Out_File); Interfaces.C.Strings.Free (Sys.Err_File); end Finalize; end Util.Processes.Os;
Fix the Input_Stream redirection from a file
Fix the Input_Stream redirection from a file
Ada
apache-2.0
stcarrez/ada-util,stcarrez/ada-util
eeff3cb26e8ce661523b7d33df1376d1b334b4ad
src/instruction.ads
src/instruction.ads
package Instruction is end package;
Add instruction package
Add instruction package
Ada
mit
peterfrankjohnson/assembler
c30869fe376785704006a751ec3f8678278e7ba3
src/sys/measures/util-measures.adb
src/sys/measures/util-measures.adb
----------------------------------------------------------------------- -- measure -- Benchmark tools -- Copyright (C) 2008 - 2019 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Task_Attributes; with Ada.Strings.Hash; with Ada.Unchecked_Deallocation; with GNAT.Calendar.Time_IO; with Util.Streams.Buffered; with Util.Streams.Texts.TR; package body Util.Measures is ISO_DATE_TIME : constant GNAT.Calendar.Time_IO.Picture_String := "%Y-%m-%d %H:%M:%S"; procedure Free is new Ada.Unchecked_Deallocation (Buckets_Type, Buckets_Access); procedure Free is new Ada.Unchecked_Deallocation (Measure, Measure_Access); procedure Free is new Ada.Unchecked_Deallocation (String, String_Access); package Task_Context is new Ada.Task_Attributes (Measure_Set_Access, null); function Format (D : in Duration) return String; -- Format the duration in a time in 'ns', 'us', 'ms' or seconds. function Format (D : in Duration; Unit : in Unit_Type) return String; -- ------------------------------ -- Disable collecting measures on the measure set. -- ------------------------------ procedure Disable (Measures : in out Measure_Set) is begin Measures.Enabled := False; end Disable; -- ------------------------------ -- Enable collecting measures on the measure set. -- ------------------------------ procedure Enable (Measures : in out Measure_Set) is begin Measures.Enabled := True; end Enable; -- ------------------------------ -- Set the per-thread measure set. -- ------------------------------ procedure Set_Current (Measures : in Measure_Set_Access) is begin Task_Context.Set_Value (Measures); end Set_Current; -- ------------------------------ -- Get the per-thread measure set. -- ------------------------------ function Get_Current return Measure_Set_Access is begin return Task_Context.Value; end Get_Current; -- ------------------------------ -- Dump an XML result with the measures collected by the measure set. -- When writing the measures, the measure set is cleared. It is safe -- to write measures while other measures are being collected. -- ------------------------------ procedure Write (Measures : in out Measure_Set; Title : in String; Stream : in out Util.Streams.Texts.Print_Stream'Class) is procedure Dump_XML (Item : in Measure_Access); procedure Dump_XML (Item : in Measure_Access) is Total : constant String := Format (Item.Time); Time : constant String := Format (Item.Time / Item.Count); begin Stream.Write ("<time count="""); Stream.Write (Item.Count); Stream.Write (""" time="""); Stream.Write (Time (Time'First + 1 .. Time'Last)); if Item.Count > 1 then Stream.Write (""" total="""); Stream.Write (Total (Total'First + 1 .. Total'Last)); end if; Stream.Write (""" title="""); Util.Streams.Texts.TR.Escape_Java_Script (Into => Stream, Content => Item.Name.all); Stream.Write ("""/>"); Stream.Write (ASCII.LF); end Dump_XML; Buckets : Buckets_Access; TS, TE : Ada.Calendar.Time; begin Measures.Data.Steal_Map (Buckets, TS, TE); Stream.Write ("<measures title="""); Util.Streams.Texts.TR.Escape_Java_Script (Into => Stream, Content => Title); Stream.Write (""" start="""); Stream.Write (TS, ISO_DATE_TIME); Stream.Write (""" end="""); Stream.Write (TE, ISO_DATE_TIME); Stream.Write (""">"); if Buckets /= null then Stream.Write (ASCII.LF); begin for I in Buckets'Range loop declare Next : Measure_Access; Node : Measure_Access := Buckets (I); begin while Node /= null loop Dump_XML (Node); Free (Node.Name); Next := Node.Next; Free (Node); Node := Next; end loop; end; end loop; exception when others => Free (Buckets); raise; end; Free (Buckets); end if; Stream.Write ("</measures>"); end Write; -- ------------------------------ -- Dump an XML result with the measures collected by the measure set. -- ------------------------------ procedure Write (Measures : in out Measure_Set; Title : in String; Stream : in Ada.Text_IO.File_Type) is Buffer : aliased Util.Streams.Buffered.Output_Buffer_Stream; Output : Util.Streams.Texts.Print_Stream; begin Buffer.Initialize (Size => 128 * 1024); Output.Initialize (To => Buffer'Access); Write (Measures, Title, Output); Output.Flush; Ada.Text_IO.Put_Line (Stream, Util.Streams.Texts.To_String (Buffer)); end Write; -- ------------------------------ -- Dump an XML result with the measures in a file. -- ------------------------------ procedure Write (Measures : in out Measure_Set; Title : in String; Path : in String) is File : Ada.Text_IO.File_Type; begin Ada.Text_IO.Create (File => File, Name => Path); Write (Measures, Title, File); Ada.Text_IO.Close (File); exception when others => if Ada.Text_IO.Is_Open (File) then Ada.Text_IO.Close (File); end if; raise; end Write; -- ------------------------------ -- Report the time spent between the stamp creation and this method call. -- Collect the result in the per-thread measure set under the given measure -- title. -- ------------------------------ procedure Report (S : in out Stamp; Title : in String; Count : in Positive := 1) is Measures : constant Measure_Set_Access := Task_Context.Value; begin if Measures /= null and then Measures.Enabled then Report (Measures.all, S, Title, Count); end if; end Report; -- ------------------------------ -- Report the time spent between the stamp creation and this method call. -- Collect the result in the measure set under the given measure title. -- ------------------------------ procedure Report (Measures : in out Measure_Set; S : in out Stamp; Title : in String; Count : in Positive := 1) is use Ada.Calendar; begin if Measures.Enabled then declare D : constant Duration := Ada.Calendar.Clock - S.Start; begin Measures.Data.Add (Title, D, Count); end; S.Start := Ada.Calendar.Clock; end if; end Report; -- ------------------------------ -- Report the time spent between the stamp creation and this method call. -- The report is written in the file with the given title. The duration is -- expressed in the unit defined in <tt>Unit</tt>. -- ------------------------------ procedure Report (S : in out Stamp; File : in out Ada.Text_IO.File_Type; Title : in String; Unit : in Unit_Type := Microseconds) is use Ada.Calendar; D : constant Duration := Ada.Calendar.Clock - S.Start; begin Ada.Text_IO.Put (File, Title); Ada.Text_IO.Put (File, Format (D, Unit)); S.Start := Ada.Calendar.Clock; end Report; protected body Measure_Data is -- ------------------------------ -- Get the measures and clear to start a new set of measures. -- Return in <b>Time_Start</b> and <b>Time_End</b> the period of time. -- ------------------------------ procedure Steal_Map (Result : out Buckets_Access; Time_Start : out Ada.Calendar.Time; Time_End : out Ada.Calendar.Time) is begin Result := Buckets; Time_Start := Start; Start := Ada.Calendar.Clock; Time_End := Start; Buckets := null; end Steal_Map; -- ------------------------------ -- Add the measure -- ------------------------------ procedure Add (Title : in String; D : in Duration; Count : in Positive := 1) is use Ada.Containers; Pos : Hash_Type; Node : Measure_Access; begin if Buckets = null then Buckets := new Buckets_Type (0 .. 256); end if; Pos := Ada.Strings.Hash (Title) mod Buckets'Length; Node := Buckets (Pos); while Node /= null loop if Node.Name'Length = Title'Length and then Node.Name.all = Title then Node.Count := Node.Count + Count; Node.Time := Node.Time + D; return; end if; Node := Node.Next; end loop; Buckets (Pos) := new Measure '(Name => new String '(Title), Time => D, Count => Count, Next => Buckets (Pos)); end Add; end Measure_Data; -- ------------------------------ -- Format the duration in a time in 'ns', 'us', 'ms' or seconds. -- ------------------------------ function Format (D : in Duration) return String is begin if D < 0.000_001 then return Duration'Image (D * 1_000_000_000) (1 .. 6) & " ns"; elsif D < 0.001 then return Duration'Image (D * 1_000_000) (1 .. 6) & " us"; elsif D < 1.0 then return Duration'Image (D * 1_000) (1 .. 6) & " ms"; else return Duration'Image (D) (1 .. 6) & " s"; end if; end Format; -- ------------------------------ -- Format the duration in a time in 'ns', 'us', 'ms' or seconds. -- ------------------------------ function Format (D : in Duration; Unit : in Unit_Type) return String is begin case Unit is when Seconds => return Duration'Image (D); when Milliseconds => return Duration'Image (D * 1_000); when Microseconds => return Duration'Image (D * 1_000_000); when Nanoseconds => return Duration'Image (D * 1_000_000_000); end case; end Format; -- ------------------------------ -- Finalize the measures and release the storage. -- ------------------------------ overriding procedure Finalize (Measures : in out Measure_Set) is Buckets : Buckets_Access; TS, TE : Ada.Calendar.Time; begin -- When deleting the measure set, we have to release the buckets and measures -- that were allocated. We could call <b>Write</b> but we don't know where -- the measures have to be written. Measures.Data.Steal_Map (Buckets, TS, TE); if Buckets /= null then for I in Buckets'Range loop declare Next : Measure_Access; Node : Measure_Access := Buckets (I); begin while Node /= null loop Free (Node.Name); Next := Node.Next; Free (Node); Node := Next; end loop; end; end loop; Free (Buckets); end if; end Finalize; end Util.Measures;
----------------------------------------------------------------------- -- measure -- Benchmark tools -- Copyright (C) 2008 - 2019, 2021 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Task_Attributes; with Ada.Strings.Hash; with Ada.Unchecked_Deallocation; with GNAT.Calendar.Time_IO; with Util.Streams.Buffered; with Util.Streams.Texts.TR; package body Util.Measures is ISO_DATE_TIME : constant GNAT.Calendar.Time_IO.Picture_String := "%Y-%m-%d %H:%M:%S"; procedure Free is new Ada.Unchecked_Deallocation (Buckets_Type, Buckets_Access); procedure Free is new Ada.Unchecked_Deallocation (Measure, Measure_Access); procedure Free is new Ada.Unchecked_Deallocation (String, String_Access); package Task_Context is new Ada.Task_Attributes (Measure_Set_Access, null); function Format (D : in Duration) return String; -- Format the duration in a time in 'ns', 'us', 'ms' or seconds. function Format (D : in Duration; Unit : in Unit_Type) return String; -- ------------------------------ -- Disable collecting measures on the measure set. -- ------------------------------ procedure Disable (Measures : in out Measure_Set) is begin Measures.Enabled := False; end Disable; -- ------------------------------ -- Enable collecting measures on the measure set. -- ------------------------------ procedure Enable (Measures : in out Measure_Set) is begin Measures.Enabled := True; end Enable; -- ------------------------------ -- Set the per-thread measure set. -- ------------------------------ procedure Set_Current (Measures : in Measure_Set_Access) is begin Task_Context.Set_Value (Measures); end Set_Current; -- ------------------------------ -- Get the per-thread measure set. -- ------------------------------ function Get_Current return Measure_Set_Access is begin return Task_Context.Value; end Get_Current; -- ------------------------------ -- Dump an XML result with the measures collected by the measure set. -- When writing the measures, the measure set is cleared. It is safe -- to write measures while other measures are being collected. -- ------------------------------ procedure Write (Measures : in out Measure_Set; Title : in String; Stream : in out Util.Streams.Texts.Print_Stream'Class) is procedure Dump_XML (Item : in Measure_Access); procedure Dump_XML (Item : in Measure_Access) is Total : constant String := Format (Item.Time); Time : constant String := Format (Item.Time / Item.Count); begin Stream.Write ("<time count="""); Stream.Write (Item.Count); Stream.Write (""" time="""); Stream.Write (Time (Time'First + 1 .. Time'Last)); if Item.Count > 1 then Stream.Write (""" total="""); Stream.Write (Total (Total'First + 1 .. Total'Last)); end if; Stream.Write (""" title="""); Util.Streams.Texts.TR.Escape_Java_Script (Into => Stream, Content => Item.Name.all); Stream.Write ("""/>"); Stream.Write (ASCII.LF); end Dump_XML; Buckets : Buckets_Access; TS, TE : Ada.Calendar.Time; begin Measures.Data.Steal_Map (Buckets, TS, TE); Stream.Write ("<measures title="""); Util.Streams.Texts.TR.Escape_Java_Script (Into => Stream, Content => Title); Stream.Write (""" start="""); Stream.Write (TS, ISO_DATE_TIME); Stream.Write (""" end="""); Stream.Write (TE, ISO_DATE_TIME); Stream.Write (""">"); if Buckets /= null then Stream.Write (ASCII.LF); begin for I in Buckets'Range loop declare Next : Measure_Access; Node : Measure_Access := Buckets (I); begin while Node /= null loop Dump_XML (Node); Free (Node.Name); Next := Node.Next; Free (Node); Node := Next; end loop; end; end loop; exception when others => Free (Buckets); raise; end; Free (Buckets); end if; Stream.Write ("</measures>"); end Write; -- ------------------------------ -- Dump an XML result with the measures collected by the measure set. -- ------------------------------ procedure Write (Measures : in out Measure_Set; Title : in String; Stream : in Ada.Text_IO.File_Type) is Buffer : aliased Util.Streams.Buffered.Output_Buffer_Stream; Output : Util.Streams.Texts.Print_Stream; begin Buffer.Initialize (Size => 128 * 1024); Output.Initialize (To => Buffer'Unchecked_Access); Write (Measures, Title, Output); Output.Flush; Ada.Text_IO.Put_Line (Stream, Util.Streams.Texts.To_String (Buffer)); end Write; -- ------------------------------ -- Dump an XML result with the measures in a file. -- ------------------------------ procedure Write (Measures : in out Measure_Set; Title : in String; Path : in String) is File : Ada.Text_IO.File_Type; begin Ada.Text_IO.Create (File => File, Name => Path); Write (Measures, Title, File); Ada.Text_IO.Close (File); exception when others => if Ada.Text_IO.Is_Open (File) then Ada.Text_IO.Close (File); end if; raise; end Write; -- ------------------------------ -- Report the time spent between the stamp creation and this method call. -- Collect the result in the per-thread measure set under the given measure -- title. -- ------------------------------ procedure Report (S : in out Stamp; Title : in String; Count : in Positive := 1) is Measures : constant Measure_Set_Access := Task_Context.Value; begin if Measures /= null and then Measures.Enabled then Report (Measures.all, S, Title, Count); end if; end Report; -- ------------------------------ -- Report the time spent between the stamp creation and this method call. -- Collect the result in the measure set under the given measure title. -- ------------------------------ procedure Report (Measures : in out Measure_Set; S : in out Stamp; Title : in String; Count : in Positive := 1) is use Ada.Calendar; begin if Measures.Enabled then declare D : constant Duration := Ada.Calendar.Clock - S.Start; begin Measures.Data.Add (Title, D, Count); end; S.Start := Ada.Calendar.Clock; end if; end Report; -- ------------------------------ -- Report the time spent between the stamp creation and this method call. -- The report is written in the file with the given title. The duration is -- expressed in the unit defined in <tt>Unit</tt>. -- ------------------------------ procedure Report (S : in out Stamp; File : in out Ada.Text_IO.File_Type; Title : in String; Unit : in Unit_Type := Microseconds) is use Ada.Calendar; D : constant Duration := Ada.Calendar.Clock - S.Start; begin Ada.Text_IO.Put (File, Title); Ada.Text_IO.Put (File, Format (D, Unit)); S.Start := Ada.Calendar.Clock; end Report; protected body Measure_Data is -- ------------------------------ -- Get the measures and clear to start a new set of measures. -- Return in <b>Time_Start</b> and <b>Time_End</b> the period of time. -- ------------------------------ procedure Steal_Map (Result : out Buckets_Access; Time_Start : out Ada.Calendar.Time; Time_End : out Ada.Calendar.Time) is begin Result := Buckets; Time_Start := Start; Start := Ada.Calendar.Clock; Time_End := Start; Buckets := null; end Steal_Map; -- ------------------------------ -- Add the measure -- ------------------------------ procedure Add (Title : in String; D : in Duration; Count : in Positive := 1) is use Ada.Containers; Pos : Hash_Type; Node : Measure_Access; begin if Buckets = null then Buckets := new Buckets_Type (0 .. 256); end if; Pos := Ada.Strings.Hash (Title) mod Buckets'Length; Node := Buckets (Pos); while Node /= null loop if Node.Name'Length = Title'Length and then Node.Name.all = Title then Node.Count := Node.Count + Count; Node.Time := Node.Time + D; return; end if; Node := Node.Next; end loop; Buckets (Pos) := new Measure '(Name => new String '(Title), Time => D, Count => Count, Next => Buckets (Pos)); end Add; end Measure_Data; -- ------------------------------ -- Format the duration in a time in 'ns', 'us', 'ms' or seconds. -- ------------------------------ function Format (D : in Duration) return String is begin if D < 0.000_001 then return Duration'Image (D * 1_000_000_000) (1 .. 6) & " ns"; elsif D < 0.001 then return Duration'Image (D * 1_000_000) (1 .. 6) & " us"; elsif D < 1.0 then return Duration'Image (D * 1_000) (1 .. 6) & " ms"; else return Duration'Image (D) (1 .. 6) & " s"; end if; end Format; -- ------------------------------ -- Format the duration in a time in 'ns', 'us', 'ms' or seconds. -- ------------------------------ function Format (D : in Duration; Unit : in Unit_Type) return String is begin case Unit is when Seconds => return Duration'Image (D); when Milliseconds => return Duration'Image (D * 1_000); when Microseconds => return Duration'Image (D * 1_000_000); when Nanoseconds => return Duration'Image (D * 1_000_000_000); end case; end Format; -- ------------------------------ -- Finalize the measures and release the storage. -- ------------------------------ overriding procedure Finalize (Measures : in out Measure_Set) is Buckets : Buckets_Access; TS, TE : Ada.Calendar.Time; begin -- When deleting the measure set, we have to release the buckets and measures -- that were allocated. We could call <b>Write</b> but we don't know where -- the measures have to be written. Measures.Data.Steal_Map (Buckets, TS, TE); if Buckets /= null then for I in Buckets'Range loop declare Next : Measure_Access; Node : Measure_Access := Buckets (I); begin while Node /= null loop Free (Node.Name); Next := Node.Next; Free (Node); Node := Next; end loop; end; end loop; Free (Buckets); end if; end Finalize; end Util.Measures;
Fix execution with GNAT 2021: use Unchecked_Access because the accessibility rules are hardened
Fix execution with GNAT 2021: use Unchecked_Access because the accessibility rules are hardened
Ada
apache-2.0
stcarrez/ada-util,stcarrez/ada-util
7c40bc316e1b39173674bc6622038ba384e1781c
src/util-concurrent-pools.adb
src/util-concurrent-pools.adb
----------------------------------------------------------------------- -- Util.Concurrent.Pools -- Concurrent Pools -- 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 Ada.Unchecked_Deallocation; package body Util.Concurrent.Pools is -- ------------------------------ -- Get an element instance from the pool. -- Wait until one instance gets available. -- ------------------------------ procedure Get_Instance (From : in out Pool; Item : out Element_Type) is begin From.List.Get_Instance (Item); end Get_Instance; -- ------------------------------ -- Put the element back to the pool. -- ------------------------------ procedure Release (Into : in out Pool; Item : in Element_Type) is begin Into.List.Release (Item); end Release; -- ------------------------------ -- Set the pool size. -- ------------------------------ procedure Set_Size (Into : in out Pool; Capacity : in Positive) is begin Into.List.Set_Size (Capacity); end Set_Size; -- ------------------------------ -- Release the pool elements. -- ------------------------------ overriding procedure Finalize (Object : in out Pool) is begin Object.List.Set_Size (0); end Finalize; -- Pool of objects protected body Protected_Pool is -- ------------------------------ -- Get an element instance from the pool. -- Wait until one instance gets available. -- ------------------------------ entry Get_Instance (Item : out Element_Type) when Available > 0 is begin Item := Elements (Available); Available := Available - 1; end Get_Instance; -- ------------------------------ -- Put the element back to the pool. -- ------------------------------ procedure Release (Item : in Element_Type) is begin Available := Available + 1; Elements (Available) := Item; end Release; -- ------------------------------ -- Set the pool size. -- ------------------------------ procedure Set_Size (Capacity : in Natural) is procedure Free is new Ada.Unchecked_Deallocation (Element_Array, Element_Array_Access); begin if Capacity = 0 then Free (Elements); elsif Elements = null then Elements := new Element_Array (1 .. Capacity); else declare New_Array : Element_Array_Access := new Element_Array (1 .. Capacity); begin if Capacity > Elements'Size then New_Array (1 .. Elements'Last) := Elements (1 .. Elements'Last); else New_Array (1 .. Capacity) := Elements (1 .. Capacity); end if; Free (Elements); Elements := New_Array; end; end if; end Set_Size; end Protected_Pool; end Util.Concurrent.Pools;
----------------------------------------------------------------------- -- Util.Concurrent.Pools -- Concurrent Pools -- Copyright (C) 2011, 2014 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Unchecked_Deallocation; package body Util.Concurrent.Pools is -- ------------------------------ -- Get an element instance from the pool. -- Wait until one instance gets available. -- ------------------------------ procedure Get_Instance (From : in out Pool; Item : out Element_Type) is begin From.List.Get_Instance (Item); end Get_Instance; -- ------------------------------ -- Put the element back to the pool. -- ------------------------------ procedure Release (Into : in out Pool; Item : in Element_Type) is begin Into.List.Release (Item); end Release; -- ------------------------------ -- Set the pool size. -- ------------------------------ procedure Set_Size (Into : in out Pool; Capacity : in Positive) is begin Into.List.Set_Size (Capacity); end Set_Size; -- ------------------------------ -- Release the pool elements. -- ------------------------------ overriding procedure Finalize (Object : in out Pool) is begin Object.List.Set_Size (0); end Finalize; -- Pool of objects protected body Protected_Pool is -- ------------------------------ -- Get an element instance from the pool. -- Wait until one instance gets available. -- ------------------------------ entry Get_Instance (Item : out Element_Type) when Available > 0 is begin Item := Elements (Available); Available := Available - 1; end Get_Instance; -- ------------------------------ -- Put the element back to the pool. -- ------------------------------ procedure Release (Item : in Element_Type) is begin Available := Available + 1; Elements (Available) := Item; end Release; -- ------------------------------ -- Set the pool size. -- ------------------------------ procedure Set_Size (Capacity : in Natural) is procedure Free is new Ada.Unchecked_Deallocation (Element_Array, Element_Array_Access); begin if Capacity = 0 then Free (Elements); elsif Elements = null then Elements := new Element_Array (1 .. Capacity); else declare New_Array : constant Element_Array_Access := new Element_Array (1 .. Capacity); begin if Capacity > Elements'Size then New_Array (1 .. Elements'Last) := Elements (1 .. Elements'Last); else New_Array (1 .. Capacity) := Elements (1 .. Capacity); end if; Free (Elements); Elements := New_Array; end; end if; end Set_Size; end Protected_Pool; end Util.Concurrent.Pools;
Fix compilation warning
Fix compilation warning
Ada
apache-2.0
stcarrez/ada-util,stcarrez/ada-util
d19ec489ef55dc38a88000ab0a4fa2aeffa92936
orka_transforms/src/orka-transforms-simd_vectors.adb
orka_transforms/src/orka-transforms-simd_vectors.adb
-- SPDX-License-Identifier: Apache-2.0 -- -- Copyright (c) 2017 onox <[email protected]> -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. with Ada.Numerics.Generic_Elementary_Functions; package body Orka.Transforms.SIMD_Vectors is function "-" (Elements : Point) return Point is Result : Vector4 := -Vector4 (Elements); begin Result (W) := Elements (W); return Point (Result); end "-"; function "+" (Left, Right : Direction) return Direction is (Direction (Vector4 (Left) + Vector4 (Right))); function "+" (Left : Point; Right : Direction) return Point is (Point (Vector4 (Left) + Vector4 (Right))); function "+" (Left : Direction; Right : Point) return Point is (Point (Vector4 (Left) + Vector4 (Right))); function "-" (Left, Right : Point) return Direction is (Direction (Vector4 (Left) - Vector4 (Right))); ---------------------------------------------------------------------------- package EF is new Ada.Numerics.Generic_Elementary_Functions (Element_Type); function Magnitude2 (Elements : Vector_Type) return Element_Type is (Sum (Elements * Elements)); function "*" (Factor : Element_Type; Elements : Vector_Type) return Vector_Type is begin return (Factor, Factor, Factor, Factor) * Elements; end "*"; function "*" (Elements : Vector_Type; Factor : Element_Type) return Vector_Type is (Factor * Elements); function "*" (Factor : Element_Type; Elements : Direction) return Direction is (Direction (Factor * Vector4 (Elements))); function "*" (Elements : Direction; Factor : Element_Type) return Direction is (Factor * Elements); function Magnitude (Elements : Vector_Type) return Element_Type is begin return EF.Sqrt (Magnitude2 (Elements)); end Magnitude; function Normalize (Elements : Vector_Type) return Vector_Type is Length : constant Element_Type := Magnitude (Elements); begin return Divide_Or_Zero (Elements, (Length, Length, Length, Length)); end Normalize; function Normalized (Elements : Vector_Type) return Boolean is function Is_Equivalent (Expected, Result : Element_Type) return Boolean is -- Because the square root is not computed, the bounds need -- to be increased to +/- 2 * Epsilon + Epsilon ** 2. Since -- Epsilon < 1, we can simply take +/- 3 * Epsilon Epsilon : constant Element_Type := 3.0 * Element_Type'Model_Epsilon; begin return Result in Expected - Epsilon .. Expected + Epsilon; end Is_Equivalent; begin return Is_Equivalent (1.0, Magnitude2 (Elements)); end Normalized; function Distance (Left, Right : Point) return Element_Type is (Magnitude (Vector_Type (Left - Right))); function Projection (Elements, Direction : Vector_Type) return Vector_Type is Unit_Direction : constant Vector_Type := Normalize (Direction); begin -- The dot product gives the magnitude of the projected vector: -- |A_b| = |A| * cos(theta) = A . U_b return Dot (Elements, Unit_Direction) * Unit_Direction; end Projection; function Perpendicular (Elements, Direction : Vector_Type) return Vector_Type is (Elements - Projection (Elements, Direction)); function Angle (Left, Right : Vector_Type) return Element_Type is begin return EF.Arccos (Dot (Left, Right) / (Magnitude (Left) * Magnitude (Right))); end Angle; function Dot (Left, Right : Vector_Type) return Element_Type is (Sum (Left * Right)); function Slerp (Left, Right : Vector_Type; Weight : Element_Type) return Vector_Type is Cos_Angle : constant Element_Type := Dot (Left, Right); Angle : constant Element_Type := EF.Arccos (Cos_Angle); SA : constant Element_Type := EF.Sin (Angle); SL : constant Element_Type := EF.Sin ((1.0 - Weight) * Angle); SR : constant Element_Type := EF.Sin (Weight * Angle); begin return (SL / SA) * Left + (SR / SA) * Right; end Slerp; end Orka.Transforms.SIMD_Vectors;
-- SPDX-License-Identifier: Apache-2.0 -- -- Copyright (c) 2017 onox <[email protected]> -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. with Ada.Numerics.Generic_Elementary_Functions; package body Orka.Transforms.SIMD_Vectors is function "-" (Elements : Point) return Point is Result : Vector4 := -Vector4 (Elements); begin Result (W) := Elements (W); return Point (Result); end "-"; function "+" (Left, Right : Direction) return Direction is (Direction (Vector4 (Left) + Vector4 (Right))); function "+" (Left : Point; Right : Direction) return Point is (Point (Vector4 (Left) + Vector4 (Right))); function "+" (Left : Direction; Right : Point) return Point is (Point (Vector4 (Left) + Vector4 (Right))); function "-" (Left, Right : Point) return Direction is (Direction (Vector4 (Left) - Vector4 (Right))); ---------------------------------------------------------------------------- package EF is new Ada.Numerics.Generic_Elementary_Functions (Element_Type); function Magnitude2 (Elements : Vector_Type) return Element_Type is (Sum (Elements * Elements)); function "*" (Factor : Element_Type; Elements : Vector_Type) return Vector_Type is begin return (Factor, Factor, Factor, Factor) * Elements; end "*"; function "*" (Elements : Vector_Type; Factor : Element_Type) return Vector_Type is (Factor * Elements); function "*" (Factor : Element_Type; Elements : Direction) return Direction is (Direction (Factor * Vector4 (Elements))); function "*" (Elements : Direction; Factor : Element_Type) return Direction is (Factor * Elements); function Magnitude (Elements : Vector_Type) return Element_Type is begin return EF.Sqrt (Magnitude2 (Elements)); end Magnitude; function Normalize (Elements : Vector_Type) return Vector_Type is Length : constant Element_Type := Magnitude (Elements); begin return Divide_Or_Zero (Elements, (Length, Length, Length, Length)); end Normalize; function Normalized (Elements : Vector_Type) return Boolean is function Is_Equivalent (Expected, Result : Element_Type) return Boolean is -- Because the square root is not computed, the bounds need -- to be increased to +/- 2 * Epsilon + Epsilon ** 2. Since -- Epsilon < 1, we can simply take +/- 3 * Epsilon Epsilon : constant Element_Type := 3.0 * Element_Type'Model_Epsilon; begin return abs (Result - Expected) <= Epsilon; end Is_Equivalent; begin return Is_Equivalent (1.0, Magnitude2 (Elements)); end Normalized; function Distance (Left, Right : Point) return Element_Type is (Magnitude (Vector_Type (Left - Right))); function Projection (Elements, Direction : Vector_Type) return Vector_Type is Unit_Direction : constant Vector_Type := Normalize (Direction); begin -- The dot product gives the magnitude of the projected vector: -- |A_b| = |A| * cos(theta) = A . U_b return Dot (Elements, Unit_Direction) * Unit_Direction; end Projection; function Perpendicular (Elements, Direction : Vector_Type) return Vector_Type is (Elements - Projection (Elements, Direction)); function Angle (Left, Right : Vector_Type) return Element_Type is begin return EF.Arccos (Dot (Left, Right) / (Magnitude (Left) * Magnitude (Right))); end Angle; function Dot (Left, Right : Vector_Type) return Element_Type is (Sum (Left * Right)); function Slerp (Left, Right : Vector_Type; Weight : Element_Type) return Vector_Type is Cos_Angle : constant Element_Type := Dot (Left, Right); Angle : constant Element_Type := EF.Arccos (Cos_Angle); SA : constant Element_Type := EF.Sin (Angle); SL : constant Element_Type := EF.Sin ((1.0 - Weight) * Angle); SR : constant Element_Type := EF.Sin (Weight * Angle); begin return (SL / SA) * Left + (SR / SA) * Right; end Slerp; end Orka.Transforms.SIMD_Vectors;
Simplify function Normalized in package SIMD_Vectors a bit
transforms: Simplify function Normalized in package SIMD_Vectors a bit Signed-off-by: onox <[email protected]>
Ada
apache-2.0
onox/orka
61493baf4057e4e14797584dddb594fcf091987d
awa/awaunit/awa-tests-helpers.ads
awa/awaunit/awa-tests-helpers.ads
----------------------------------------------------------------------- -- Aawa-tests-helpers - Helpers for AWA unit tests -- 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 AWA.Tests.Helpers is end AWA.Tests.Helpers;
----------------------------------------------------------------------- -- awa-tests-helpers - Helpers for AWA unit tests -- Copyright (C) 2011, 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 ASF.Responses.Mockup; with Ada.Strings.Unbounded; package AWA.Tests.Helpers is -- Extract from the Location header the part that is after the given base string. -- If the Location header does not start with the base string, returns the empty -- string. function Extract_Redirect (Reply : in ASF.Responses.Mockup.Response'Class; Base : in String) return String; function Extract_Redirect (Reply : in ASF.Responses.Mockup.Response'Class; Base : in String) return Ada.Strings.Unbounded.Unbounded_String; end AWA.Tests.Helpers;
Declare the Extract_Redirect function to help a unit test in extracting the result from a redirection
Declare the Extract_Redirect function to help a unit test in extracting the result from a redirection
Ada
apache-2.0
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
d48bd9b1732ba759fc09260e60463841a3d11472
regtests/dlls/util-systems-dlls-tests.adb
regtests/dlls/util-systems-dlls-tests.adb
----------------------------------------------------------------------- -- util-systems-dlls-tests -- Unit tests for shared libraries -- Copyright (C) 2013, 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.Test_Caller; package body Util.Systems.DLLs.Tests is use Util.Tests; use type System.Address; package Caller is new Util.Test_Caller (Test, "Systems.Dlls"); procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is begin Caller.Add_Test (Suite, "Test Util.Systems.Dlls.Load", Test_Load'Access); Caller.Add_Test (Suite, "Test Util.Systems.Dlls.Get_Symbol", Test_Get_Symbol'Access); end Add_Tests; procedure Load_Library (T : in out Test; Lib : out Handle) is Lib1 : Handle; Lib2 : Handle; Lib3 : Handle; begin begin Lib1 := Util.Systems.DLLs.Load ("libcrypto.so"); T.Assert (Lib1 /= Null_Handle, "Load operation returned null"); Lib := Lib1; exception when Load_Error => Lib1 := Null_Handle; end; begin Lib2 := Util.Systems.DLLs.Load ("libcrypto.dylib"); T.Assert (Lib2 /= Null_Handle, "Load operation returned null"); Lib := Lib2; exception when Load_Error => Lib2 := Null_Handle; end; begin Lib3 := Util.Systems.DLLs.Load ("zlib1.dll"); T.Assert (Lib3 /= Null_Handle, "Load operation returned null"); Lib := Lib3; exception when Load_Error => Lib3 := Null_Handle; end; T.Assert (Lib1 /= Null_Handle or Lib2 /= Null_Handle or Lib3 = Null_Handle, "At least on Load operation should have failedreturned null"); end Load_Library; -- ------------------------------ -- Test the loading a shared library. -- ------------------------------ procedure Test_Load (T : in out Test) is Lib : Handle; begin Load_Library (T, Lib); begin Lib := Util.Systems.DLLs.Load ("some-invalid-library"); T.Fail ("Load must raise an exception"); exception when Load_Error => null; end; end Test_Load; -- ------------------------------ -- Test getting a shared library symbol. -- ------------------------------ procedure Test_Get_Symbol (T : in out Test) is Lib : Handle; Sym : System.Address := System.Null_Address; begin Load_Library (T, Lib); T.Assert (Lib /= Null_Handle, "Load operation returned null"); begin Sym := Util.Systems.DLLs.Get_Symbol (Lib, "EVP_sha1"); T.Assert (Sym /= System.Null_Address, "Get_Symbol returned null"); exception when Not_Found => null; end; begin Sym := Util.Systems.DLLs.Get_Symbol (Lib, "compress"); T.Assert (Sym /= System.Null_Address, "Get_Symbol returned null"); exception when Not_Found => null; end; -- We must have found one of the two symbols T.Assert (Sym /= System.Null_Address, "Get_Symbol returned null"); begin Sym := Util.Systems.DLLs.Get_Symbol (Lib, "some-invalid-symbol"); T.Fail ("The Get_Symbol operation must raise an exception"); exception when Not_Found => null; end; end Test_Get_Symbol; end Util.Systems.DLLs.Tests;
----------------------------------------------------------------------- -- util-systems-dlls-tests -- Unit tests for shared libraries -- Copyright (C) 2013, 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.Test_Caller; package body Util.Systems.DLLs.Tests is use Util.Tests; use type System.Address; package Caller is new Util.Test_Caller (Test, "Systems.Dlls"); procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is begin Caller.Add_Test (Suite, "Test Util.Systems.Dlls.Load", Test_Load'Access); Caller.Add_Test (Suite, "Test Util.Systems.Dlls.Get_Symbol", Test_Get_Symbol'Access); end Add_Tests; procedure Load_Library (T : in out Test; Lib : out Handle) is Lib1 : Handle; Lib2 : Handle; Lib3 : Handle; begin begin Lib1 := Util.Systems.DLLs.Load ("libcrypto.so"); T.Assert (Lib1 /= Null_Handle, "Load operation returned null"); Lib := Lib1; exception when Load_Error => Lib1 := Null_Handle; end; begin Lib2 := Util.Systems.DLLs.Load ("libcrypto.dylib"); T.Assert (Lib2 /= Null_Handle, "Load operation returned null"); Lib := Lib2; exception when Load_Error => Lib2 := Null_Handle; end; begin Lib3 := Util.Systems.DLLs.Load ("zlib1.dll"); T.Assert (Lib3 /= Null_Handle, "Load operation returned null"); Lib := Lib3; exception when Load_Error => Lib3 := Null_Handle; end; T.Assert (Lib1 /= Null_Handle or Lib2 /= Null_Handle or Lib3 /= Null_Handle, "At least on Load operation should have failedreturned null"); end Load_Library; -- ------------------------------ -- Test the loading a shared library. -- ------------------------------ procedure Test_Load (T : in out Test) is Lib : Handle; begin Load_Library (T, Lib); begin Lib := Util.Systems.DLLs.Load ("some-invalid-library"); T.Fail ("Load must raise an exception"); exception when Load_Error => null; end; end Test_Load; -- ------------------------------ -- Test getting a shared library symbol. -- ------------------------------ procedure Test_Get_Symbol (T : in out Test) is Lib : Handle; Sym : System.Address := System.Null_Address; begin Load_Library (T, Lib); T.Assert (Lib /= Null_Handle, "Load operation returned null"); begin Sym := Util.Systems.DLLs.Get_Symbol (Lib, "EVP_sha1"); T.Assert (Sym /= System.Null_Address, "Get_Symbol returned null"); exception when Not_Found => null; end; begin Sym := Util.Systems.DLLs.Get_Symbol (Lib, "compress"); T.Assert (Sym /= System.Null_Address, "Get_Symbol returned null"); exception when Not_Found => null; end; -- We must have found one of the two symbols T.Assert (Sym /= System.Null_Address, "Get_Symbol returned null"); begin Sym := Util.Systems.DLLs.Get_Symbol (Lib, "some-invalid-symbol"); T.Fail ("The Get_Symbol operation must raise an exception"); exception when Not_Found => null; end; end Test_Get_Symbol; end Util.Systems.DLLs.Tests;
Fix again DLL test on Windows
Fix again DLL test on Windows
Ada
apache-2.0
stcarrez/ada-util,stcarrez/ada-util
9b091885ce265ac2bd16b7055d602e4fdd1b3b9c
tools/hmac-main.adb
tools/hmac-main.adb
------------------------------------------------------------------------------ -- Copyright (c) 2014, Natacha Porté -- -- -- -- Permission to use, copy, modify, and distribute this software for any -- -- purpose with or without fee is hereby granted, provided that the above -- -- copyright notice and this permission notice appear in all copies. -- -- -- -- THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES -- -- WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF -- -- MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR -- -- ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES -- -- WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN -- -- ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF -- -- OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. -- ------------------------------------------------------------------------------ with Ada.Command_Line; with Ada.Streams; with Ada.Text_IO; with Ada.Text_IO.Text_Streams; with Natools.S_Expressions; with Natools.S_Expressions.Encodings; procedure HMAC.Main is begin case Ada.Command_Line.Argument_Count is when 0 => Ada.Text_IO.Put_Line ("Usage: " & Ada.Command_Line.Command_Name & " key [message]"); when 1 => declare Context : HMAC_Implementation.Context := HMAC_Implementation.Create (Ada.Command_Line.Argument (1)); Block : Ada.Streams.Stream_Element_Array (1 .. 64); Last : Ada.Streams.Stream_Element_Offset; Input : constant Ada.Text_IO.Text_Streams.Stream_Access := Ada.Text_IO.Text_Streams.Stream (Ada.Text_IO.Current_Input); begin loop Input.Read (Block, Last); exit when Last not in Block'Range; HMAC_Implementation.Update (Context, Block (Block'First .. Last)); end loop; Ada.Text_IO.Put_Line (Natools.S_Expressions.To_String (Natools.S_Expressions.Encodings.Encode_Hex (HMAC_Implementation.Digest (Context), Natools.S_Expressions.Encodings.Lower))); end; when others => for I in 2 .. Ada.Command_Line.Argument_Count loop Ada.Text_IO.Put_Line (Natools.S_Expressions.To_String (Natools.S_Expressions.Encodings.Encode_Hex (HMAC_Implementation.Digest (Ada.Command_Line.Argument (1), Natools.S_Expressions.To_Atom (Ada.Command_Line.Argument (I))), Natools.S_Expressions.Encodings.Lower))); end loop; end case; end HMAC.Main;
------------------------------------------------------------------------------ -- Copyright (c) 2014, Natacha Porté -- -- -- -- Permission to use, copy, modify, and distribute this software for any -- -- purpose with or without fee is hereby granted, provided that the above -- -- copyright notice and this permission notice appear in all copies. -- -- -- -- THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES -- -- WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF -- -- MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR -- -- ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES -- -- WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN -- -- ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF -- -- OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. -- ------------------------------------------------------------------------------ with Ada.Command_Line; with Ada.Streams; with Ada.Strings.Unbounded; with Ada.Text_IO; with Ada.Text_IO.Text_Streams; with Natools.Getopt_Long; with Natools.S_Expressions; with Natools.S_Expressions.Encodings; procedure HMAC.Main is procedure Base64_Output (Digest : in Ada.Streams.Stream_Element_Array); -- Output the given binary Digest in base-64 procedure Lower_Hex_Output (Digest : in Ada.Streams.Stream_Element_Array); -- Output the given binary Digest in lower-case hexadecimal procedure Raw_Output (Digest : in Ada.Streams.Stream_Element_Array); -- Output the given binary Direct directly procedure Upper_Hex_Output (Digest : in Ada.Streams.Stream_Element_Array); -- Output the given binary Digest in upper-case hexadecimal package Options is type Id is (Base64_Output, Lower_Hex_Output, Raw_Output, Upper_Hex_Output); end Options; package Getopt is new Natools.Getopt_Long (Options.Id); type Encode_Output is not null access procedure (Digest : in Ada.Streams.Stream_Element_Array); type Callback is new Getopt.Handlers.Callback with record Output : Encode_Output := Lower_Hex_Output'Access; Key : Ada.Strings.Unbounded.Unbounded_String; Has_Key : Boolean := False; Done : Boolean := False; end record; overriding procedure Option (Handler : in out Callback; Id : in Options.Id; Argument : in String); overriding procedure Argument (Handler : in out Callback; Argument : in String); overriding procedure Option (Handler : in out Callback; Id : in Options.Id; Argument : in String) is pragma Unreferenced (Argument); begin case Id is when Options.Base64_Output => Handler.Output := Base64_Output'Access; when Options.Lower_Hex_Output => Handler.Output := Lower_Hex_Output'Access; when Options.Raw_Output => Handler.Output := Raw_Output'Access; when Options.Upper_Hex_Output => Handler.Output := Upper_Hex_Output'Access; end case; end Option; overriding procedure Argument (Handler : in out Callback; Argument : in String) is begin if Handler.Has_Key then Handler.Output (HMAC_Implementation.Digest (Ada.Strings.Unbounded.To_String (Handler.Key), Natools.S_Expressions.To_Atom (Argument))); Handler.Done := True; else Handler.Key := Ada.Strings.Unbounded.To_Unbounded_String (Argument); Handler.Has_Key := True; end if; end Argument; procedure Base64_Output (Digest : in Ada.Streams.Stream_Element_Array) is begin Ada.Text_IO.Put_Line (Natools.S_Expressions.To_String (Natools.S_Expressions.Encodings.Encode_Base64 (Digest))); end Base64_Output; procedure Lower_Hex_Output (Digest : in Ada.Streams.Stream_Element_Array) is begin Ada.Text_IO.Put_Line (Natools.S_Expressions.To_String (Natools.S_Expressions.Encodings.Encode_Hex (Digest, Natools.S_Expressions.Encodings.Lower))); end Lower_Hex_Output; procedure Raw_Output (Digest : in Ada.Streams.Stream_Element_Array) is begin Ada.Text_IO.Text_Streams.Stream (Ada.Text_IO.Current_Output).Write (Digest); end Raw_Output; procedure Upper_Hex_Output (Digest : in Ada.Streams.Stream_Element_Array) is begin Ada.Text_IO.Put_Line (Natools.S_Expressions.To_String (Natools.S_Expressions.Encodings.Encode_Hex (Digest, Natools.S_Expressions.Encodings.Upper))); end Upper_Hex_Output; Opt_Config : Getopt.Configuration; Handler : Callback; begin Opt_Config.Add_Option ("base64", 'b', Getopt.No_Argument, Options.Base64_Output); Opt_Config.Add_Option ("lower-hex", 'h', Getopt.No_Argument, Options.Lower_Hex_Output); Opt_Config.Add_Option ("raw", 'r', Getopt.No_Argument, Options.Raw_Output); Opt_Config.Add_Option ("upper-hex", 'H', Getopt.No_Argument, Options.Upper_Hex_Output); Opt_Config.Process (Handler); if not Handler.Has_Key then Ada.Text_IO.Put_Line ("Usage: " & Ada.Command_Line.Command_Name & "[-h | -H | -b | -r] key [message]"); elsif not Handler.Done then declare Context : HMAC_Implementation.Context := HMAC_Implementation.Create (Ada.Strings.Unbounded.To_String (Handler.Key)); Block : Ada.Streams.Stream_Element_Array (1 .. 64); Last : Ada.Streams.Stream_Element_Offset; Input : constant Ada.Text_IO.Text_Streams.Stream_Access := Ada.Text_IO.Text_Streams.Stream (Ada.Text_IO.Current_Input); begin loop Input.Read (Block, Last); exit when Last not in Block'Range; HMAC_Implementation.Update (Context, Block (Block'First .. Last)); end loop; Handler.Output (HMAC_Implementation.Digest (Context)); end; end if; end HMAC.Main;
add command-line options to control output format
hmac-main: add command-line options to control output format
Ada
isc
faelys/natools
1602fd166ca0db2b59821ab83a145bfa9a9b7fc0
src/ado-parameters.ads
src/ado-parameters.ads
----------------------------------------------------------------------- -- ADO Parameters -- Parameters for queries -- Copyright (C) 2010, 2011, 2012, 2013, 2015 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Strings.Unbounded; with Ada.Finalization; with Ada.Calendar; with Ada.Containers.Indefinite_Vectors; with ADO.Utils; with ADO.Drivers.Dialects; -- Defines a list of parameters for an SQL statement. -- 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 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); -- 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> -- </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; 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. 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); -- 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> -- </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;
Declare the Expander interface Add some documentation
Declare the Expander interface Add some documentation
Ada
apache-2.0
stcarrez/ada-ado
552d08a2a05913232295659e060f9cdd1c991484
src/wiki-parsers-mediawiki.adb
src/wiki-parsers-mediawiki.adb
----------------------------------------------------------------------- -- wiki-parsers-mediawiki -- Media Wiki parser operations -- Copyright (C) 2011- 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 Wiki.Nodes; with Wiki.Helpers; with Wiki.Parsers.Common; package body Wiki.Parsers.MediaWiki is use Wiki.Helpers; use Wiki.Buffers; use type Wiki.Nodes.Node_Kind; procedure Parse_Bold_Italic (Parser : in out Parser_Type; Text : in out Wiki.Buffers.Buffer_Access; From : in out Positive); -- ------------------------------ -- Parse an italic, bold or bold + italic sequence. -- Example: -- ''name'' (italic) -- '''name''' (bold) -- '''''name''''' (bold+italic) -- ------------------------------ procedure Parse_Bold_Italic (Parser : in out Parser_Type; Text : in out Wiki.Buffers.Buffer_Access; From : in out Positive) is Count : Natural := Count_Occurence (Text, From, '''); begin case Count is when 1 => Common.Parse_Text (Parser, Text, From); return; when 2 => Toggle_Format (Parser, ITALIC); when 3 => Toggle_Format (Parser, BOLD); when 4 => Toggle_Format (Parser, BOLD); Common.Parse_Text (Parser, Text, From); Count := 3; when 5 => Toggle_Format (Parser, BOLD); Toggle_Format (Parser, ITALIC); when others => Common.Parse_Text (Parser, Text, From); return; end case; for I in 1 .. Count loop Next (Text, From); end loop; end Parse_Bold_Italic; procedure Parse_Line (Parser : in out Parser_Type; Text : in Wiki.Buffers.Buffer_Access) is Pos : Natural := 1; C : Wiki.Strings.WChar; Buffer : Wiki.Buffers.Buffer_Access := Text; begin -- Feed the HTML parser if there are some pending state. if not Wiki.Html_Parser.Is_Empty (Parser.Html) then Common.Parse_Html_Element (Parser, Buffer, Pos, Start => False); if Buffer = null then return; end if; end if; if Parser.Pre_Tag_Counter > 0 then Common.Parse_Html_Preformatted (Parser, Buffer, Pos); if Buffer = null then return; end if; end if; if Parser.Current_Node = Nodes.N_PREFORMAT then if Buffer.Content (Pos) = ' ' then Common.Append (Parser.Text, Buffer, Pos + 1); return; end if; Pop_Block (Parser); end if; if Parser.Current_Node = Nodes.N_HEADER then Pop_Block (Parser); end if; C := Buffer.Content (Pos); case C is when CR | LF => Common.Parse_Paragraph (Parser, Buffer, Pos); return; when '=' => Common.Parse_Header (Parser, Buffer, Pos, '='); if Buffer = null then return; end if; when '-' => Common.Parse_Horizontal_Rule (Parser, Buffer, Pos, '-'); if Buffer = null then return; end if; when '*' | '#' => if Common.Is_List (Buffer, Pos) then Common.Parse_List (Parser, Buffer, Pos); end if; when ' ' => if Common.Is_List (Buffer, Pos + 1) then Pos := Pos + 1; Common.Parse_List (Parser, Buffer, Pos); end if; -- Parser.Preformat_Indent := 1; -- Parser.Preformat_Fence := ' '; -- Parser.Preformat_Fcount := 1; -- Flush_Text (Parser, Trim => Right); -- Pop_Block (Parser); -- Push_Block (Parser, Nodes.N_PREFORMAT); -- Common.Append (Parser.Text, Buffer, Pos + 1); -- return; when ';' => Common.Parse_Definition (Parser, Buffer, Pos); return; when ':' => if Parser.Current_Node = Nodes.N_DEFINITION then Next (Buffer, Pos); Common.Skip_Spaces (Buffer, Pos); end if; when others => if Parser.Current_Node /= Nodes.N_PARAGRAPH then Pop_List (Parser); Push_Block (Parser, Nodes.N_PARAGRAPH); end if; end case; Main : while Buffer /= null loop declare Last : Natural := Buffer.Last; begin while Pos <= Buffer.Last loop C := Buffer.Content (Pos); case C is when ''' => Parse_Bold_Italic (Parser, Buffer, Pos); exit Main when Buffer = null; when '/' => Parse_Format_Double (Parser, Buffer, Pos, '/', Wiki.EMPHASIS); exit Main when Buffer = null; when '[' => Common.Parse_Link (Parser, Buffer, Pos); exit Main when Buffer = null; when '{' => Common.Parse_Template (Parser, Buffer, Pos, '{'); exit Main when Buffer = null; when CR | LF => Append (Parser.Text, ' '); Pos := Pos + 1; when '<' => Common.Parse_Html_Element (Parser, Buffer, Pos, Start => True); exit Main when Buffer = null; when '&' => Common.Parse_Entity (Parser, Buffer, Pos); exit Main when Buffer = null; when others => Append (Parser.Text, C); Pos := Pos + 1; end case; end loop; end; Buffer := Buffer.Next_Block; Pos := 1; end loop Main; end Parse_Line; end Wiki.Parsers.MediaWiki;
----------------------------------------------------------------------- -- wiki-parsers-mediawiki -- Media Wiki parser operations -- Copyright (C) 2011- 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 Wiki.Nodes; with Wiki.Helpers; with Wiki.Parsers.Common; package body Wiki.Parsers.MediaWiki is use Wiki.Helpers; use Wiki.Buffers; use type Wiki.Nodes.Node_Kind; procedure Parse_Bold_Italic (Parser : in out Parser_Type; Text : in out Wiki.Buffers.Buffer_Access; From : in out Positive); -- ------------------------------ -- Parse an italic, bold or bold + italic sequence. -- Example: -- ''name'' (italic) -- '''name''' (bold) -- '''''name''''' (bold+italic) -- ------------------------------ procedure Parse_Bold_Italic (Parser : in out Parser_Type; Text : in out Wiki.Buffers.Buffer_Access; From : in out Positive) is Count : Natural := Count_Occurence (Text, From, '''); begin case Count is when 1 => Common.Parse_Text (Parser, Text, From); return; when 2 => Toggle_Format (Parser, ITALIC); when 3 => Toggle_Format (Parser, BOLD); when 4 => Toggle_Format (Parser, BOLD); Common.Parse_Text (Parser, Text, From); Count := 3; when 5 => Toggle_Format (Parser, BOLD); Toggle_Format (Parser, ITALIC); when others => Common.Parse_Text (Parser, Text, From); return; end case; for I in 1 .. Count loop Next (Text, From); end loop; end Parse_Bold_Italic; procedure Parse_Line (Parser : in out Parser_Type; Text : in Wiki.Buffers.Buffer_Access) is Pos : Natural := 1; C : Wiki.Strings.WChar; Buffer : Wiki.Buffers.Buffer_Access := Text; begin -- Feed the HTML parser if there are some pending state. if not Wiki.Html_Parser.Is_Empty (Parser.Html) then Common.Parse_Html_Element (Parser, Buffer, Pos, Start => False); if Buffer = null then return; end if; end if; if Parser.Pre_Tag_Counter > 0 then Common.Parse_Html_Preformatted (Parser, Buffer, Pos); if Buffer = null then return; end if; end if; if Parser.Current_Node = Nodes.N_PREFORMAT then if Buffer.Content (Pos) = ' ' then Common.Append (Parser.Text, Buffer, Pos + 1); return; end if; Pop_Block (Parser); end if; if Parser.Current_Node = Nodes.N_HEADER then Pop_Block (Parser); end if; C := Buffer.Content (Pos); case C is when CR | LF => Common.Parse_Paragraph (Parser, Buffer, Pos); return; when '=' => Common.Parse_Header (Parser, Buffer, Pos, '='); if Buffer = null then return; end if; when '-' => Common.Parse_Horizontal_Rule (Parser, Buffer, Pos, '-'); if Buffer = null then return; end if; when '*' | '#' => if Common.Is_List (Buffer, Pos) then Common.Parse_List (Parser, Buffer, Pos); end if; when ' ' => if Common.Is_List (Buffer, Pos + 1) then Pos := Pos + 1; Common.Parse_List (Parser, Buffer, Pos); end if; if not Parser.In_Html then Parser.Preformat_Indent := 1; Parser.Preformat_Fence := ' '; Parser.Preformat_Fcount := 1; Flush_Text (Parser, Trim => Right); Pop_Block (Parser); Push_Block (Parser, Nodes.N_PREFORMAT); Common.Append (Parser.Text, Buffer, Pos + 1); return; end if; when ';' => Common.Parse_Definition (Parser, Buffer, Pos); return; when ':' => if Parser.Current_Node = Nodes.N_DEFINITION then Next (Buffer, Pos); declare Count : Natural; begin Common.Skip_Spaces (Buffer, Pos, Count); end; end if; when others => if Parser.Current_Node /= Nodes.N_PARAGRAPH then Pop_List (Parser); Push_Block (Parser, Nodes.N_PARAGRAPH); end if; end case; Main : while Buffer /= null loop declare Last : Natural := Buffer.Last; begin while Pos <= Buffer.Last loop C := Buffer.Content (Pos); case C is when ''' => Parse_Bold_Italic (Parser, Buffer, Pos); exit Main when Buffer = null; when '/' => Parse_Format_Double (Parser, Buffer, Pos, '/', Wiki.EMPHASIS); exit Main when Buffer = null; when '[' => Common.Parse_Link (Parser, Buffer, Pos); exit Main when Buffer = null; when '{' => Common.Parse_Template (Parser, Buffer, Pos, '{'); exit Main when Buffer = null; when CR | LF => Append (Parser.Text, ' '); Pos := Pos + 1; when '<' => Common.Parse_Html_Element (Parser, Buffer, Pos, Start => True); exit Main when Buffer = null; when '&' => Common.Parse_Entity (Parser, Buffer, Pos); exit Main when Buffer = null; when others => Append (Parser.Text, C); Pos := Pos + 1; end case; end loop; end; Buffer := Buffer.Next_Block; Pos := 1; end loop Main; end Parse_Line; end Wiki.Parsers.MediaWiki;
Update calls to Skip_Spaces
Update calls to Skip_Spaces
Ada
apache-2.0
stcarrez/ada-wiki,stcarrez/ada-wiki
faec66c1f87e0622e4e3d688cd6a9cd9697b5fed
src/wiki-plugins-templates.ads
src/wiki-plugins-templates.ads
----------------------------------------------------------------------- -- wiki-plugins-template -- Template Plugin -- 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 Wiki.Strings; -- === Template Plugins === -- The <b>Wiki.Plugins.Templates</b> package defines an abstract template plugin. -- To use the template plugin, the <tt>Get_Template</tt> procedure must be implemented. -- It is responsible for getting the template content according to the plugin parameters. -- package Wiki.Plugins.Templates is type Template_Plugin is abstract new Wiki_Plugin with null record; -- Get the template content for the plugin evaluation. procedure Get_Template (Plugin : in out Template_Plugin; Params : in out Wiki.Attributes.Attribute_List; Template : out Wiki.Strings.UString) is abstract; -- Expand the template configured with the parameters for the document. -- The <tt>Get_Template</tt> operation is called and the template content returned -- by that operation is parsed in the current document. Template parameters are passed -- in the <tt>Context</tt> instance and they can be evaluated within the template -- while parsing the template content. overriding procedure Expand (Plugin : in out Template_Plugin; Document : in out Wiki.Documents.Document; Params : in out Wiki.Attributes.Attribute_List; Context : in Plugin_Context); type File_Template_Plugin is new Wiki_Plugin with private; -- Set the directory path that contains template files. procedure Set_Template_Path (Plugin : in out File_Template_Plugin; Path : in String); -- Expand the template configured with the parameters for the document. -- Read the file whose basename correspond to the first parameter and parse that file -- in the current document. Template parameters are passed -- in the <tt>Context</tt> instance and they can be evaluated within the template -- while parsing the template content. overriding procedure Expand (Plugin : in out File_Template_Plugin; Document : in out Wiki.Documents.Document; Params : in out Wiki.Attributes.Attribute_List; Context : in Plugin_Context); private type File_Template_Plugin is new Wiki_Plugin with record Path : Ada.Strings.Unbounded.Unbounded_String; end record; end Wiki.Plugins.Templates;
----------------------------------------------------------------------- -- wiki-plugins-template -- Template Plugin -- 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 Wiki.Strings; -- === Template Plugins === -- The <b>Wiki.Plugins.Templates</b> package defines an abstract template plugin. -- To use the template plugin, the <tt>Get_Template</tt> procedure must be implemented. -- It is responsible for getting the template content according to the plugin parameters. -- package Wiki.Plugins.Templates is type Template_Plugin is abstract new Wiki_Plugin with null record; -- Get the template content for the plugin evaluation. procedure Get_Template (Plugin : in out Template_Plugin; Params : in out Wiki.Attributes.Attribute_List; Template : out Wiki.Strings.UString) is abstract; -- Expand the template configured with the parameters for the document. -- The <tt>Get_Template</tt> operation is called and the template content returned -- by that operation is parsed in the current document. Template parameters are passed -- in the <tt>Context</tt> instance and they can be evaluated within the template -- while parsing the template content. overriding procedure Expand (Plugin : in out Template_Plugin; Document : in out Wiki.Documents.Document; Params : in out Wiki.Attributes.Attribute_List; Context : in Plugin_Context); type File_Template_Plugin is new Wiki_Plugin and Plugin_Factory with private; -- Find a plugin knowing its name. overriding function Find (Factory : in File_Template_Plugin; Name : in String) return Wiki_Plugin_Access; -- Set the directory path that contains template files. procedure Set_Template_Path (Plugin : in out File_Template_Plugin; Path : in String); -- Expand the template configured with the parameters for the document. -- Read the file whose basename correspond to the first parameter and parse that file -- in the current document. Template parameters are passed -- in the <tt>Context</tt> instance and they can be evaluated within the template -- while parsing the template content. overriding procedure Expand (Plugin : in out File_Template_Plugin; Document : in out Wiki.Documents.Document; Params : in out Wiki.Attributes.Attribute_List; Context : in Plugin_Context); private type File_Template_Plugin is new Wiki_Plugin and Plugin_Factory with record Path : Ada.Strings.Unbounded.Unbounded_String; end record; end Wiki.Plugins.Templates;
Change the File_Template_Plugin to implement the Plugin_Factory interface
Change the File_Template_Plugin to implement the Plugin_Factory interface
Ada
apache-2.0
stcarrez/ada-wiki,stcarrez/ada-wiki
dbbb2c6a510c30fdbfddee37fd8b41115a8dc46d
mat/src/mat-targets-probes.adb
mat/src/mat-targets-probes.adb
----------------------------------------------------------------------- -- mat-targets-probes - Definition and Analysis of process start events -- Copyright (C) 2014 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Log.Loggers; with MAT.Readers.Marshaller; package body MAT.Targets.Probes is -- The logger Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("MAT.Targets.Probes"); MSG_BEGIN : constant MAT.Events.Internal_Reference := 0; MSG_END : constant MAT.Events.Internal_Reference := 1; M_PID : constant MAT.Events.Internal_Reference := 1; M_EXE : constant MAT.Events.Internal_Reference := 2; M_HEAP_START : constant MAT.Events.Internal_Reference := 3; M_HEAP_END : constant MAT.Events.Internal_Reference := 4; M_END : constant MAT.Events.Internal_Reference := 5; PID_NAME : aliased constant String := "pid"; EXE_NAME : aliased constant String := "exe"; HP_START_NAME : aliased constant String := "hp_start"; HP_END_NAME : aliased constant String := "hp_end"; END_NAME : aliased constant String := "end"; Process_Attributes : aliased constant MAT.Events.Attribute_Table := (1 => (Name => PID_NAME'Access, Size => 0, Kind => MAT.Events.T_SIZE_T, Ref => M_PID), 2 => (Name => EXE_NAME'Access, Size => 0, Kind => MAT.Events.T_FRAME, Ref => M_EXE), 3 => (Name => HP_START_NAME'Access, Size => 0, Kind => MAT.Events.T_FRAME, Ref => M_HEAP_START), 4 => (Name => HP_END_NAME'Access, Size => 0, Kind => MAT.Events.T_FRAME, Ref => M_HEAP_END), 5 => (Name => END_NAME'Access, Size => 0, Kind => MAT.Events.T_FRAME, Ref => M_END)); -- ------------------------------ -- Create a new process after the begin event is received from the event stream. -- ------------------------------ procedure Create_Process (For_Servant : in out Process_Probe_Type; Pid : in MAT.Types.Target_Process_Ref; Path : in Ada.Strings.Unbounded.Unbounded_String) is begin For_Servant.Target.Create_Process (Pid => Pid, Path => Path, Process => For_Servant.Process); For_Servant.Process.Events := For_Servant.Events; MAT.Memory.Targets.Initialize (Memory => For_Servant.Process.Memory, Reader => For_Servant.Reader.all); end Create_Process; procedure Probe_Begin (Probe : in out Process_Probe_Type; Id : in MAT.Events.Internal_Reference; Defs : in MAT.Events.Attribute_Table; Frame : in MAT.Events.Frame_Info; Msg : in out MAT.Readers.Message) is Pid : MAT.Types.Target_Process_Ref := 0; Path : Ada.Strings.Unbounded.Unbounded_String; Heap : MAT.Memory.Region_Info; begin for I in Defs'Range loop declare Def : MAT.Events.Attribute renames Defs (I); begin case Def.Ref is when M_PID => Pid := MAT.Readers.Marshaller.Get_Target_Size (Msg, Def.Kind); when M_EXE => Path := MAT.Readers.Marshaller.Get_String (Msg); when M_HEAP_START => Heap.Start_Addr := MAT.Readers.Marshaller.Get_Target_Addr (Msg, Def.Kind); when M_HEAP_END => Heap.End_Addr := MAT.Readers.Marshaller.Get_Target_Addr (Msg, Def.Kind); when others => MAT.Readers.Marshaller.Skip (Msg, Def.Size); end case; end; end loop; Heap.Size := Heap.End_Addr - Heap.Start_Addr; Heap.Path := Ada.Strings.Unbounded.To_Unbounded_String ("[heap]"); For_Servant.Create_Process (Pid, Path); For_Servant.Reader.Read_Message (Msg); For_Servant.Reader.Read_Event_Definitions (Msg); For_Servant.Process.Memory.Add_Region (Heap); end Probe_Begin; overriding procedure Extract (Probe : in Process_Probe_Type; Params : in MAT.Events.Const_Attribute_Table_Access; Msg : in out MAT.Readers.Message_Type; Event : in out MAT.Events.Targets.Probe_Event_Type) is begin null; end Extract; procedure Execute (Probe : in Process_Probe_Type; Event : in MAT.Events.Targets.Probe_Event_Type) is begin null; end Execute; -- ------------------------------ -- Register the reader to extract and analyze process events. -- ------------------------------ procedure Register (Into : in out MAT.Events.Probes.Probe_Manager_Type'Class; Probe : in Process_Probe_Type_Access) is begin Probe.Manager := Into'Unchecked_Access; Into.Register_Probe (Probe.all'Access, "begin", MSG_BEGIN, Process_Attributes'Access); Into.Register_Probe (Probe.all'Access, "end", MSG_END, Process_Attributes'Access); end Register; -- ------------------------------ -- Initialize the target object to prepare for reading process events. -- ------------------------------ procedure Initialize (Target : in out Target_Type; Manager : in out MAT.Events.Probes.Probe_Manager_Type_Access) is Process_Probe : constant Process_Probe_Type_Access := new Process_Probe_Type; begin Process_Probe.Target := Target'Unrestricted_Access; Process_Probe.Events := Manager.Get_Target_Events; Register (Manager.all, Process_Probe); end Initialize; end MAT.Targets.Probes;
----------------------------------------------------------------------- -- mat-targets-probes - Definition and Analysis of process start events -- Copyright (C) 2014 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Log.Loggers; with MAT.Readers.Marshaller; package body MAT.Targets.Probes is -- The logger Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("MAT.Targets.Probes"); MSG_BEGIN : constant MAT.Events.Targets.Probe_Index_Type := 0; MSG_END : constant MAT.Events.Targets.Probe_Index_Type := 1; M_PID : constant MAT.Events.Internal_Reference := 1; M_EXE : constant MAT.Events.Internal_Reference := 2; M_HEAP_START : constant MAT.Events.Internal_Reference := 3; M_HEAP_END : constant MAT.Events.Internal_Reference := 4; M_END : constant MAT.Events.Internal_Reference := 5; PID_NAME : aliased constant String := "pid"; EXE_NAME : aliased constant String := "exe"; HP_START_NAME : aliased constant String := "hp_start"; HP_END_NAME : aliased constant String := "hp_end"; END_NAME : aliased constant String := "end"; Process_Attributes : aliased constant MAT.Events.Attribute_Table := (1 => (Name => PID_NAME'Access, Size => 0, Kind => MAT.Events.T_SIZE_T, Ref => M_PID), 2 => (Name => EXE_NAME'Access, Size => 0, Kind => MAT.Events.T_FRAME, Ref => M_EXE), 3 => (Name => HP_START_NAME'Access, Size => 0, Kind => MAT.Events.T_FRAME, Ref => M_HEAP_START), 4 => (Name => HP_END_NAME'Access, Size => 0, Kind => MAT.Events.T_FRAME, Ref => M_HEAP_END), 5 => (Name => END_NAME'Access, Size => 0, Kind => MAT.Events.T_FRAME, Ref => M_END)); -- ------------------------------ -- Create a new process after the begin event is received from the event stream. -- ------------------------------ procedure Create_Process (Probe : in out Process_Probe_Type; Pid : in MAT.Types.Target_Process_Ref; Path : in Ada.Strings.Unbounded.Unbounded_String) is begin -- Probe.Target.Create_Process (Pid => Pid, -- Path => Path, -- Process => Probe.Process); Probe.Process.Events := Probe.Events; MAT.Memory.Targets.Initialize (Memory => Probe.Process.Memory, Manager => Probe.Manager.all); end Create_Process; procedure Probe_Begin (Probe : in out Process_Probe_Type; Id : in MAT.Events.Internal_Reference; Defs : in MAT.Events.Attribute_Table; Frame : in MAT.Events.Frame_Info; Msg : in out MAT.Readers.Message) is Pid : MAT.Types.Target_Process_Ref := 0; Path : Ada.Strings.Unbounded.Unbounded_String; Heap : MAT.Memory.Region_Info; begin for I in Defs'Range loop declare Def : MAT.Events.Attribute renames Defs (I); begin case Def.Ref is when M_PID => Pid := MAT.Readers.Marshaller.Get_Target_Size (Msg, Def.Kind); when M_EXE => Path := MAT.Readers.Marshaller.Get_String (Msg); when M_HEAP_START => Heap.Start_Addr := MAT.Readers.Marshaller.Get_Target_Addr (Msg, Def.Kind); when M_HEAP_END => Heap.End_Addr := MAT.Readers.Marshaller.Get_Target_Addr (Msg, Def.Kind); when others => MAT.Readers.Marshaller.Skip (Msg, Def.Size); end case; end; end loop; Heap.Size := Heap.End_Addr - Heap.Start_Addr; Heap.Path := Ada.Strings.Unbounded.To_Unbounded_String ("[heap]"); Probe.Create_Process (Pid, Path); Probe.Manager.Read_Message (Msg); Probe.Manager.Read_Event_Definitions (Msg); Probe.Process.Memory.Add_Region (Heap); end Probe_Begin; overriding procedure Extract (Probe : in Process_Probe_Type; Params : in MAT.Events.Const_Attribute_Table_Access; Msg : in out MAT.Readers.Message_Type; Event : in out MAT.Events.Targets.Probe_Event_Type) is begin null; end Extract; procedure Execute (Probe : in Process_Probe_Type; Event : in MAT.Events.Targets.Probe_Event_Type) is begin null; end Execute; -- ------------------------------ -- Register the reader to extract and analyze process events. -- ------------------------------ procedure Register (Into : in out MAT.Events.Probes.Probe_Manager_Type'Class; Probe : in Process_Probe_Type_Access) is begin Probe.Manager := Into'Unchecked_Access; Into.Register_Probe (Probe.all'Access, "begin", MSG_BEGIN, Process_Attributes'Access); Into.Register_Probe (Probe.all'Access, "end", MSG_END, Process_Attributes'Access); end Register; -- ------------------------------ -- Initialize the target object to prepare for reading process events. -- ------------------------------ procedure Initialize (Target : in out Target_Type; Manager : in out MAT.Events.Probes.Probe_Manager_Type'Class) is Process_Probe : constant Process_Probe_Type_Access := new Process_Probe_Type; begin Process_Probe.Target := Target'Unrestricted_Access; Process_Probe.Events := Manager.Get_Target_Events; Register (Manager, Process_Probe); end Initialize; end MAT.Targets.Probes;
Fix the Initialize and Create_Process procedures
Fix the Initialize and Create_Process procedures
Ada
apache-2.0
stcarrez/mat,stcarrez/mat,stcarrez/mat
391866ad37a599347df40a4dbb3bf0721bedabea
arch/ARM/Nordic/drivers/nrf51-temperature.adb
arch/ARM/Nordic/drivers/nrf51-temperature.adb
------------------------------------------------------------------------------ -- -- -- Copyright (C) 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. -- -- -- ------------------------------------------------------------------------------ with NRF51_SVD.TEMP; use NRF51_SVD.TEMP; with HAL; use HAL; package body nRF51.Temperature is type RAW_Temp is delta 0.25 range Temp_Celcius'First * 4.0 .. Temp_Celcius'Last * 4.0; ---------- -- Read -- ---------- function Read return Temp_Celcius is Raw : RAW_Temp; begin -- Clear event TEMP_Periph.EVENTS_DATARDY := 0; -- Start temperature measurement TEMP_Periph.TASKS_START := 1; while TEMP_Periph.EVENTS_DATARDY = 0 loop null; end loop; Raw := RAW_Temp (TEMP_Periph.TEMP); return Temp_Celcius (Raw / 4); end Read; end nRF51.Temperature;
------------------------------------------------------------------------------ -- -- -- Copyright (C) 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. -- -- -- ------------------------------------------------------------------------------ with NRF51_SVD.TEMP; use NRF51_SVD.TEMP; with HAL; use HAL; package body nRF51.Temperature is type RAW_Temp is delta 0.25 range Temp_Celsius'First * 4.0 .. Temp_Celsius'Last * 4.0; ---------- -- Read -- ---------- function Read return Temp_Celsius is Raw : RAW_Temp; begin -- Clear event TEMP_Periph.EVENTS_DATARDY := 0; -- Start temperature measurement TEMP_Periph.TASKS_START := 1; while TEMP_Periph.EVENTS_DATARDY = 0 loop null; end loop; Raw := RAW_Temp (TEMP_Periph.TEMP); return Temp_Celsius (Raw / 4); end Read; end nRF51.Temperature;
Update nrf51-temperature.adb
Update nrf51-temperature.adb
Ada
bsd-3-clause
simonjwright/Ada_Drivers_Library,AdaCore/Ada_Drivers_Library,AdaCore/Ada_Drivers_Library,simonjwright/Ada_Drivers_Library
fd9514f4ceb461090e597d71b59bb1c0cf3f1464
src/ado-caches.adb
src/ado-caches.adb
----------------------------------------------------------------------- -- ado-cache -- Simple cache management -- Copyright (C) 2017 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Unchecked_Deallocation; package body ADO.Caches is -- -------------------- -- 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. -- -------------------- overriding function Expand (Instance : in Cache_Manager; Group : in String; Name : in String) return ADO.Parameters.Parameter is use type Ada.Strings.Unbounded.Unbounded_String; C : Cache_Type_Access := Instance.First; begin while C /= null loop if C.Name = Group then return C.Expand (Name); end if; C := C.Next; end loop; raise No_Value; end Expand; -- -------------------- -- Insert a new cache in the manager. The cache is identified by the given name. -- -------------------- procedure Add_Cache (Manager : in out Cache_Manager; Name : in String; Cache : in Cache_Type_Access) is begin Cache.Next := Manager.First; Cache.Name := Ada.Strings.Unbounded.To_Unbounded_String (Name); Manager.First := Cache; end Add_Cache; -- -------------------- -- Finalize the cache manager releasing every cache group. -- -------------------- overriding procedure Finalize (Manager : in out Cache_Manager) is procedure Free is new Ada.Unchecked_Deallocation (Object => Cache_Type'Class, Name => Cache_Type_Access); Cache : Cache_Type_Access; begin loop Cache := Manager.First; exit when Cache = null; Manager.First := Cache.Next; Free (Cache); end loop; end Finalize; end ADO.Caches;
----------------------------------------------------------------------- -- ado-cache -- Simple cache management -- Copyright (C) 2017 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Unchecked_Deallocation; package body ADO.Caches is -- -------------------- -- 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. -- -------------------- overriding function Expand (Instance : in Cache_Manager; Group : in String; Name : in String) return ADO.Parameters.Parameter is use type Ada.Strings.Unbounded.Unbounded_String; C : Cache_Type_Access := Instance.First; begin while C /= null loop if C.Name = Group then return C.Expand (Name); end if; C := C.Next; end loop; Log.Warn ("There is no group {0} registered in the cache manager", Group); raise No_Value with "No group '" & Group & "'"; end Expand; -- -------------------- -- Insert a new cache in the manager. The cache is identified by the given name. -- -------------------- procedure Add_Cache (Manager : in out Cache_Manager; Name : in String; Cache : in Cache_Type_Access) is begin Log.Debug ("Adding cache group {0}", Name); Cache.Next := Manager.First; Cache.Name := Ada.Strings.Unbounded.To_Unbounded_String (Name); Manager.First := Cache; end Add_Cache; -- -------------------- -- Finalize the cache manager releasing every cache group. -- -------------------- overriding procedure Finalize (Manager : in out Cache_Manager) is procedure Free is new Ada.Unchecked_Deallocation (Object => Cache_Type'Class, Name => Cache_Type_Access); Cache : Cache_Type_Access; begin loop Cache := Manager.First; exit when Cache = null; Manager.First := Cache.Next; Free (Cache); end loop; end Finalize; end ADO.Caches;
Add some log and report a message when the No_Value exception is raised
Add some log and report a message when the No_Value exception is raised
Ada
apache-2.0
stcarrez/ada-ado
d9f901096c5c611a505eb64e0115f895050c4772
src/sys/lzma/util-streams-buffered-lzma.ads
src/sys/lzma/util-streams-buffered-lzma.ads
----------------------------------------------------------------------- -- util-streams-buffered-lzma -- LZMA streams -- Copyright (C) 2018 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Encoders; package Util.Streams.Buffered.Lzma is -- ----------------------- -- Compress stream -- ----------------------- -- The <b>Compress_Stream</b> is an output stream which uses the LZMA encoder to -- compress the data before writing it to the output. type Compress_Stream is limited new Util.Streams.Buffered.Output_Buffer_Stream with private; -- Initialize the stream to write on the given stream. -- An internal buffer is allocated for writing the stream. procedure Initialize (Stream : in out Compress_Stream; Output : in Output_Stream_Access; Size : in Natural; Format : in String); -- Close the sink. overriding procedure Close (Stream : in out Compress_Stream); -- Write the buffer array to the output stream. overriding procedure Write (Stream : in out Compress_Stream; Buffer : in Ada.Streams.Stream_Element_Array); -- Flush the buffer by writing on the output stream. -- Raises Data_Error if there is no output stream. overriding procedure Flush (Stream : in out Compress_Stream); private type Compress_Stream is limited new Util.Streams.Buffered.Output_Buffer_Stream with record Transform : Util.Encoders.Transformer_Access; end record; -- Flush the stream and release the buffer. overriding procedure Finalize (Object : in out Compress_Stream); end Util.Streams.Buffered.Lzma;
----------------------------------------------------------------------- -- util-streams-buffered-lzma -- LZMA streams -- Copyright (C) 2018, 2019 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Lzma.Base; use Lzma; package Util.Streams.Buffered.Lzma is -- ----------------------- -- Compress stream -- ----------------------- -- The <b>Compress_Stream</b> is an output stream which uses the LZMA encoder to -- compress the data before writing it to the output. type Compress_Stream is limited new Util.Streams.Buffered.Output_Buffer_Stream with private; -- Initialize the stream to write on the given stream. -- An internal buffer is allocated for writing the stream. overriding procedure Initialize (Stream : in out Compress_Stream; Output : in Output_Stream_Access; Size : in Positive); -- Close the sink. overriding procedure Close (Stream : in out Compress_Stream); -- Write the buffer array to the output stream. overriding procedure Write (Stream : in out Compress_Stream; Buffer : in Ada.Streams.Stream_Element_Array); -- Flush the buffer by writing on the output stream. -- Raises Data_Error if there is no output stream. overriding procedure Flush (Stream : in out Compress_Stream); private type Compress_Stream is limited new Util.Streams.Buffered.Output_Buffer_Stream with record Stream : aliased Base.lzma_stream := Base.LZMA_STREAM_INIT; end record; -- Flush the stream and release the buffer. overriding procedure Finalize (Object : in out Compress_Stream); end Util.Streams.Buffered.Lzma;
Refactor the LZMA buffered stream implementation
Refactor the LZMA buffered stream implementation
Ada
apache-2.0
stcarrez/ada-util,stcarrez/ada-util
8bc07d0361b4f12224e496a885618774fe681df2
src/security.ads
src/security.ads
----------------------------------------------------------------------- -- security -- Security -- Copyright (C) 2010, 2011, 2012 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- -- == Introduction == -- The <tt>Security</tt> package provides security frameworks that allows -- an application to use OpenID or OAuth security frameworks. This security -- framework was first developed within the Ada Server Faces project. -- This package defines abstractions that are close or similar to Java -- security package. -- -- @include security-permissions.ads -- @include security-openid.ads -- @include security-oauth.ads -- @include security-contexts.ads -- @include security-controllers.ads package Security is -- ------------------------------ -- Principal -- ------------------------------ type Principal is limited interface; type Principal_Access is access all Principal'Class; -- -- -- Returns true if the given role is stored in the user principal. -- function Has_Role (User : in Principal; -- Role : in Role_Type) return Boolean is abstract; -- Get the principal name. function Get_Name (From : in Principal) return String is abstract; end Security;
----------------------------------------------------------------------- -- security -- Security -- Copyright (C) 2010, 2011, 2012 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- -- == Introduction == -- The <tt>Security</tt> package provides security frameworks that allows -- an application to use OpenID or OAuth security frameworks. This security -- framework was first developed within the Ada Server Faces project. -- This package defines abstractions that are close or similar to Java -- security package. -- -- @include security-permissions.ads -- @include security-openid.ads -- @include security-oauth.ads -- @include security-contexts.ads -- @include security-controllers.ads package Security is -- ------------------------------ -- Principal -- ------------------------------ type Principal is limited interface; type Principal_Access is access all Principal'Class; -- Get the principal name. function Get_Name (From : in Principal) return String is abstract; end Security;
Make the Principal be a real principal (ie, no knowledge of roles)
Make the Principal be a real principal (ie, no knowledge of roles)
Ada
apache-2.0
stcarrez/ada-security
4e6d8de04e0fd83df356a9bdd4c94594f4496241
awa/regtests/awa-testsuite.adb
awa/regtests/awa-testsuite.adb
----------------------------------------------------------------------- -- Util testsuite - Util Testsuite -- 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.Users.Services.Tests; with AWA.Users.Tests; with AWA.Blogs.Services.Tests; with AWA.Wikis.Parsers.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.Services.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.Converters.Dates; with AWA.Tests; with AWA.Services.Contexts; with AWA.Jobs.Services.Tests; with AWA.Jobs.Modules.Tests; with ASF.Server.Web; with ASF.Server.Tests; 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; Blogs : aliased AWA.Blogs.Modules.Blog_Module; Storages : aliased AWA.Storages.Modules.Storage_Module; Images : aliased AWA.Images.Modules.Image_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.Wikis.Parsers.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.Blogs.Services.Tests.Add_Tests (Ret); AWA.Storages.Services.Tests.Add_Tests (Ret); AWA.Images.Services.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 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.Storages.Modules.NAME, URI => "storages", Module => Storages'Access); Register (App => Application.all'Access, Name => AWA.Images.Modules.NAME, URI => "images", Module => Images'Access); Register (App => Application.all'Access, Name => AWA.Jobs.Modules.NAME, URI => "jobs", Module => Jobs'Access); Register (App => Application.all'Access, Name => AWA.Blogs.Modules.NAME, URI => "blogs", Module => Blogs'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; ASF.Server.Tests.Set_Context (Application.all'Access); end; end if; end Initialize; end AWA.Testsuite;
----------------------------------------------------------------------- -- Util testsuite - Util Testsuite -- 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 AWA.Users.Services.Tests; with AWA.Users.Tests; with AWA.Blogs.Services.Tests; with AWA.Wikis.Parsers.Tests; with AWA.Wikis.Writers.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.Services.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.Converters.Dates; with AWA.Tests; with AWA.Services.Contexts; with AWA.Jobs.Services.Tests; with AWA.Jobs.Modules.Tests; with ASF.Server.Web; with ASF.Server.Tests; 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; Blogs : aliased AWA.Blogs.Modules.Blog_Module; Storages : aliased AWA.Storages.Modules.Storage_Module; Images : aliased AWA.Images.Modules.Image_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.Wikis.Parsers.Tests.Add_Tests (Ret); AWA.Wikis.Writers.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.Blogs.Services.Tests.Add_Tests (Ret); AWA.Storages.Services.Tests.Add_Tests (Ret); AWA.Images.Services.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 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.Storages.Modules.NAME, URI => "storages", Module => Storages'Access); Register (App => Application.all'Access, Name => AWA.Images.Modules.NAME, URI => "images", Module => Images'Access); Register (App => Application.all'Access, Name => AWA.Jobs.Modules.NAME, URI => "jobs", Module => Jobs'Access); Register (App => Application.all'Access, Name => AWA.Blogs.Modules.NAME, URI => "blogs", Module => Blogs'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; ASF.Server.Tests.Set_Context (Application.all'Access); end; end if; end Initialize; end AWA.Testsuite;
Add the new wiki tests in the testsuite
Add the new wiki tests in the testsuite
Ada
apache-2.0
Letractively/ada-awa,Letractively/ada-awa,tectronics/ada-awa,tectronics/ada-awa,Letractively/ada-awa,tectronics/ada-awa
ea7ba3473b0ce8299d0ba3173d06be4e6e25ef34
awa/src/awa-modules-reader.adb
awa/src/awa-modules-reader.adb
----------------------------------------------------------------------- -- awa-modules-reader -- Read module configuration files -- 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.Serialize.IO.XML; with ASF.Applications.Main; with ASF.Navigations.Mappers; with ASF.Servlets.Mappers; with ASF.Beans.Mappers; -- The <b>AWA.Modules.Reader</b> package reads the module configuration files -- and initializes the module. package body AWA.Modules.Reader is -- ------------------------------ -- Read the module configuration file and configure the components -- ------------------------------ procedure Read_Configuration (Plugin : in out Module'Class; File : in String; Context : in EL.Contexts.ELContext_Access) is Reader : Util.Serialize.IO.XML.Parser; Nav : constant ASF.Navigations.Navigation_Handler_Access := Plugin.App.Get_Navigation_Handler; package Bean_Config is new ASF.Beans.Mappers.Reader_Config (Reader, Plugin.Factory'Unchecked_Access, Context); package Navigation_Config is new ASF.Navigations.Mappers.Reader_Config (Reader, Nav); package Servlet_Config is new ASF.Servlets.Mappers.Reader_Config (Reader, Plugin.App.all'Unchecked_Access); pragma Warnings (Off, Bean_Config); pragma Warnings (Off, Navigation_Config); pragma Warnings (Off, Servlet_Config); begin Log.Info ("Reading module configuration file {0}", File); Util.Serialize.IO.Dump (Reader, AWA.Modules.Log); -- Read the configuration file and record managed beans, navigation rules. Reader.Parse (File); end Read_Configuration; end AWA.Modules.Reader;
----------------------------------------------------------------------- -- awa-modules-reader -- Read module configuration files -- 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.Serialize.IO.XML; with ASF.Navigations.Mappers; with ASF.Servlets.Mappers; with ASF.Beans.Mappers; with Security.Permissions; with Security.Controllers.Roles; with AWA.Permissions.Configs; with AWA.Services.Contexts; -- The <b>AWA.Modules.Reader</b> package reads the module configuration files -- and initializes the module. package body AWA.Modules.Reader is -- ------------------------------ -- Read the module configuration file and configure the components -- ------------------------------ procedure Read_Configuration (Plugin : in out Module'Class; File : in String; Context : in EL.Contexts.ELContext_Access) is Reader : Util.Serialize.IO.XML.Parser; Ctx : AWA.Services.Contexts.Service_Context; Nav : constant ASF.Navigations.Navigation_Handler_Access := Plugin.App.Get_Navigation_Handler; Sec : constant Security.Permissions.Permission_Manager_Access := Plugin.App.Get_Permission_Manager; begin Log.Info ("Reading module configuration file {0}", File); Ctx.Set_Context (Plugin.App.all'Unchecked_Access, null); declare package Bean_Config is new ASF.Beans.Mappers.Reader_Config (Reader, Plugin.Factory'Unchecked_Access, Context); package Navigation_Config is new ASF.Navigations.Mappers.Reader_Config (Reader, Nav); package Servlet_Config is new ASF.Servlets.Mappers.Reader_Config (Reader, Plugin.App.all'Unchecked_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); pragma Warnings (Off, Bean_Config); pragma Warnings (Off, Navigation_Config); pragma Warnings (Off, Servlet_Config); pragma Warnings (Off, Policy_Config); pragma Warnings (Off, Role_Config); pragma Warnings (Off, Entity_Config); begin Util.Serialize.IO.Dump (Reader, AWA.Modules.Log); -- Read the configuration file and record managed beans, navigation rules. Reader.Parse (File); end; end Read_Configuration; end AWA.Modules.Reader;
Read the XML entity-permission from the module XML files
Read the XML entity-permission from the module XML files
Ada
apache-2.0
tectronics/ada-awa,Letractively/ada-awa,Letractively/ada-awa,Letractively/ada-awa,tectronics/ada-awa,tectronics/ada-awa
cae708c8e3c4d8816975359704cb2a10522b3e10
examples/orka/orka_test-test_4_mdi.adb
examples/orka/orka_test-test_4_mdi.adb
-- Copyright (c) 2016 onox <[email protected]> -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. with GL.Buffers; with GL.Objects.Buffers; with GL.Types.Indirect; with Orka.Buffers.MDI; with Orka.Meshes.Attributes; with Orka.Programs.Modules; with GL_Test.Display_Backend; procedure Orka_Test.Test_4_MDI is Initialized : constant Boolean := GL_Test.Display_Backend.Init (Major => 3, Minor => 2, Width => 500, Height => 500, Resizable => False); pragma Unreferenced (Initialized); use Orka.Meshes; use Orka.Programs; use GL.Objects.Buffers; function Load_Mesh (Program : Orka.Programs.Program; MDI_Buffers : out Orka.Buffers.MDI.MDI_Buffers) return Vertex_Format is use GL.Types; Vertices_1 : constant Indirect.Single_Array_Access := new Single_Array'(-0.3, 0.5, -1.0, -0.8, -0.5, -1.0, 0.2, -0.5, -1.0); Vertices_2 : constant Indirect.Single_Array_Access := new Single_Array'(-0.2, 0.5, -1.0, 0.3, -0.5, -1.0, 0.8, 0.5, -1.0); Indices_1 : constant Indirect.UInt_Array_Access := new UInt_Array'(0, 1, 2); Indices_2 : constant Indirect.UInt_Array_Access := new UInt_Array'(0, 1, 2); MDI : Orka.Buffers.MDI.Batch := Orka.Buffers.MDI.Create_Batch (3); Instance_ID : Natural; begin -- Create one VBO, one IBO, and a buffer containing the draw commands MDI.Append (Vertices_1, Indices_1, Instance_ID); MDI.Append (Vertices_2, Indices_2, Instance_ID); pragma Assert (MDI.Length = 2); MDI_Buffers := MDI.Create_Buffers (Storage_Bits'(others => False)); -- Create mesh and its attributes return Result : Vertex_Format := Orka.Meshes.Create_Vertex_Format (Triangles) do declare Attributes_Pos : Attributes.Attribute_Buffer := Result.Add_Attribute_Buffer (Single_Type); Attributes_Ins : Attributes.Attribute_Buffer := Result.Add_Attribute_Buffer (UInt_Type); begin Attributes_Pos.Add_Attribute (Program.Attribute_Location ("in_Position"), 3); Attributes_Pos.Set_Buffer (MDI_Buffers.Vertex_Buffer); Attributes_Ins.Add_Attribute (Program.Attribute_Location ("in_InstanceID"), 1); Attributes_Ins.Set_Per_Instance (True); Attributes_Ins.Set_Buffer (MDI_Buffers.Instances_Buffer); end; Result.Set_Index_Buffer (MDI_Buffers.Index_Buffer); end return; end Load_Mesh; use GL.Buffers; MDI_Buffers : Orka.Buffers.MDI.MDI_Buffers; Program_1 : constant Program := Orka.Programs.Create_Program (Modules.Create_Module (VS => "../examples/orka/shaders/test-4-module-1.vert", FS => "../examples/orka/shaders/test-4-module-1.frag")); Mesh_1 : constant Vertex_Format := Load_Mesh (Program_1, MDI_Buffers); begin Program_1.Use_Program; while not GL_Test.Display_Backend.Get_Window.Should_Close loop Clear (Buffer_Bits'(Color => True, Depth => True, others => False)); Mesh_1.Draw_Indirect (MDI_Buffers.Command_Buffer); GL_Test.Display_Backend.Swap_Buffers_And_Poll_Events; end loop; GL_Test.Display_Backend.Shutdown; end Orka_Test.Test_4_MDI;
-- Copyright (c) 2016 onox <[email protected]> -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. with GL.Buffers; with GL.Objects.Buffers; with GL.Types.Indirect; with Orka.Buffers.MDI; with Orka.Meshes.Attributes; with Orka.Programs.Modules; with GL_Test.Display_Backend; procedure Orka_Test.Test_4_MDI is Initialized : constant Boolean := GL_Test.Display_Backend.Init (Major => 3, Minor => 2, Width => 500, Height => 500, Resizable => False); pragma Unreferenced (Initialized); use Orka.Meshes; use Orka.Programs; use GL.Objects.Buffers; function Load_Mesh (Program : Orka.Programs.Program; MDI_Buffers : out Orka.Buffers.MDI.MDI_Buffers) return Vertex_Format is use GL.Types; Vertices_1 : constant Indirect.Single_Array_Access := new Single_Array'(-0.3, 0.5, -1.0, -0.8, -0.5, -1.0, 0.2, -0.5, -1.0); Vertices_2 : constant Indirect.Single_Array_Access := new Single_Array'(-0.2, 0.5, -1.0, 0.3, -0.5, -1.0, 0.8, 0.5, -1.0); Indices_1 : constant Indirect.UInt_Array_Access := new UInt_Array'(0, 1, 2); Indices_2 : constant Indirect.UInt_Array_Access := new UInt_Array'(0, 1, 2); MDI : Orka.Buffers.MDI.Batch := Orka.Buffers.MDI.Create_Batch (3); Instance_ID : Natural; begin -- Create one VBO, one IBO, and a buffer containing the draw commands MDI.Append (Vertices_1, Indices_1, Instance_ID); MDI.Append (Vertices_2, Indices_2, Instance_ID); pragma Assert (MDI.Length = 2); MDI_Buffers := MDI.Create_Buffers (Storage_Bits'(others => False)); -- Create mesh and its attributes return Result : Vertex_Format := Orka.Meshes.Create_Vertex_Format (Triangles) do declare Attributes_Pos : Attributes.Attribute_Buffer := Result.Add_Attribute_Buffer (Half_Type); Attributes_Ins : Attributes.Attribute_Buffer := Result.Add_Attribute_Buffer (UInt_Type); begin Attributes_Pos.Add_Attribute (Program.Attribute_Location ("in_Position"), 3); Attributes_Pos.Set_Buffer (MDI_Buffers.Vertex_Buffer); Attributes_Ins.Add_Attribute (Program.Attribute_Location ("in_InstanceID"), 1); Attributes_Ins.Set_Per_Instance (True); Attributes_Ins.Set_Buffer (MDI_Buffers.Instances_Buffer); end; Result.Set_Index_Buffer (MDI_Buffers.Index_Buffer); end return; end Load_Mesh; use GL.Buffers; MDI_Buffers : Orka.Buffers.MDI.MDI_Buffers; Program_1 : constant Program := Orka.Programs.Create_Program (Modules.Create_Module (VS => "../examples/orka/shaders/test-4-module-1.vert", FS => "../examples/orka/shaders/test-4-module-1.frag")); Mesh_1 : constant Vertex_Format := Load_Mesh (Program_1, MDI_Buffers); begin Program_1.Use_Program; while not GL_Test.Display_Backend.Get_Window.Should_Close loop Clear (Buffer_Bits'(Color => True, Depth => True, others => False)); Mesh_1.Draw_Indirect (MDI_Buffers.Command_Buffer); GL_Test.Display_Backend.Swap_Buffers_And_Poll_Events; end loop; GL_Test.Display_Backend.Shutdown; end Orka_Test.Test_4_MDI;
Fix MDI example
examples: Fix MDI example Signed-off-by: onox <[email protected]>
Ada
apache-2.0
onox/orka
bbcd17ae902798793ad3e55fc0d454da743dc9a3
regtests/ado-testsuite.adb
regtests/ado-testsuite.adb
----------------------------------------------------------------------- -- ado-testsuite -- Testsuite for ADO -- Copyright (C) 2009, 2010, 2011, 2012 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with ADO.Tests; with ADO.Sequences.Tests; with ADO.Schemas.Tests; with ADO.Objects.Tests; with ADO.Queries.Tests; with ADO.Parameters.Tests; package body ADO.Testsuite is use ADO.Tests; procedure Drivers (Suite : in Util.Tests.Access_Test_Suite); procedure Drivers (Suite : in Util.Tests.Access_Test_Suite) is separate; 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 ADO.Parameters.Tests.Add_Tests (Ret); ADO.Sequences.Tests.Add_Tests (Ret); ADO.Objects.Tests.Add_Tests (Ret); ADO.Tests.Add_Tests (Ret); ADO.Schemas.Tests.Add_Tests (Ret); Drivers (Ret); ADO.Queries.Tests.Add_Tests (Ret); return Ret; end Suite; end ADO.Testsuite;
----------------------------------------------------------------------- -- ado-testsuite -- Testsuite for ADO -- 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 ADO.Tests; with ADO.Sequences.Tests; with ADO.Schemas.Tests; with ADO.Objects.Tests; with ADO.Queries.Tests; with ADO.Parameters.Tests; with ADO.Datasets.Tests; package body ADO.Testsuite is use ADO.Tests; procedure Drivers (Suite : in Util.Tests.Access_Test_Suite); procedure Drivers (Suite : in Util.Tests.Access_Test_Suite) is separate; 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 ADO.Parameters.Tests.Add_Tests (Ret); ADO.Sequences.Tests.Add_Tests (Ret); ADO.Objects.Tests.Add_Tests (Ret); ADO.Tests.Add_Tests (Ret); ADO.Schemas.Tests.Add_Tests (Ret); Drivers (Ret); ADO.Queries.Tests.Add_Tests (Ret); ADO.Datasets.Tests.Add_Tests (Ret); return Ret; end Suite; end ADO.Testsuite;
Add the new unit tests
Add the new unit tests
Ada
apache-2.0
Letractively/ada-ado
024f5bc835ccca4108d9082285ad14d4a18b9504
src/babel-files-signatures.ads
src/babel-files-signatures.ads
----------------------------------------------------------------------- -- babel-files-signatures -- Signatures calculation -- 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 Babel.Files; with Babel.Files.Buffers; with Babel.Files.Maps; package Babel.Files.Signatures is -- Compute the SHA1 signature of the data stored in the buffer. procedure Sha1 (Buffer : in Babel.Files.Buffers.Buffer; Result : out Util.Encoders.SHA1.Hash_Array); -- Write the SHA1 checksum for the files stored in the map. procedure Save_Checksum (Path : in String; Files : in Babel.Files.Maps.File_Map); end Babel.Files.Signatures;
----------------------------------------------------------------------- -- babel-files-signatures -- Signatures calculation -- 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 Babel.Files; with Babel.Files.Buffers; with Babel.Files.Maps; with Babel.Streams.Refs; package Babel.Files.Signatures is -- Compute the SHA1 signature of the data stored in the buffer. procedure Sha1 (Buffer : in Babel.Files.Buffers.Buffer; Result : out Util.Encoders.SHA1.Hash_Array); -- Compute the SHA1 signature of the file stream. procedure Sha1 (Stream : in Babel.Streams.Refs.Stream_Ref; Result : out Util.Encoders.SHA1.Hash_Array); -- Write the SHA1 checksum for the files stored in the map. procedure Save_Checksum (Path : in String; Files : in Babel.Files.Maps.File_Map); end Babel.Files.Signatures;
Define Sha1 procedure with a Stream_Ref object
Define Sha1 procedure with a Stream_Ref object
Ada
apache-2.0
stcarrez/babel
c59b517b8a70843a2091535e2f437a6986e7a1c4
src/gen-model-mappings.ads
src/gen-model-mappings.ads
----------------------------------------------------------------------- -- gen-model-mappings -- Type mappings for Code Generator -- Copyright (C) 2011, 2012 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Strings.Unbounded; with Ada.Containers.Hashed_Maps; with Ada.Strings.Unbounded.Hash; with Util.Beans.Objects; -- The <b>Gen.Model.Mappings</b> package controls the mappings to convert an XML -- type into the Ada type. package Gen.Model.Mappings is ADA_MAPPING : constant String := "Ada05"; MySQL_MAPPING : constant String := "MySQL"; SQLite_MAPPING : constant String := "SQLite"; type Basic_Type is (T_BOOLEAN, T_INTEGER, T_DATE, T_ENUM, T_IDENTIFIER, T_STRING, T_BLOB); -- ------------------------------ -- Mapping Definition -- ------------------------------ type Mapping_Definition is new Definition with record Target : Ada.Strings.Unbounded.Unbounded_String; Kind : Basic_Type := T_INTEGER; end record; type Mapping_Definition_Access is access all Mapping_Definition'Class; -- Get the value identified by the name. -- If the name cannot be found, the method should return the Null object. overriding function Get_Value (From : Mapping_Definition; Name : String) return Util.Beans.Objects.Object; -- Find the mapping for the given type name. function Find_Type (Name : in Ada.Strings.Unbounded.Unbounded_String) return Mapping_Definition_Access; procedure Register_Type (Name : in String; Mapping : in Mapping_Definition_Access; Kind : in Basic_Type); -- Register a type mapping <b>From</b> that is mapped to <b>Target</b>. procedure Register_Type (Target : in String; From : in String; Kind : in Basic_Type); -- Setup the type mapping for the language identified by the given name. procedure Set_Mapping_Name (Name : in String); package Mapping_Maps is new Ada.Containers.Hashed_Maps (Key_Type => Ada.Strings.Unbounded.Unbounded_String, Element_Type => Mapping_Definition_Access, Hash => Ada.Strings.Unbounded.Hash, Equivalent_Keys => Ada.Strings.Unbounded."="); end Gen.Model.Mappings;
----------------------------------------------------------------------- -- gen-model-mappings -- Type mappings for Code Generator -- Copyright (C) 2011, 2012 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Strings.Unbounded; with Ada.Containers.Hashed_Maps; with Ada.Strings.Unbounded.Hash; with Util.Beans.Objects; -- The <b>Gen.Model.Mappings</b> package controls the mappings to convert an XML -- type into the Ada type. package Gen.Model.Mappings is ADA_MAPPING : constant String := "Ada05"; MySQL_MAPPING : constant String := "MySQL"; SQLite_MAPPING : constant String := "SQLite"; type Basic_Type is (T_BOOLEAN, T_INTEGER, T_DATE, T_ENUM, T_IDENTIFIER, T_STRING, T_BLOB); -- ------------------------------ -- Mapping Definition -- ------------------------------ type Mapping_Definition is new Definition with record Target : Ada.Strings.Unbounded.Unbounded_String; Kind : Basic_Type := T_INTEGER; end record; type Mapping_Definition_Access is access all Mapping_Definition'Class; -- Get the value identified by the name. -- If the name cannot be found, the method should return the Null object. overriding function Get_Value (From : Mapping_Definition; Name : String) return Util.Beans.Objects.Object; -- Find the mapping for the given type name. function Find_Type (Name : in Ada.Strings.Unbounded.Unbounded_String) return Mapping_Definition_Access; procedure Register_Type (Name : in String; Mapping : in Mapping_Definition_Access; Kind : in Basic_Type); -- Register a type mapping <b>From</b> that is mapped to <b>Target</b>. procedure Register_Type (Target : in String; From : in String; Kind : in Basic_Type); -- Setup the type mapping for the language identified by the given name. procedure Set_Mapping_Name (Name : in String); package Mapping_Maps is new Ada.Containers.Hashed_Maps (Key_Type => Ada.Strings.Unbounded.Unbounded_String, Element_Type => Mapping_Definition_Access, Hash => Ada.Strings.Unbounded.Hash, Equivalent_Keys => Ada.Strings.Unbounded."="); subtype Map is Mapping_Maps.Map; subtype Cursor is Mapping_Maps.Cursor; end Gen.Model.Mappings;
Define the Map and Cursor subtypes
Define the Map and Cursor subtypes
Ada
apache-2.0
stcarrez/dynamo,stcarrez/dynamo,stcarrez/dynamo
6f1477f6553b779d9aac4e1d0738e8d129ca3d0f
regtests/asf-servlets-tests.ads
regtests/asf-servlets-tests.ads
----------------------------------------------------------------------- -- Servlets Tests - Unit tests for ASF.Servlets -- Copyright (C) 2010, 2011, 2012, 2013, 2015 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Tests; package ASF.Servlets.Tests is procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite); type Test_Servlet1 is new Servlet with null record; procedure Do_Get (Server : in Test_Servlet1; Request : in out Requests.Request'Class; Response : in out Responses.Response'Class); type Test_Servlet2 is new Test_Servlet1 with null record; procedure Do_Post (Server : in Test_Servlet2; Request : in out Requests.Request'Class; Response : in out Responses.Response'Class); type Test is new Util.Tests.Test with record Writer : Integer; end record; -- Test creation of session procedure Test_Create_Servlet (T : in out Test); -- Test add servlet procedure Test_Add_Servlet (T : in out Test); -- Test getting a resource path procedure Test_Get_Resource (T : in out Test); procedure Test_Request_Dispatcher (T : in out Test); -- Test mapping and servlet path on a request. procedure Test_Servlet_Path (T : in out Test); -- Test mapping and servlet path on a request. procedure Test_Filter_Mapping (T : in out Test); -- Test execution of filters procedure Test_Filter_Execution (T : in out Test); -- Test execution of filters on complex mapping. procedure Test_Complex_Filter_Execution (T : in out Test); -- Check that the mapping for the given URI matches the server. procedure Check_Mapping (T : in out Test; Ctx : in Servlet_Registry; URI : in String; Server : in Servlet_Access; Filter : in Natural := 0); -- Check that the request is done on the good servlet and with the correct servlet path -- and path info. procedure Check_Request (T : in out Test; Ctx : in Servlet_Registry; URI : in String; Servlet_Path : in String; Path_Info : in String); end ASF.Servlets.Tests;
----------------------------------------------------------------------- -- Servlets Tests - Unit tests for ASF.Servlets -- Copyright (C) 2010, 2011, 2012, 2013, 2015 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Tests; package ASF.Servlets.Tests is procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite); type Test_Servlet1 is new Servlet with null record; procedure Do_Get (Server : in Test_Servlet1; Request : in out Requests.Request'Class; Response : in out Responses.Response'Class); type Test_Servlet2 is new Test_Servlet1 with null record; procedure Do_Post (Server : in Test_Servlet2; Request : in out Requests.Request'Class; Response : in out Responses.Response'Class); type Test is new Util.Tests.Test with record Writer : Integer; end record; -- Test creation of session procedure Test_Create_Servlet (T : in out Test); -- Test add servlet procedure Test_Add_Servlet (T : in out Test); -- Test getting a resource path procedure Test_Get_Resource (T : in out Test); procedure Test_Request_Dispatcher (T : in out Test); -- Test mapping and servlet path on a request. procedure Test_Servlet_Path (T : in out Test); -- Test mapping and servlet path on a request. procedure Test_Filter_Mapping (T : in out Test); -- Test execution of filters procedure Test_Filter_Execution (T : in out Test); -- Test execution of filters on complex mapping. procedure Test_Complex_Filter_Execution (T : in out Test); -- Test execution of the cache control filter. procedure Test_Cache_Control_Filter (T : in out Test); -- Check that the mapping for the given URI matches the server. procedure Check_Mapping (T : in out Test; Ctx : in Servlet_Registry; URI : in String; Server : in Servlet_Access; Filter : in Natural := 0); -- Check that the request is done on the good servlet and with the correct servlet path -- and path info. procedure Check_Request (T : in out Test; Ctx : in Servlet_Registry; URI : in String; Servlet_Path : in String; Path_Info : in String); end ASF.Servlets.Tests;
Declare the Test_Cache_Control_Filter procedure
Declare the Test_Cache_Control_Filter procedure
Ada
apache-2.0
stcarrez/ada-asf,stcarrez/ada-asf,stcarrez/ada-asf
eba9a555ab50dd65ae403dc7faf9c9c2a668ffc8
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; 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_Base64_Stream (T : in out Test); procedure Test_AES_Stream (T : in out Test); end Util.Streams.Tests;
----------------------------------------------------------------------- -- 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;
Declare Test_AES procedure and remove Test_AES_Stream
Declare Test_AES procedure and remove Test_AES_Stream
Ada
apache-2.0
stcarrez/ada-util,stcarrez/ada-util
c99b8595b7a2bdbfa7ba31184d0c0f5b6813eef1
src/util-events-timers.adb
src/util-events-timers.adb
----------------------------------------------------------------------- -- util-events-timers -- Timer list management -- Copyright (C) 2017 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Unchecked_Deallocation; package body Util.Events.Timers is use type Ada.Real_Time.Time; procedure Free is new Ada.Unchecked_Deallocation (Object => Timer_Node, Name => Timer_Node_Access); -- ----------------------- -- Repeat the timer. -- ----------------------- procedure Repeat (Event : in out Timer_Ref; In_Time : in Ada.Real_Time.Time_Span) is Timer : constant Timer_Node_Access := Event.Value; begin if Timer /= null and then Timer.List /= null then Timer.List.Add (Timer, Timer.Deadline + In_Time); end if; end Repeat; -- ----------------------- -- Cancel the timer. -- ----------------------- procedure Cancel (Event : in out Timer_Ref) is begin if Event.Value /= null and then Event.Value.List /= null then Event.Value.List.all.Cancel (Event.Value); Event.Value.List := null; end if; end Cancel; -- ----------------------- -- Check if the timer is ready to be executed. -- ----------------------- function Is_Scheduled (Event : in Timer_Ref) return Boolean is begin return Event.Value /= null and then Event.Value.List /= null; end Is_Scheduled; -- ----------------------- -- Returns the deadline time for the timer execution. -- Returns Time'Last if the timer is not scheduled. -- ----------------------- function Time_Of_Event (Event : in Timer_Ref) return Ada.Real_Time.Time is begin return (if Event.Value /= null then Event.Value.Deadline else Ada.Real_Time.Time_Last); end Time_Of_Event; -- ----------------------- -- Set a timer to be called at the given time. -- ----------------------- procedure Set_Timer (List : in out Timer_List; Handler : in Timer_Access; Event : in out Timer_Ref'Class; At_Time : in Ada.Real_Time.Time) is Timer : Timer_Node_Access := Event.Value; begin if Timer = null then Event.Value := new Timer_Node; Timer := Event.Value; end if; Timer.Handler := Handler; -- Cancel the timer if it is part of another timer manager. if Timer.List /= null and Timer.List /= List.Manager'Unchecked_Access then Timer.List.Cancel (Timer); end if; -- Update the timer. Timer.List := List.Manager'Unchecked_Access; List.Manager.Add (Timer, At_Time); end Set_Timer; -- ----------------------- -- Process the timer handlers that have passed the deadline and return the next -- deadline. The <tt>Max_Count</tt> parameter allows to limit the number of timer handlers -- that are called by operation. The default is not limited. -- ----------------------- procedure Process (List : in out Timer_List; Timeout : out Ada.Real_Time.Time; Max_Count : in Natural := Natural'Last) is Timer : Timer_Ref; begin loop List.Manager.Find_Next (Timeout, Timer); exit when not Timer.Is_Scheduled; Timer.Value.Handler.Time_Handler (Timer); end loop; end Process; overriding procedure Adjust (Object : in out Timer_Ref) is begin if Object.Value /= null then Util.Concurrent.Counters.Increment (Object.Value.Counter); end if; end Adjust; overriding procedure Finalize (Object : in out Timer_Ref) is Is_Zero : Boolean; begin if Object.Value /= null then Util.Concurrent.Counters.Decrement (Object.Value.Counter, Is_Zero); if Is_Zero then Free (Object.Value); else Object.Value := null; end if; end if; end Finalize; protected body Timer_Manager is procedure Remove (Timer : in Timer_Node_Access) is begin if List = Timer then List := Timer.Next; Timer.Prev := null; if List /= null then List.Prev := null; end if; elsif Timer.Prev /= null then Timer.Prev.Next := Timer.Next; Timer.Next.Prev := Timer.Prev; else return; end if; Timer.Next := null; Timer.Prev := null; Timer.List := null; end Remove; -- ----------------------- -- Add a timer. -- ----------------------- procedure Add (Timer : in Timer_Node_Access; Deadline : in Ada.Real_Time.Time) is Current : Timer_Node_Access := List; Prev : Timer_Node_Access; begin Util.Concurrent.Counters.Increment (Timer.Counter); if Timer.List /= null then Remove (Timer); end if; Timer.Deadline := Deadline; while Current /= null loop if Current.Deadline < Deadline then if Prev = null then List := Timer; else Prev.Next := Timer; end if; Timer.Next := Current; Current.Prev := Timer; return; end if; Prev := Current; Current := Current.Next; end loop; if Prev = null then List := Timer; Timer.Prev := null; else Prev.Next := Timer; Timer.Prev := Prev; end if; Timer.Next := null; end Add; -- ----------------------- -- Cancel a timer. -- ----------------------- procedure Cancel (Timer : in out Timer_Node_Access) is Is_Zero : Boolean; begin if Timer.List = null then return; end if; Remove (Timer); Util.Concurrent.Counters.Decrement (Timer.Counter, Is_Zero); if Is_Zero then Free (Timer); end if; end Cancel; -- ----------------------- -- Find the next timer to be executed or return the next deadline. -- ----------------------- procedure Find_Next (Deadline : out Ada.Real_Time.Time; Timer : in out Timer_Ref) is Now : constant Ada.Real_Time.Time := Ada.Real_Time.Clock; begin if List = null then Timer.Finalize; Deadline := Ada.Real_Time.Time_Last; elsif List.Deadline < Now then Timer.Value := List; Util.Concurrent.Counters.Increment (Timer.Value.Counter); List := List.Next; if List /= null then List.Prev := null; Deadline := List.Deadline; else Deadline := Ada.Real_Time.Time_Last; end if; else Deadline := List.Deadline; Timer.Finalize; end if; end Find_Next; end Timer_Manager; overriding procedure Finalize (Object : in out Timer_List) is begin null; end Finalize; end Util.Events.Timers;
----------------------------------------------------------------------- -- util-events-timers -- Timer list management -- Copyright (C) 2017 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Unchecked_Deallocation; package body Util.Events.Timers is use type Ada.Real_Time.Time; procedure Free is new Ada.Unchecked_Deallocation (Object => Timer_Node, Name => Timer_Node_Access); -- ----------------------- -- Repeat the timer. -- ----------------------- procedure Repeat (Event : in out Timer_Ref; In_Time : in Ada.Real_Time.Time_Span) is Timer : constant Timer_Node_Access := Event.Value; begin if Timer /= null and then Timer.List /= null then Timer.List.Add (Timer, Timer.Deadline + In_Time); end if; end Repeat; -- ----------------------- -- Cancel the timer. -- ----------------------- procedure Cancel (Event : in out Timer_Ref) is begin if Event.Value /= null and then Event.Value.List /= null then Event.Value.List.all.Cancel (Event.Value); Event.Value.List := null; end if; end Cancel; -- ----------------------- -- Check if the timer is ready to be executed. -- ----------------------- function Is_Scheduled (Event : in Timer_Ref) return Boolean is begin return Event.Value /= null and then Event.Value.List /= null; end Is_Scheduled; -- ----------------------- -- Returns the deadline time for the timer execution. -- Returns Time'Last if the timer is not scheduled. -- ----------------------- function Time_Of_Event (Event : in Timer_Ref) return Ada.Real_Time.Time is begin return (if Event.Value /= null then Event.Value.Deadline else Ada.Real_Time.Time_Last); end Time_Of_Event; -- ----------------------- -- Set a timer to be called at the given time. -- ----------------------- procedure Set_Timer (List : in out Timer_List; Handler : in Timer_Access; Event : in out Timer_Ref'Class; At_Time : in Ada.Real_Time.Time) is Timer : Timer_Node_Access := Event.Value; begin if Timer = null then Event.Value := new Timer_Node; Timer := Event.Value; end if; Timer.Handler := Handler; -- Cancel the timer if it is part of another timer manager. if Timer.List /= null and Timer.List /= List.Manager'Unchecked_Access then Timer.List.Cancel (Timer); end if; -- Update the timer. Timer.List := List.Manager'Unchecked_Access; List.Manager.Add (Timer, At_Time); end Set_Timer; -- ----------------------- -- Process the timer handlers that have passed the deadline and return the next -- deadline. The <tt>Max_Count</tt> parameter allows to limit the number of timer handlers -- that are called by operation. The default is not limited. -- ----------------------- procedure Process (List : in out Timer_List; Timeout : out Ada.Real_Time.Time; Max_Count : in Natural := Natural'Last) is Timer : Timer_Ref; begin loop List.Manager.Find_Next (Timeout, Timer); exit when not Timer.Is_Scheduled; Timer.Value.Handler.Time_Handler (Timer); end loop; end Process; overriding procedure Adjust (Object : in out Timer_Ref) is begin if Object.Value /= null then Util.Concurrent.Counters.Increment (Object.Value.Counter); end if; end Adjust; overriding procedure Finalize (Object : in out Timer_Ref) is Is_Zero : Boolean; begin if Object.Value /= null then Util.Concurrent.Counters.Decrement (Object.Value.Counter, Is_Zero); if Is_Zero then Free (Object.Value); else Object.Value := null; end if; end if; end Finalize; protected body Timer_Manager is procedure Remove (Timer : in Timer_Node_Access) is begin if List = Timer then List := Timer.Next; Timer.Prev := null; if List /= null then List.Prev := null; end if; elsif Timer.Prev /= null then Timer.Prev.Next := Timer.Next; Timer.Next.Prev := Timer.Prev; else return; end if; Timer.Next := null; Timer.Prev := null; Timer.List := null; end Remove; -- ----------------------- -- Add a timer. -- ----------------------- procedure Add (Timer : in Timer_Node_Access; Deadline : in Ada.Real_Time.Time) is Current : Timer_Node_Access := List; Prev : Timer_Node_Access; begin Util.Concurrent.Counters.Increment (Timer.Counter); if Timer.List /= null then Remove (Timer); end if; Timer.Deadline := Deadline; while Current /= null loop if Current.Deadline < Deadline then if Prev = null then List := Timer; else Prev.Next := Timer; end if; Timer.Next := Current; Current.Prev := Timer; return; end if; Prev := Current; Current := Current.Next; end loop; if Prev = null then List := Timer; Timer.Prev := null; else Prev.Next := Timer; Timer.Prev := Prev; end if; Timer.Next := null; end Add; -- ----------------------- -- Cancel a timer. -- ----------------------- procedure Cancel (Timer : in out Timer_Node_Access) is Is_Zero : Boolean; begin if Timer.List = null then return; end if; Remove (Timer); Util.Concurrent.Counters.Decrement (Timer.Counter, Is_Zero); if Is_Zero then Free (Timer); end if; end Cancel; -- ----------------------- -- Find the next timer to be executed or return the next deadline. -- ----------------------- procedure Find_Next (Deadline : out Ada.Real_Time.Time; Timer : in out Timer_Ref) is Now : constant Ada.Real_Time.Time := Ada.Real_Time.Clock; begin Timer.Finalize; if List = null then Deadline := Ada.Real_Time.Time_Last; elsif List.Deadline < Now then Timer.Value := List; List := List.Next; if List /= null then List.Prev := null; Deadline := List.Deadline; else Deadline := Ada.Real_Time.Time_Last; end if; else Deadline := List.Deadline; end if; end Find_Next; end Timer_Manager; overriding procedure Finalize (Object : in out Timer_List) is begin null; end Finalize; end Util.Events.Timers;
Fix the Find_Next procedure to avoid updating the reference counter when not necessary
Fix the Find_Next procedure to avoid updating the reference counter when not necessary
Ada
apache-2.0
stcarrez/ada-util,stcarrez/ada-util
6883607bb57b1e5879c0008dc21afd8cdef3fca5
regtests/asf-applications-tests.adb
regtests/asf-applications-tests.adb
----------------------------------------------------------------------- -- asf-applications-tests - ASF Application tests using ASFUnit -- Copyright (C) 2011 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Tests; with Util.Test_Caller; with ASF.Tests; with ASF.Events.Actions; with ASF.Requests.Mockup; with ASF.Responses.Mockup; with ASF.Applications.Main; package body ASF.Applications.Tests is use ASF.Tests; use Util.Tests; package Caller is new Util.Test_Caller (Test); procedure Add_Tests (Suite : AUnit.Test_Suites.Access_Test_Suite) is begin Caller.Add_Test (Suite, "Test service HTTP invalid method", Test_Invalid_Request'Access); Caller.Add_Test (Suite, "Test service HTTP GET (File_Servlet)", Test_Get_File'Access); Caller.Add_Test (Suite, "Test service HTTP GET 404", Test_Get_404'Access); Caller.Add_Test (Suite, "Test service HTTP GET (Measure_Servlet)", Test_Get_Measures'Access); Caller.Add_Test (Suite, "Test service HTTP POST+INVOKE_APPLICATION", Test_Form_Post'Access); Caller.Add_Test (Suite, "Test service HTTP POST+PROCESS_VALIDATION", Test_Form_Post_Validation_Error'Access); end Add_Tests; package Save_Binding is new ASF.Events.Actions.Action_Method.Bind (Bean => Form_Bean, Method => Save, Name => "save"); Binding_Array : aliased constant Util.Beans.Methods.Method_Binding_Array := (Save_Binding.Proxy'Access, Save_Binding.Proxy'Access); -- ------------------------------ -- Get the value identified by the name. -- ------------------------------ overriding function Get_Value (From : in Form_Bean; Name : in String) return Util.Beans.Objects.Object is begin if Name = "email" then return Util.Beans.Objects.To_Object (From.Email); elsif Name = "password" then return Util.Beans.Objects.To_Object (From.Password); elsif Name = "name" then return Util.Beans.Objects.To_Object (From.Name); else return Util.Beans.Objects.Null_Object; end if; end Get_Value; -- ------------------------------ -- Set the value identified by the name. -- ------------------------------ overriding procedure Set_Value (From : in out Form_Bean; Name : in String; Value : in Util.Beans.Objects.Object) is begin if Name = "email" then From.Email := Util.Beans.Objects.To_Unbounded_String (Value); elsif Name = "password" then From.Password := Util.Beans.Objects.To_Unbounded_String (Value); elsif Name = "name" then From.Name := Util.Beans.Objects.To_Unbounded_String (Value); end if; end Set_Value; -- ------------------------------ -- This bean provides some methods that can be used in a Method_Expression -- ------------------------------ overriding function Get_Method_Bindings (From : in Form_Bean) return Util.Beans.Methods.Method_Binding_Array_Access is pragma Unreferenced (From); begin return Binding_Array'Access; end Get_Method_Bindings; -- ------------------------------ -- Initialize the test application -- ------------------------------ overriding procedure Set_Up (T : in out Test) is pragma Unreferenced (T); use type ASF.Applications.Main.Application_Access; begin if ASF.Tests.Get_Application = null then ASF.Tests.Initialize (Util.Tests.Get_Properties); end if; end Set_Up; -- ------------------------------ -- Action to authenticate a user (password authentication). -- ------------------------------ procedure Save (Data : in out Form_Bean; Outcome : in out Unbounded_String) is begin Outcome := To_Unbounded_String ("success"); end Save; -- ------------------------------ -- Test an invalid HTTP request. -- ------------------------------ procedure Test_Invalid_Request (T : in out Test) is Request : ASF.Requests.Mockup.Request; Reply : ASF.Responses.Mockup.Response; begin -- Unknown method Request.Set_Method ("BLAB"); Request.Set_Request_URI ("/asfunit/views/set.xhtml"); Do_Req (Request, Reply); Assert_Equals (T, ASF.Responses.SC_NOT_IMPLEMENTED, Reply.Get_Status, "Invalid response"); -- PUT on a file is not allowed Request.Set_Method ("PUT"); Request.Set_Request_URI ("/asfunit/views/set.xhtml"); Do_Req (Request, Reply); Assert_Equals (T, ASF.Responses.SC_METHOD_NOT_ALLOWED, Reply.Get_Status, "Invalid response"); -- POST on a file is not allowed Request.Set_Method ("POST"); Request.Set_Request_URI ("/asfunit/views/set.xhtml"); Do_Req (Request, Reply); Assert_Equals (T, ASF.Responses.SC_METHOD_NOT_ALLOWED, Reply.Get_Status, "Invalid response"); -- DELETE on a file is not allowed Request.Set_Method ("DELETE"); Request.Set_Request_URI ("/asfunit/views/set.xhtml"); Do_Req (Request, Reply); Assert_Equals (T, ASF.Responses.SC_METHOD_NOT_ALLOWED, Reply.Get_Status, "Invalid response"); end Test_Invalid_Request; -- ------------------------------ -- Test a GET request on a static file served by the File_Servlet. -- ------------------------------ procedure Test_Get_404 (T : in out Test) is Request : ASF.Requests.Mockup.Request; Reply : ASF.Responses.Mockup.Response; begin Do_Get (Request, Reply, "/file-does-not-exist.txt", "test-404.html"); Assert_Equals (T, ASF.Responses.SC_NOT_FOUND, Reply.Get_Status, "Invalid response"); end Test_Get_404; -- ------------------------------ -- Test a GET request on a static file served by the File_Servlet. -- ------------------------------ procedure Test_Get_File (T : in out Test) is Request : ASF.Requests.Mockup.Request; Reply : ASF.Responses.Mockup.Response; begin Do_Get (Request, Reply, "/views/set.xhtml", "get-file-set.txt"); Assert_Contains (T, "<c:set var=""user"" value=""John Smith""/>", Reply, "Wrong content"); Do_Get (Request, Reply, "/views/set.html", "get-file-set.html"); Assert_Matches (T, "^\s*John Smith\s?$", Reply, "Wrong content"); end Test_Get_File; -- ------------------------------ -- Test a GET request on the measure servlet -- ------------------------------ procedure Test_Get_Measures (T : in out Test) is Request : ASF.Requests.Mockup.Request; Reply : ASF.Responses.Mockup.Response; begin Do_Get (Request, Reply, "/stats.xml", "stats.xml"); -- We must get at least one measure value (assuming the Test_Get_File test -- was executed). Assert_Matches (T, "<time count=""\d+"" time=""\d+.\d+[um]s"" title="".*""/>", Reply, "Wrong content"); end Test_Get_Measures; -- ------------------------------ -- Test a GET+POST request with submitted values and an action method called on the bean. -- ------------------------------ procedure Test_Form_Post (T : in out Test) is use Util.Beans.Objects; Request : ASF.Requests.Mockup.Request; Reply : ASF.Responses.Mockup.Response; Form : aliased Form_Bean; begin Request.Set_Attribute ("form", To_Object (Value => Form'Unchecked_Access, Storage => STATIC)); Do_Get (Request, Reply, "/tests/form-text.html", "form-text.txt"); Assert_Matches (T, ".*<label for=.name.>Name</label>.*", Reply, "Wrong form content"); Assert_Matches (T, ".*<input type=.text. name=.name. value=.. id=.name.*", Reply, "Wrong form content"); Request.Set_Parameter ("formText", "1"); Request.Set_Parameter ("name", "John"); Request.Set_Parameter ("password", "12345"); Request.Set_Parameter ("email", "[email protected]"); Do_Post (Request, Reply, "/tests/form-text.html", "form-text-post.txt"); Assert_Matches (T, ".*<input type=.text. name=.name. value=.John. id=.name.*", Reply, "Wrong form content"); Assert_Equals (T, "John", Form.Name, "Form name not saved in the bean"); Assert_Equals (T, "12345", Form.Password, "Form password not saved in the bean"); Assert_Equals (T, "[email protected]", Form.Email, "Form email not saved in the bean"); end Test_Form_Post; -- ------------------------------ -- Test a POST request with an invalid submitted value -- ------------------------------ procedure Test_Form_Post_Validation_Error (T : in out Test) is use Util.Beans.Objects; Request : ASF.Requests.Mockup.Request; Reply : ASF.Responses.Mockup.Response; Form : aliased Form_Bean; begin Request.Set_Attribute ("form", To_Object (Value => Form'Unchecked_Access, Storage => STATIC)); -- Post with password too short and empty email Request.Set_Parameter ("formText", "1"); Request.Set_Parameter ("name", "John"); Request.Set_Parameter ("password", "12"); Request.Set_Parameter ("email", ""); Do_Post (Request, Reply, "/tests/form-text.html", "form-text-post-1.txt"); Assert_Matches (T, ".*<input type=.text. name=.name. value=.John. id=.name.*", Reply, "Wrong form content"); Assert_Matches (T, ".*Password: Validation Error: Length is less than " & "allowable minimum of '4'.*", Reply, "Missing error message"); -- No field should be modified. Assert_Equals (T, "", Form.Name, "Form name was saved in the bean"); Assert_Equals (T, "", Form.Password, "Form password was saved in the bean"); Assert_Equals (T, "", Form.Email, "Form email was saved in the bean"); Request.Set_Parameter ("email", "1"); Request.Set_Parameter ("password", "12333"); Request.Set_Parameter ("name", "122222222222222222222222222222222222222222"); Do_Post (Request, Reply, "/tests/form-text.html", "form-text-post-2.txt"); end Test_Form_Post_Validation_Error; end ASF.Applications.Tests;
----------------------------------------------------------------------- -- asf-applications-tests - ASF Application tests using ASFUnit -- Copyright (C) 2011 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Tests; with Util.Test_Caller; with ASF.Tests; with ASF.Events.Actions; with ASF.Requests.Mockup; with ASF.Responses.Mockup; with ASF.Applications.Main; package body ASF.Applications.Tests is use ASF.Tests; use Util.Tests; package Caller is new Util.Test_Caller (Test); procedure Add_Tests (Suite : AUnit.Test_Suites.Access_Test_Suite) is begin Caller.Add_Test (Suite, "Test service HTTP invalid method", Test_Invalid_Request'Access); Caller.Add_Test (Suite, "Test service HTTP GET (File_Servlet)", Test_Get_File'Access); Caller.Add_Test (Suite, "Test service HTTP GET 404", Test_Get_404'Access); Caller.Add_Test (Suite, "Test service HTTP GET (Measure_Servlet)", Test_Get_Measures'Access); Caller.Add_Test (Suite, "Test service HTTP POST+INVOKE_APPLICATION", Test_Form_Post'Access); Caller.Add_Test (Suite, "Test service HTTP POST+PROCESS_VALIDATION", Test_Form_Post_Validation_Error'Access); end Add_Tests; package Save_Binding is new ASF.Events.Actions.Action_Method.Bind (Bean => Form_Bean, Method => Save, Name => "save"); Binding_Array : aliased constant Util.Beans.Methods.Method_Binding_Array := (Save_Binding.Proxy'Access, Save_Binding.Proxy'Access); -- ------------------------------ -- Get the value identified by the name. -- ------------------------------ overriding function Get_Value (From : in Form_Bean; Name : in String) return Util.Beans.Objects.Object is begin if Name = "email" then return Util.Beans.Objects.To_Object (From.Email); elsif Name = "password" then return Util.Beans.Objects.To_Object (From.Password); elsif Name = "name" then return Util.Beans.Objects.To_Object (From.Name); else return Util.Beans.Objects.Null_Object; end if; end Get_Value; -- ------------------------------ -- Set the value identified by the name. -- ------------------------------ overriding procedure Set_Value (From : in out Form_Bean; Name : in String; Value : in Util.Beans.Objects.Object) is begin if Name = "email" then From.Email := Util.Beans.Objects.To_Unbounded_String (Value); elsif Name = "password" then From.Password := Util.Beans.Objects.To_Unbounded_String (Value); elsif Name = "name" then From.Name := Util.Beans.Objects.To_Unbounded_String (Value); end if; end Set_Value; -- ------------------------------ -- This bean provides some methods that can be used in a Method_Expression -- ------------------------------ overriding function Get_Method_Bindings (From : in Form_Bean) return Util.Beans.Methods.Method_Binding_Array_Access is pragma Unreferenced (From); begin return Binding_Array'Access; end Get_Method_Bindings; -- ------------------------------ -- Initialize the test application -- ------------------------------ overriding procedure Set_Up (T : in out Test) is pragma Unreferenced (T); use type ASF.Applications.Main.Application_Access; begin if ASF.Tests.Get_Application = null then ASF.Tests.Initialize (Util.Tests.Get_Properties); end if; end Set_Up; -- ------------------------------ -- Action to authenticate a user (password authentication). -- ------------------------------ procedure Save (Data : in out Form_Bean; Outcome : in out Unbounded_String) is begin Outcome := To_Unbounded_String ("success"); end Save; -- ------------------------------ -- Test an invalid HTTP request. -- ------------------------------ procedure Test_Invalid_Request (T : in out Test) is Request : ASF.Requests.Mockup.Request; Reply : ASF.Responses.Mockup.Response; begin -- Unknown method Request.Set_Method ("BLAB"); Request.Set_Request_URI ("/asfunit/views/set.xhtml"); Do_Req (Request, Reply); Assert_Equals (T, ASF.Responses.SC_NOT_IMPLEMENTED, Reply.Get_Status, "Invalid response"); -- PUT on a file is not allowed Request.Set_Method ("PUT"); Request.Set_Request_URI ("/asfunit/views/set.xhtml"); Do_Req (Request, Reply); Assert_Equals (T, ASF.Responses.SC_METHOD_NOT_ALLOWED, Reply.Get_Status, "Invalid response"); -- POST on a file is not allowed Request.Set_Method ("POST"); Request.Set_Request_URI ("/asfunit/views/set.xhtml"); Do_Req (Request, Reply); Assert_Equals (T, ASF.Responses.SC_METHOD_NOT_ALLOWED, Reply.Get_Status, "Invalid response"); -- DELETE on a file is not allowed Request.Set_Method ("DELETE"); Request.Set_Request_URI ("/asfunit/views/set.xhtml"); Do_Req (Request, Reply); Assert_Equals (T, ASF.Responses.SC_METHOD_NOT_ALLOWED, Reply.Get_Status, "Invalid response"); end Test_Invalid_Request; -- ------------------------------ -- Test a GET request on a static file served by the File_Servlet. -- ------------------------------ procedure Test_Get_404 (T : in out Test) is Request : ASF.Requests.Mockup.Request; Reply : ASF.Responses.Mockup.Response; begin Do_Get (Request, Reply, "/file-does-not-exist.txt", "test-404.html"); Assert_Equals (T, ASF.Responses.SC_NOT_FOUND, Reply.Get_Status, "Invalid response"); end Test_Get_404; -- ------------------------------ -- Test a GET request on a static file served by the File_Servlet. -- ------------------------------ procedure Test_Get_File (T : in out Test) is Request : ASF.Requests.Mockup.Request; Reply : ASF.Responses.Mockup.Response; begin Do_Get (Request, Reply, "/views/set.xhtml", "get-file-set.txt"); Assert_Contains (T, "<c:set var=""user"" value=""John Smith""/>", Reply, "Wrong content"); Do_Get (Request, Reply, "/views/set.html", "get-file-set.html"); Assert_Matches (T, "^\s*John Smith\s?$", Reply, "Wrong content"); end Test_Get_File; -- ------------------------------ -- Test a GET request on the measure servlet -- ------------------------------ procedure Test_Get_Measures (T : in out Test) is Request : ASF.Requests.Mockup.Request; Reply : ASF.Responses.Mockup.Response; begin Do_Get (Request, Reply, "/stats.xml", "stats.xml"); -- We must get at least one measure value (assuming the Test_Get_File test -- was executed). Assert_Matches (T, "<time count=""\d+"" time=""\d+.\d+[um]s"" title="".*""/>", Reply, "Wrong content"); end Test_Get_Measures; -- ------------------------------ -- Test a GET+POST request with submitted values and an action method called on the bean. -- ------------------------------ procedure Test_Form_Post (T : in out Test) is use Util.Beans.Objects; Request : ASF.Requests.Mockup.Request; Reply : ASF.Responses.Mockup.Response; Form : aliased Form_Bean; begin Request.Set_Attribute ("form", To_Object (Value => Form'Unchecked_Access, Storage => STATIC)); Do_Get (Request, Reply, "/tests/form-text.html", "form-text.txt"); Assert_Matches (T, ".*<label for=.name.>Name</label>.*", Reply, "Wrong form content"); Assert_Matches (T, ".*<input type=.text. name=.name. value=.. id=.name.*", Reply, "Wrong form content"); Request.Set_Parameter ("formText", "1"); Request.Set_Parameter ("name", "John"); Request.Set_Parameter ("password", "12345"); Request.Set_Parameter ("email", "[email protected]"); Do_Post (Request, Reply, "/tests/form-text.html", "form-text-post.txt"); Assert_Matches (T, ".*<input type=.text. name=.name. value=.John. id=.name.*", Reply, "Wrong form content"); Assert_Equals (T, "John", Form.Name, "Form name not saved in the bean"); Assert_Equals (T, "12345", Form.Password, "Form password not saved in the bean"); Assert_Equals (T, "[email protected]", Form.Email, "Form email not saved in the bean"); end Test_Form_Post; -- ------------------------------ -- Test a POST request with an invalid submitted value -- ------------------------------ procedure Test_Form_Post_Validation_Error (T : in out Test) is use Util.Beans.Objects; Request : ASF.Requests.Mockup.Request; Reply : ASF.Responses.Mockup.Response; Form : aliased Form_Bean; begin Request.Set_Attribute ("form", To_Object (Value => Form'Unchecked_Access, Storage => STATIC)); -- Post with password too short and empty email Request.Set_Parameter ("formText", "1"); Request.Set_Parameter ("name", "John"); Request.Set_Parameter ("password", "12"); Request.Set_Parameter ("email", ""); Do_Post (Request, Reply, "/tests/form-text.html", "form-text-post-1.txt"); Assert_Matches (T, ".*<input type=.text. name=.name. value=.John. id=.name.*", Reply, "Wrong form content"); Assert_Matches (T, ".*Password: Validation Error: Length is less than " & "allowable minimum of '4'.*", Reply, "Missing error message"); -- No field should be modified. Assert_Equals (T, "", Form.Name, "Form name was saved in the bean"); Assert_Equals (T, "", Form.Password, "Form password was saved in the bean"); Assert_Equals (T, "", Form.Email, "Form email was saved in the bean"); Request.Set_Parameter ("email", "1"); Request.Set_Parameter ("password", "12333"); Request.Set_Parameter ("name", "122222222222222222222222222222222222222222"); Do_Post (Request, Reply, "/tests/form-text.html", "form-text-post-2.txt"); Assert_Matches (T, ".*<span class=.error.>Invalid email address</span>.*", Reply, "Invalid error message for email"); Assert_Matches (T, ".*<span class=.error.>Invalid name</span>.*", Reply, "Invalid error message for name"); Request.Set_Parameter ("email", "1dddddd"); Request.Set_Parameter ("password", "12333ddddddddddddddd"); Request.Set_Parameter ("name", "1222222222"); Do_Post (Request, Reply, "/tests/form-text.html", "form-text-post-3.txt"); Assert_Matches (T, ".*Password: Validation Error: Length is greater than " & "allowable maximum of '10'.*", Reply, "Invalid error message for password"); end Test_Form_Post_Validation_Error; end ASF.Applications.Tests;
Verify the error message
Verify the error message
Ada
apache-2.0
stcarrez/ada-asf,stcarrez/ada-asf,stcarrez/ada-asf
302622ecd31fd7ef37e0fa960ac4a3bfe93e22b0
examples/MicroBit/src/main.adb
examples/MicroBit/src/main.adb
------------------------------------------------------------------------------ -- -- -- Copyright (C) 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. -- -- -- ------------------------------------------------------------------------------ with MicroBit.Display; use MicroBit.Display; with MicroBit.Time; with Beacon; procedure Main is Str : constant String := "MAKE WITH ADA "; begin Beacon.Initialize_Radio; loop for C of Str loop Display (C); Beacon.Send_Beacon_Packet; MicroBit.Time.Delay_Ms (500); end loop; end loop; end Main;
------------------------------------------------------------------------------ -- -- -- Copyright (C) 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. -- -- -- ------------------------------------------------------------------------------ with MicroBit.Display; with MicroBit.Time; with Beacon; procedure Main is begin MicroBit.Display.Set_Animation_Step_Duration (80); Beacon.Initialize_Radio; loop if not MicroBit.Display.Animation_In_Progress then MicroBit.Display.Display_Async ("MAKE WITH Ada! "); end if; Beacon.Send_Beacon_Packet; MicroBit.Time.Delay_Ms (500); end loop; end Main;
Use text scroll in the example
MicroBit: Use text scroll in the example
Ada
bsd-3-clause
simonjwright/Ada_Drivers_Library,Fabien-Chouteau/Ada_Drivers_Library,AdaCore/Ada_Drivers_Library,simonjwright/Ada_Drivers_Library,AdaCore/Ada_Drivers_Library,Fabien-Chouteau/Ada_Drivers_Library
aed76d1c426aa2b5fb5b39bff514c793d1107aa7
src/ado-sessions.ads
src/ado-sessions.ads
----------------------------------------------------------------------- -- ADO Sessions -- Sessions 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 Ada.Finalization; with ADO.Schemas; with ADO.Statements; with ADO.Objects; with ADO.Objects.Cache; with ADO.Databases; with ADO.Queries; with ADO.SQL; with Util.Concurrent.Counters; limited with ADO.Sequences; limited with ADO.Schemas.Entities; package ADO.Sessions is use ADO.Statements; -- Raised for all errors reported by the database DB_Error : exception; -- Raised if the database connection is not open. NOT_OPEN : exception; NOT_FOUND : exception; NO_DATABASE : exception; -- Raised when the connection URI is invalid. Connection_Error : exception; 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 ADO.Databases.Connection_Status; -- Close the session. procedure Close (Database : in out Session); -- Get the database connection. function Get_Connection (Database : in Session) return ADO.Databases.Connection'Class; -- 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; -- --------- -- 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; type Session_Proxy is limited private; type Session_Proxy_Access is access all Session_Proxy; function Get_Session_Proxy (Database : in Session) return ADO.Objects.Session_Proxy_Access; type Session_Record is limited private; type Session_Record_Access is access all Session_Record; private type Entity_Cache_Access is access constant 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; type Session_Proxy is limited record Counter : Util.Concurrent.Counters.Counter; Session : Session_Record_Access; Factory : Object_Factory_Access; end record; -- 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 : Natural := 1; Database : ADO.Databases.Master_Connection; Proxy : ADO.Objects.Session_Proxy_Access; Cache : ADO.Objects.Cache.Object_Cache; Entities : Entity_Cache_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 ADO.Sequences.Factory; type Master_Session is new Session with record Sequences : Factory_Access; end record; procedure Check_Session (Database : in Session'Class); pragma Inline (Check_Session); end ADO.Sessions;
----------------------------------------------------------------------- -- ADO Sessions -- Sessions 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 Ada.Finalization; with ADO.Schemas; with ADO.Statements; with ADO.Objects; with ADO.Objects.Cache; with ADO.Databases; with ADO.Queries; with ADO.SQL; with Util.Concurrent.Counters; limited with ADO.Sequences; limited with ADO.Schemas.Entities; package ADO.Sessions is use ADO.Statements; -- Raised for all errors reported by the database DB_Error : exception; -- Raised if the database connection is not open. NOT_OPEN : exception; NOT_FOUND : exception; NO_DATABASE : exception; -- Raised when the connection URI is invalid. Connection_Error : exception; 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 ADO.Databases.Connection_Status; -- Close the session. procedure Close (Database : in out Session); -- Get the database connection. function Get_Connection (Database : in Session) return ADO.Databases.Connection'Class; -- 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; -- --------- -- 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; type Session_Proxy is limited private; type Session_Proxy_Access is access all Session_Proxy; function Get_Session_Proxy (Database : in Session) return ADO.Objects.Session_Proxy_Access; type Session_Record is limited private; type Session_Record_Access is access all Session_Record; private type Entity_Cache_Access is access constant 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; type Session_Proxy is limited record Counter : Util.Concurrent.Counters.Counter; Session : Session_Record_Access; Factory : Object_Factory_Access; end record; -- 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 : Natural := 1; Database : ADO.Databases.Master_Connection; Proxy : ADO.Objects.Session_Proxy_Access; Cache : ADO.Objects.Cache.Object_Cache; Entities : Entity_Cache_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); pragma Inline (Check_Session); end ADO.Sessions;
Change the Factory_Access to add 'all' access types
Change the Factory_Access to add 'all' access types
Ada
apache-2.0
Letractively/ada-ado
08f39c92e9f908cae66d52beaa8fa401106e4d08
src/sqlite/ado-drivers-connections-sqlite.ads
src/sqlite/ado-drivers-connections-sqlite.ads
----------------------------------------------------------------------- -- ADO Sqlite Database -- SQLite Database connections -- Copyright (C) 2009, 2010, 2011, 2012, 2017, 2018 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Sqlite3_H; private with Ada.Containers.Doubly_Linked_Lists; package ADO.Drivers.Connections.Sqlite is subtype Sqlite3 is Sqlite3_H.sqlite3; -- The database connection manager type Sqlite_Driver is limited private; -- Initialize the SQLite driver. procedure Initialize; private -- Database connection implementation type Database_Connection is new ADO.Drivers.Connections.Database_Connection with record Server : aliased access Sqlite3_H.sqlite3; Name : Unbounded_String; URI : Unbounded_String; end record; type Database_Connection_Access is access all Database_Connection'Class; -- Get the database driver which manages this connection. overriding function Get_Driver (Database : in Database_Connection) return Driver_Access; overriding function Create_Statement (Database : in Database_Connection; Table : in ADO.Schemas.Class_Mapping_Access) return Query_Statement_Access; overriding function Create_Statement (Database : in Database_Connection; Query : in String) return Query_Statement_Access; -- Create a delete statement. overriding function Create_Statement (Database : in Database_Connection; Table : in ADO.Schemas.Class_Mapping_Access) return Delete_Statement_Access; -- Create an insert statement. overriding function Create_Statement (Database : in Database_Connection; Table : in ADO.Schemas.Class_Mapping_Access) return Insert_Statement_Access; -- Create an update statement. overriding function Create_Statement (Database : in Database_Connection; Table : in ADO.Schemas.Class_Mapping_Access) return Update_Statement_Access; -- Start a transaction. overriding procedure Begin_Transaction (Database : in out Database_Connection); -- Commit the current transaction. overriding procedure Commit (Database : in out Database_Connection); -- Rollback the current transaction. overriding procedure Rollback (Database : in out Database_Connection); -- Load the database schema definition for the current database. overriding procedure Load_Schema (Database : in Database_Connection; Schema : out ADO.Schemas.Schema_Definition); -- Closes the database connection overriding procedure Close (Database : in out Database_Connection); -- Releases the sqlite connection if it is open overriding procedure Finalize (Database : in out Database_Connection); package Database_List is new Ada.Containers.Doubly_Linked_Lists (Element_Type => Ref.Ref, "=" => ADO.Drivers.Connections.Ref."="); protected type Sqlite_Connections is procedure Open (Config : in Configuration'Class; Result : in out Ref.Ref'Class); private List : Database_List.List; end Sqlite_Connections; type Sqlite_Driver is new ADO.Drivers.Connections.Driver with record Map : Sqlite_Connections; end record; -- Create a new SQLite connection using the configuration parameters. overriding procedure Create_Connection (D : in out Sqlite_Driver; Config : in Configuration'Class; Result : in out Ref.Ref'Class); -- Create the database and initialize it with the schema SQL file. -- The `Admin` parameter describes the database connection with administrator access. -- The `Config` parameter describes the target database connection. overriding procedure Create_Database (D : in out Sqlite_Driver; Admin : in Configs.Configuration'Class; Config : in Configs.Configuration'Class; Schema_Path : in String; Messages : out Util.Strings.Vectors.Vector); -- Deletes the SQLite driver. overriding procedure Finalize (D : in out Sqlite_Driver); end ADO.Drivers.Connections.Sqlite;
----------------------------------------------------------------------- -- ADO Sqlite Database -- SQLite Database connections -- Copyright (C) 2009, 2010, 2011, 2012, 2017, 2018 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Sqlite3_H; private with Ada.Containers.Doubly_Linked_Lists; package ADO.Drivers.Connections.Sqlite is subtype Sqlite3 is Sqlite3_H.sqlite3; -- The database connection manager type Sqlite_Driver is limited private; -- Initialize the SQLite driver. procedure Initialize; private -- Database connection implementation type Database_Connection is new ADO.Drivers.Connections.Database_Connection with record Server : aliased access Sqlite3_H.sqlite3; Name : Unbounded_String; URI : Unbounded_String; end record; type Database_Connection_Access is access all Database_Connection'Class; -- Get the database driver which manages this connection. overriding function Get_Driver (Database : in Database_Connection) return Driver_Access; overriding function Create_Statement (Database : in Database_Connection; Table : in ADO.Schemas.Class_Mapping_Access) return Query_Statement_Access; overriding function Create_Statement (Database : in Database_Connection; Query : in String) return Query_Statement_Access; -- Create a delete statement. overriding function Create_Statement (Database : in Database_Connection; Table : in ADO.Schemas.Class_Mapping_Access) return Delete_Statement_Access; -- Create an insert statement. overriding function Create_Statement (Database : in Database_Connection; Table : in ADO.Schemas.Class_Mapping_Access) return Insert_Statement_Access; -- Create an update statement. overriding function Create_Statement (Database : in Database_Connection; Table : in ADO.Schemas.Class_Mapping_Access) return Update_Statement_Access; -- Start a transaction. overriding procedure Begin_Transaction (Database : in out Database_Connection); -- Commit the current transaction. overriding procedure Commit (Database : in out Database_Connection); -- Rollback the current transaction. overriding procedure Rollback (Database : in out Database_Connection); -- Load the database schema definition for the current database. overriding procedure Load_Schema (Database : in Database_Connection; Schema : out ADO.Schemas.Schema_Definition); -- Closes the database connection overriding procedure Close (Database : in out Database_Connection); type SQLite_Database is record Server : aliased access Sqlite3_H.sqlite3; Name : Unbounded_String; URI : Unbounded_String; end record; package Database_List is new Ada.Containers.Doubly_Linked_Lists (Element_Type => SQLite_Database); protected type Sqlite_Connections is procedure Open (Config : in Configuration'Class; Result : in out Ref.Ref'Class); procedure Clear; private List : Database_List.List; end Sqlite_Connections; type Sqlite_Driver is new ADO.Drivers.Connections.Driver with record Map : Sqlite_Connections; end record; -- Create a new SQLite connection using the configuration parameters. overriding procedure Create_Connection (D : in out Sqlite_Driver; Config : in Configuration'Class; Result : in out Ref.Ref'Class); -- Create the database and initialize it with the schema SQL file. -- The `Admin` parameter describes the database connection with administrator access. -- The `Config` parameter describes the target database connection. overriding procedure Create_Database (D : in out Sqlite_Driver; Admin : in Configs.Configuration'Class; Config : in Configs.Configuration'Class; Schema_Path : in String; Messages : out Util.Strings.Vectors.Vector); -- Deletes the SQLite driver. overriding procedure Finalize (D : in out Sqlite_Driver); end ADO.Drivers.Connections.Sqlite;
Define private type SQLite_Database and use it to keep track of SQLite databases
Define private type SQLite_Database and use it to keep track of SQLite databases
Ada
apache-2.0
stcarrez/ada-ado
5b86620bc1caa8bd9249dfe6d7689adf5fde59bb
src/asf-components-html-panels.adb
src/asf-components-html-panels.adb
----------------------------------------------------------------------- -- html.panels -- Layout panels -- Copyright (C) 2009, 2010 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with EL.Objects; package body ASF.Components.Html.Panels is function Get_Layout (UI : UIPanelGroup; Context : in Faces_Context'Class) return String is Value : constant EL.Objects.Object := UI.Get_Attribute (Context, "layout"); Layout : constant String := EL.Objects.To_String (Value); begin if Layout = "div" or Layout = "block" then return "block"; elsif Layout = "none" then return ""; else return "span"; end if; end Get_Layout; procedure Encode_Begin (UI : in UIPanelGroup; Context : in out Faces_Context'Class) is begin if not UI.Is_Rendered (Context) then return; end if; declare Writer : constant Response_Writer_Access := Context.Get_Response_Writer; Tag : constant String := UI.Get_Layout (Context); begin if Tag'Length > 0 then Writer.Start_Optional_Element (Tag); end if; end; end Encode_Begin; procedure Encode_End (UI : in UIPanelGroup; Context : in out Faces_Context'Class) is begin if not UI.Is_Rendered (Context) then return; end if; declare Writer : constant Response_Writer_Access := Context.Get_Response_Writer; Tag : constant String := UI.Get_Layout (Context); begin if Tag'Length > 0 then Writer.End_Optional_Element (Tag); end if; end; end Encode_End; end ASF.Components.Html.Panels;
----------------------------------------------------------------------- -- html.panels -- Layout panels -- Copyright (C) 2009, 2010 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with EL.Objects; package body ASF.Components.Html.Panels is function Get_Layout (UI : UIPanelGroup; Context : in Faces_Context'Class) return String is Value : constant EL.Objects.Object := UI.Get_Attribute (Context, "layout"); Layout : constant String := EL.Objects.To_String (Value); begin if Layout = "div" or Layout = "block" then return "div"; elsif Layout = "none" then return ""; else return "span"; end if; end Get_Layout; procedure Encode_Begin (UI : in UIPanelGroup; Context : in out Faces_Context'Class) is begin if not UI.Is_Rendered (Context) then return; end if; declare Writer : constant Response_Writer_Access := Context.Get_Response_Writer; Tag : constant String := UI.Get_Layout (Context); begin if Tag'Length > 0 then Writer.Start_Optional_Element (Tag); UI.Render_Attributes (Context, Writer); end if; end; end Encode_Begin; procedure Encode_End (UI : in UIPanelGroup; Context : in out Faces_Context'Class) is begin if not UI.Is_Rendered (Context) then return; end if; declare Writer : constant Response_Writer_Access := Context.Get_Response_Writer; Tag : constant String := UI.Get_Layout (Context); begin if Tag'Length > 0 then Writer.End_Optional_Element (Tag); end if; end; end Encode_End; end ASF.Components.Html.Panels;
Fix <h:panelGroup> rendering for a div or block layout
Fix <h:panelGroup> rendering for a div or block layout
Ada
apache-2.0
Letractively/ada-asf,Letractively/ada-asf,Letractively/ada-asf
dec6ea077190c509eb24aa169569090a5eb32912
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
Letractively/ada-security
ad8a6b8b56c8d4956226e5a209584cb0db5afcfd
src/util-serialize-io-json.ads
src/util-serialize-io-json.ads
----------------------------------------------------------------------- -- util-serialize-io-json -- JSON Serialization Driver -- Copyright (C) 2010, 2011, 2012, 2016 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Strings.Unbounded; with Util.Streams.Texts; with Util.Stacks; package Util.Serialize.IO.JSON is -- ------------------------------ -- JSON Output Stream -- ------------------------------ -- The <b>Output_Stream</b> provides methods for creating a JSON output stream. -- The stream object takes care of the JSON escape rules. type Output_Stream is new Util.Streams.Texts.Print_Stream and Util.Serialize.IO.Output_Stream with private; -- Start a JSON document. This operation writes the initial JSON marker ('{'). overriding procedure Start_Document (Stream : in out Output_Stream); -- Finish a JSON document by writing the final JSON marker ('}'). overriding procedure End_Document (Stream : in out Output_Stream); -- Write the value as a JSON string. Special characters are escaped using the JSON -- escape rules. procedure Write_String (Stream : in out Output_Stream; Value : in String); -- Write the value as a JSON string. Special characters are escaped using the JSON -- escape rules. procedure Write_Wide_String (Stream : in out Output_Stream; Value : in Wide_Wide_String); -- Start a new JSON object. If the name is not empty, write it as a string -- followed by the ':' (colon). The JSON object starts with '{' (curly brace). -- Example: "list": { procedure Start_Entity (Stream : in out Output_Stream; Name : in String); -- Terminates the current JSON object. procedure End_Entity (Stream : in out Output_Stream; Name : in String); -- Write the attribute name/value pair. overriding procedure Write_Attribute (Stream : in out Output_Stream; Name : in String; Value : in String); overriding procedure Write_Wide_Attribute (Stream : in out Output_Stream; Name : in String; Value : in Wide_Wide_String); overriding procedure Write_Attribute (Stream : in out Output_Stream; Name : in String; Value : in Integer); overriding procedure Write_Attribute (Stream : in out Output_Stream; Name : in String; Value : in Boolean); -- Write a JSON name/value pair. The value is written according to its type -- Example: "name": null -- "name": false -- "name": 12 -- "name": "value" procedure Write_Attribute (Stream : in out Output_Stream; Name : in String; Value : in Util.Beans.Objects.Object); -- Write a JSON name/value pair (see Write_Attribute). procedure Write_Entity (Stream : in out Output_Stream; Name : in String; Value : in Util.Beans.Objects.Object); -- Write a JSON name/value pair (see Write_Attribute). overriding procedure Write_Entity (Stream : in out Output_Stream; Name : in String; Value : in String); overriding procedure Write_Wide_Entity (Stream : in out Output_Stream; Name : in String; Value : in Wide_Wide_String); overriding procedure Write_Entity (Stream : in out Output_Stream; Name : in String; Value : in Boolean); overriding procedure Write_Entity (Stream : in out Output_Stream; Name : in String; Value : in Integer); overriding procedure Write_Entity (Stream : in out Output_Stream; Name : in String; Value : in Ada.Calendar.Time); overriding procedure Write_Long_Entity (Stream : in out Output_Stream; Name : in String; Value : in Long_Long_Integer); overriding procedure Write_Enum_Entity (Stream : in out Output_Stream; Name : in String; Value : in String); -- Starts a JSON array. -- Example: "list": [ overriding procedure Start_Array (Stream : in out Output_Stream; Name : in String); -- Terminates a JSON array. overriding procedure End_Array (Stream : in out Output_Stream; Name : in String); type Parser is new Serialize.IO.Parser with private; -- Parse the stream using the JSON parser. procedure Parse (Handler : in out Parser; Stream : in out Util.Streams.Buffered.Buffered_Stream'Class); -- Get the current location (file and line) to report an error message. function Get_Location (Handler : in Parser) return String; private type Node_Info is record Is_Array : Boolean := False; Has_Fields : Boolean := False; end record; type Node_Info_Access is access all Node_Info; package Node_Info_Stack is new Util.Stacks (Element_Type => Node_Info, Element_Type_Access => Node_Info_Access); type Output_Stream is new Util.Streams.Texts.Print_Stream and Util.Serialize.IO.Output_Stream with record Stack : Node_Info_Stack.Stack; end record; type Token_Type is (T_EOF, T_LEFT_BRACE, T_RIGHT_BRACE, T_LEFT_BRACKET, T_RIGHT_BRACKET, T_COLON, T_COMMA, T_TRUE, T_FALSE, T_STRING, T_NUMBER, T_BOOLEAN, T_UNKNOWN, T_NULL); type Parser is new Util.Serialize.IO.Parser with record Token : Ada.Strings.Unbounded.Unbounded_String; Pending_Token : Token_Type := T_EOF; Line_Number : Natural := 1; Has_Pending_Char : Boolean := False; Pending_Char : Character; end record; end Util.Serialize.IO.JSON;
----------------------------------------------------------------------- -- util-serialize-io-json -- JSON Serialization Driver -- Copyright (C) 2010, 2011, 2012, 2016 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Strings.Unbounded; with Ada.Streams; with Util.Streams.Texts; with Util.Stacks; package Util.Serialize.IO.JSON is -- ------------------------------ -- JSON Output Stream -- ------------------------------ -- The <b>Output_Stream</b> provides methods for creating a JSON output stream. -- The stream object takes care of the JSON escape rules. type Output_Stream is limited new Util.Serialize.IO.Output_Stream with private; -- Set the target output stream. procedure Initialize (Stream : in out Output_Stream; Output : in Util.Streams.Texts.Print_Stream_Access); -- Flush the buffer (if any) to the sink. overriding procedure Flush (Stream : in out Output_Stream); -- Close the sink. overriding procedure Close (Stream : in out Output_Stream); -- Write the buffer array to the output stream. overriding procedure Write (Stream : in out Output_Stream; Buffer : in Ada.Streams.Stream_Element_Array); -- Write a raw character on the stream. procedure Write (Stream : in out Output_Stream; Char : in Character); -- Write a wide character on the stream doing some conversion if necessary. -- The default implementation translates the wide character to a UTF-8 sequence. procedure Write_Wide (Stream : in out Output_Stream; Item : in Wide_Wide_Character); -- Write a raw string on the stream. procedure Write (Stream : in out Output_Stream; Item : in String); -- Start a JSON document. This operation writes the initial JSON marker ('{'). overriding procedure Start_Document (Stream : in out Output_Stream); -- Finish a JSON document by writing the final JSON marker ('}'). overriding procedure End_Document (Stream : in out Output_Stream); -- Write the value as a JSON string. Special characters are escaped using the JSON -- escape rules. procedure Write_String (Stream : in out Output_Stream; Value : in String); -- Write the value as a JSON string. Special characters are escaped using the JSON -- escape rules. procedure Write_Wide_String (Stream : in out Output_Stream; Value : in Wide_Wide_String); -- Start a new JSON object. If the name is not empty, write it as a string -- followed by the ':' (colon). The JSON object starts with '{' (curly brace). -- Example: "list": { procedure Start_Entity (Stream : in out Output_Stream; Name : in String); -- Terminates the current JSON object. procedure End_Entity (Stream : in out Output_Stream; Name : in String); -- Write the attribute name/value pair. overriding procedure Write_Attribute (Stream : in out Output_Stream; Name : in String; Value : in String); overriding procedure Write_Wide_Attribute (Stream : in out Output_Stream; Name : in String; Value : in Wide_Wide_String); overriding procedure Write_Attribute (Stream : in out Output_Stream; Name : in String; Value : in Integer); overriding procedure Write_Attribute (Stream : in out Output_Stream; Name : in String; Value : in Boolean); -- Write a JSON name/value pair. The value is written according to its type -- Example: "name": null -- "name": false -- "name": 12 -- "name": "value" procedure Write_Attribute (Stream : in out Output_Stream; Name : in String; Value : in Util.Beans.Objects.Object); -- Write a JSON name/value pair (see Write_Attribute). procedure Write_Entity (Stream : in out Output_Stream; Name : in String; Value : in Util.Beans.Objects.Object); -- Write a JSON name/value pair (see Write_Attribute). overriding procedure Write_Entity (Stream : in out Output_Stream; Name : in String; Value : in String); overriding procedure Write_Wide_Entity (Stream : in out Output_Stream; Name : in String; Value : in Wide_Wide_String); overriding procedure Write_Entity (Stream : in out Output_Stream; Name : in String; Value : in Boolean); overriding procedure Write_Entity (Stream : in out Output_Stream; Name : in String; Value : in Integer); overriding procedure Write_Entity (Stream : in out Output_Stream; Name : in String; Value : in Ada.Calendar.Time); overriding procedure Write_Long_Entity (Stream : in out Output_Stream; Name : in String; Value : in Long_Long_Integer); overriding procedure Write_Enum_Entity (Stream : in out Output_Stream; Name : in String; Value : in String); -- Starts a JSON array. -- Example: "list": [ overriding procedure Start_Array (Stream : in out Output_Stream; Name : in String); -- Terminates a JSON array. overriding procedure End_Array (Stream : in out Output_Stream; Name : in String); type Parser is new Serialize.IO.Parser with private; -- Parse the stream using the JSON parser. procedure Parse (Handler : in out Parser; Stream : in out Util.Streams.Buffered.Buffered_Stream'Class); -- Get the current location (file and line) to report an error message. function Get_Location (Handler : in Parser) return String; private type Node_Info is record Is_Array : Boolean := False; Has_Fields : Boolean := False; end record; type Node_Info_Access is access all Node_Info; package Node_Info_Stack is new Util.Stacks (Element_Type => Node_Info, Element_Type_Access => Node_Info_Access); type Output_Stream is limited new Util.Serialize.IO.Output_Stream with record Stack : Node_Info_Stack.Stack; Stream : Util.Streams.Texts.Print_Stream_Access; end record; type Token_Type is (T_EOF, T_LEFT_BRACE, T_RIGHT_BRACE, T_LEFT_BRACKET, T_RIGHT_BRACKET, T_COLON, T_COMMA, T_TRUE, T_FALSE, T_STRING, T_NUMBER, T_BOOLEAN, T_UNKNOWN, T_NULL); type Parser is new Util.Serialize.IO.Parser with record Token : Ada.Strings.Unbounded.Unbounded_String; Pending_Token : Token_Type := T_EOF; Line_Number : Natural := 1; Has_Pending_Char : Boolean := False; Pending_Char : Character; end record; end Util.Serialize.IO.JSON;
Change Output_Stream implementation to avoid inheriting from Print_Stream but instead allow to use a Print_Stream instance as the output stream. Override the Initialize, Flush, Close, Write procedues. Define the Write_Wide procedure so that the Output_Stream type provides almost the same operations as Print_Stream type.
Change Output_Stream implementation to avoid inheriting from Print_Stream but instead allow to use a Print_Stream instance as the output stream. Override the Initialize, Flush, Close, Write procedues. Define the Write_Wide procedure so that the Output_Stream type provides almost the same operations as Print_Stream type.
Ada
apache-2.0
stcarrez/ada-util,stcarrez/ada-util
d7e4a310eb58136c615319929cdd3cf6aa022f65
src/asf-components-widgets-panels.ads
src/asf-components-widgets-panels.ads
----------------------------------------------------------------------- -- components-widgets-panels -- Collapsible panels -- 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 ASF.Components.Html; with ASF.Contexts.Faces; with ASF.Contexts.Writer; package ASF.Components.Widgets.Panels is HEADER_FACET_NAME : constant String := "header"; FOOTER_FACET_NAME : constant String := "footer"; HEADER_ATTR_NAME : constant String := "header"; FOOTER_ATTR_NAME : constant String := "footer"; -- ------------------------------ -- UIPanel -- ------------------------------ -- The <b>UIPanel</b> component displays a <tt>div</tt> panel with a header, a body -- and a footer. The panel header can contain some actions to collapse or expand the -- panel content. type UIPanel is new ASF.Components.Html.UIHtmlComponent with null record; -- Render the panel header. procedure Render_Header (UI : in UIPanel; Writer : in out ASF.Contexts.Writer.Response_Writer'Class; Context : in out ASF.Contexts.Faces.Faces_Context'Class); -- Render the panel footer. procedure Render_Footer (UI : in UIPanel; Writer : in out ASF.Contexts.Writer.Response_Writer'Class; Context : in out ASF.Contexts.Faces.Faces_Context'Class); -- Render the panel header and prepare for the panel content. overriding procedure Encode_Begin (UI : in UIPanel; Context : in out ASF.Contexts.Faces.Faces_Context'Class); -- Render the panel footer. overriding procedure Encode_End (UI : in UIPanel; Context : in out ASF.Contexts.Faces.Faces_Context'Class); end ASF.Components.Widgets.Panels;
----------------------------------------------------------------------- -- components-widgets-panels -- Collapsible panels -- 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 ASF.Components.Html; with ASF.Contexts.Faces; with ASF.Contexts.Writer; package ASF.Components.Widgets.Panels is HEADER_FACET_NAME : constant String := "header"; FOOTER_FACET_NAME : constant String := "footer"; HEADER_ATTR_NAME : constant String := "header"; FOOTER_ATTR_NAME : constant String := "footer"; TOGGLEABLE_ATTR_NAME : constant String := "toggleable"; CLOSABLE_ATTR_NAME : constant String := "closable"; -- ------------------------------ -- UIPanel -- ------------------------------ -- The <b>UIPanel</b> component displays a <tt>div</tt> panel with a header, a body -- and a footer. The panel header can contain some actions to collapse or expand the -- panel content. type UIPanel is new ASF.Components.Html.UIHtmlComponent with null record; -- Render the panel header. procedure Render_Header (UI : in UIPanel; Writer : in out ASF.Contexts.Writer.Response_Writer'Class; Context : in out ASF.Contexts.Faces.Faces_Context'Class); -- Render the panel footer. procedure Render_Footer (UI : in UIPanel; Writer : in out ASF.Contexts.Writer.Response_Writer'Class; Context : in out ASF.Contexts.Faces.Faces_Context'Class); -- Render the panel header and prepare for the panel content. overriding procedure Encode_Begin (UI : in UIPanel; Context : in out ASF.Contexts.Faces.Faces_Context'Class); -- Render the panel footer. overriding procedure Encode_End (UI : in UIPanel; Context : in out ASF.Contexts.Faces.Faces_Context'Class); end ASF.Components.Widgets.Panels;
Define some attribute names
Define some attribute names
Ada
apache-2.0
Letractively/ada-asf,Letractively/ada-asf,Letractively/ada-asf
f4fdffca07f70c9d4a294601c8bf762fa80c4f8d
src/os-linux/util-systems-dlls.ads
src/os-linux/util-systems-dlls.ads
----------------------------------------------------------------------- -- util-systems-dlls -- Unix shared library support -- 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 System; with Interfaces.C; with Util.Systems.Constants; package Util.Systems.DLLs is -- The shared library handle. type Handle is private; Null_Handle : constant Handle; -- Exception raised when there is a problem loading a shared library. Load_Error : exception; -- Exception raised when a symbol cannot be found in a shared library. Not_Found : exception; subtype Flags is Interfaces.C.int; -- Load the shared library with the given name or path and return a library handle. -- Raises the <tt>Load_Error</tt> exception if the library cannot be loaded. function Load (Path : in String; Mode : in Flags := Util.Systems.Constants.RTLD_LAZY) return Handle; -- Unload the shared library. procedure Unload (Lib : in Handle); -- Get a global symbol with the given name in the library. -- Raises the <tt>Not_Found</tt> exception if the symbol does not exist. function Get_Symbol (Lib : in Handle; Name : in String) return System.Address; private type Handle is new System.Address; Null_Handle : constant Handle := Handle (System.Null_Address); end Util.Systems.DLLs;
----------------------------------------------------------------------- -- util-systems-dlls -- Unix shared library support -- 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 System; with Interfaces.C; with Util.Systems.Constants; package Util.Systems.DLLs is -- The shared library handle. type Handle is private; Null_Handle : constant Handle; -- Exception raised when there is a problem loading a shared library. Load_Error : exception; -- Exception raised when a symbol cannot be found in a shared library. Not_Found : exception; subtype Flags is Interfaces.C.int; Extension : constant String := ".so"; -- Load the shared library with the given name or path and return a library handle. -- Raises the <tt>Load_Error</tt> exception if the library cannot be loaded. function Load (Path : in String; Mode : in Flags := Util.Systems.Constants.RTLD_LAZY) return Handle; -- Unload the shared library. procedure Unload (Lib : in Handle); -- Get a global symbol with the given name in the library. -- Raises the <tt>Not_Found</tt> exception if the symbol does not exist. function Get_Symbol (Lib : in Handle; Name : in String) return System.Address; private type Handle is new System.Address; Null_Handle : constant Handle := Handle (System.Null_Address); end Util.Systems.DLLs;
Define the extension for shared libraries
Define the extension for shared libraries
Ada
apache-2.0
flottokarotto/ada-util,Letractively/ada-util,flottokarotto/ada-util,Letractively/ada-util
ee06eb77c5f766b3388b41a35ce41b1b6e7558b6
src/sys/streams/util-streams-aes.adb
src/sys/streams/util-streams-aes.adb
----------------------------------------------------------------------- -- util-streams-aes -- AES encoding and decoding streams -- Copyright (C) 2019 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- package body Util.Streams.AES is -- ----------------------- -- Set the encryption key and mode to be used. -- ----------------------- procedure Set_Key (Stream : in out Encoding_Stream; Data : in Ada.Streams.Stream_Element_Array; Mode : in Util.Encoders.AES.AES_Mode := Util.Encoders.AES.CBC) is begin Stream.Transform.Set_Key (Data, Mode); end Set_Key; -- ----------------------- -- Set the encryption initialization vector before starting the encryption. -- ----------------------- procedure Set_IV (Stream : in out Encoding_Stream; IV : in Util.Encoders.AES.Word_Block_Type) is begin Stream.Transform.Set_IV (IV); end Set_IV; -- ----------------------- -- Set the encryption key and mode to be used. -- ----------------------- procedure Set_Key (Stream : in out Decoding_Stream; Data : in Ada.Streams.Stream_Element_Array; Mode : in Util.Encoders.AES.AES_Mode := Util.Encoders.AES.CBC) is begin Stream.Transform.Set_Key (Data, Mode); end Set_Key; -- ----------------------- -- Set the encryption initialization vector before starting the encryption. -- ----------------------- procedure Set_IV (Stream : in out Decoding_Stream; IV : in Util.Encoders.AES.Word_Block_Type) is begin Stream.Transform.Set_IV (IV); end Set_IV; end Util.Streams.AES;
----------------------------------------------------------------------- -- util-streams-aes -- AES encoding and decoding streams -- Copyright (C) 2019 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- package body Util.Streams.AES is -- ----------------------- -- Set the encryption key and mode to be used. -- ----------------------- procedure Set_Key (Stream : in out Encoding_Stream; Secret : in Util.Encoders.Secret_Key; Mode : in Util.Encoders.AES.AES_Mode := Util.Encoders.AES.CBC) is begin Stream.Transform.Set_Key (Secret, Mode); end Set_Key; -- ----------------------- -- Set the encryption initialization vector before starting the encryption. -- ----------------------- procedure Set_IV (Stream : in out Encoding_Stream; IV : in Util.Encoders.AES.Word_Block_Type) is begin Stream.Transform.Set_IV (IV); end Set_IV; -- ----------------------- -- Set the encryption key and mode to be used. -- ----------------------- procedure Set_Key (Stream : in out Decoding_Stream; Secret : in Util.Encoders.Secret_Key; Mode : in Util.Encoders.AES.AES_Mode := Util.Encoders.AES.CBC) is begin Stream.Transform.Set_Key (Secret, Mode); end Set_Key; -- ----------------------- -- Set the encryption initialization vector before starting the encryption. -- ----------------------- procedure Set_IV (Stream : in out Decoding_Stream; IV : in Util.Encoders.AES.Word_Block_Type) is begin Stream.Transform.Set_IV (IV); end Set_IV; end Util.Streams.AES;
Use the Secret_Key type for AES secret keys
Use the Secret_Key type for AES secret keys
Ada
apache-2.0
stcarrez/ada-util,stcarrez/ada-util
bf5a9c5ab58570067207d46c1cf9ae359e80d653
awa/plugins/awa-jobs/src/awa-jobs-services.adb
awa/plugins/awa-jobs/src/awa-jobs-services.adb
----------------------------------------------------------------------- -- awa-jobs -- AWA Jobs -- Copyright (C) 2012 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Serialize.Tools; with Util.Log.Loggers; with Ada.Tags; with Ada.Calendar; with Ada.Unchecked_Deallocation; with ADO.Sessions.Entities; with AWA.Users.Models; with AWA.Events.Models; with AWA.Services.Contexts; with AWA.Jobs.Modules; with AWA.Applications; with AWA.Events.Services; with AWA.Modules; package body AWA.Jobs.Services is package ASC renames AWA.Services.Contexts; Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("AWA.Jobs.Services"); -- ------------------------------ -- Set the job parameter identified by the <b>Name</b> to the value given in <b>Value</b>. -- ------------------------------ procedure Set_Parameter (Job : in out Abstract_Job_Type; Name : in String; Value : in String) is begin Job.Set_Parameter (Name, Util.Beans.Objects.To_Object (Value)); end Set_Parameter; -- ------------------------------ -- Set the job parameter identified by the <b>Name</b> to the value given in <b>Value</b>. -- ------------------------------ procedure Set_Parameter (Job : in out Abstract_Job_Type; Name : in String; Value : in Integer) is begin Job.Set_Parameter (Name, Util.Beans.Objects.To_Object (Value)); end Set_Parameter; -- ------------------------------ -- Set the job parameter identified by the <b>Name</b> to the value given in <b>Value</b>. -- The value object can hold any kind of basic value type (integer, enum, date, strings). -- If the value represents a bean, the <tt>Invalid_Value</tt> exception is raised. -- ------------------------------ procedure Set_Parameter (Job : in out Abstract_Job_Type; Name : in String; Value : in Util.Beans.Objects.Object) is begin Job.Props.Include (Name, Value); Job.Props_Modified := True; end Set_Parameter; -- ------------------------------ -- Get the job parameter identified by the <b>Name</b> and convert the value into a string. -- ------------------------------ function Get_Parameter (Job : in Abstract_Job_Type; Name : in String) return String is Value : constant Util.Beans.Objects.Object := Job.Get_Parameter (Name); begin return Util.Beans.Objects.To_String (Value); end Get_Parameter; -- ------------------------------ -- Get the job parameter identified by the <b>Name</b> and convert the value as an integer. -- If the parameter is not defined, return the default value passed in <b>Default</b>. -- ------------------------------ function Get_Parameter (Job : in Abstract_Job_Type; Name : in String; Default : in Integer) return Integer is Pos : constant Util.Beans.Objects.Maps.Cursor := Job.Props.Find (Name); begin if Util.Beans.Objects.Maps.Has_Element (Pos) then declare Value : constant Util.Beans.Objects.Object := Util.Beans.Objects.Maps.Element (Pos); begin if Util.Beans.Objects.Is_Null (Value) then return Default; else return Util.Beans.Objects.To_Integer (Value); end if; end; else return Default; end if; end Get_Parameter; -- ------------------------------ -- Get the job parameter identified by the <b>Name</b> and return it as a typed object. -- ------------------------------ function Get_Parameter (Job : in Abstract_Job_Type; Name : in String) return Util.Beans.Objects.Object is begin return Job.Props.Element (Name); end Get_Parameter; -- ------------------------------ -- Get the job status. -- ------------------------------ function Get_Status (Job : in Abstract_Job_Type) return AWA.Jobs.Models.Job_Status_Type is begin return Job.Job.Get_Status; end Get_Status; -- ------------------------------ -- Set the job status. -- When the job is terminated, it is closed and the job parameters or results cannot be -- changed. -- ------------------------------ procedure Set_Status (Job : in out Abstract_Job_Type; Status : in AWA.Jobs.Models.Job_Status_Type) is begin case Job.Job.Get_Status is when AWA.Jobs.Models.CANCELED | Models.FAILED | Models.TERMINATED => raise Closed_Error; when Models.SCHEDULED | Models.RUNNING => Job.Job.Set_Status (Status); end case; end Set_Status; -- ------------------------------ -- Save the job information in the database. Use the database session defined by <b>DB</b> -- to save the job. -- ------------------------------ procedure Save (Job : in out Abstract_Job_Type; DB : in out ADO.Sessions.Master_Session'Class) is begin if Job.Results_Modified then Job.Job.Set_Results (Util.Serialize.Tools.To_JSON (Job.Results)); Job.Results_Modified := False; end if; Job.Job.Save (DB); end Save; -- Schedule the job. procedure Schedule (Job : in out Abstract_Job_Type; Definition : in Job_Factory'Class) is procedure Set_Event (Manager : in out AWA.Events.Services.Event_Manager); Ctx : constant ASC.Service_Context_Access := ASC.Current; DB : ADO.Sessions.Master_Session := ASC.Get_Master_Session (Ctx); Msg : AWA.Events.Models.Message_Ref; User : constant AWA.Users.Models.User_Ref := Ctx.Get_User; Sess : constant AWA.Users.Models.Session_Ref := Ctx.Get_User_Session; App : constant AWA.Applications.Application_Access := Ctx.Get_Application; procedure Set_Event (Manager : in out AWA.Events.Services.Event_Manager) is begin Manager.Set_Message_Type (Msg, Job_Create_Event.Kind); Manager.Set_Event_Queue (Msg, "job-queue"); end Set_Event; begin if Job.Job.Is_Inserted then Log.Error ("Job is already scheduled"); raise Schedule_Error with "The job is already scheduled."; end if; AWA.Jobs.Modules.Create_Event (Msg); Job.Job.Set_Create_Date (Msg.Get_Create_Date); DB.Begin_Transaction; Job.Job.Set_Name (Definition.Get_Name); Job.Job.Set_User (User); Job.Job.Set_Session (Sess); Job.Save (DB); -- Create the event Msg.Set_Parameters (Util.Serialize.Tools.To_JSON (Job.Props)); App.Do_Event_Manager (Process => Set_Event'Access); Msg.Set_User (User); Msg.Set_Session (Sess); Msg.Set_Entity_Id (Job.Job.Get_Id); Msg.Set_Entity_Type (ADO.Sessions.Entities.Find_Entity_Type (Session => DB, Object => Job.Job.Get_Key)); Msg.Save (DB); Job.Job.Set_Event (Msg); Job.Job.Save (DB); DB.Commit; end Schedule; -- ------------------------------ -- Execute the job and save the job information in the database. -- ------------------------------ procedure Execute (Job : in out Abstract_Job_Type'Class; DB : in out ADO.Sessions.Master_Session'Class) is use type AWA.Jobs.Models.Job_Status_Type; begin -- Execute the job with an exception guard. begin Job.Execute; exception when E : others => Log.Error ("Exception when executing job {0}", Job.Job.Get_Name); Log.Error ("Exception:", E, True); Job.Job.Set_Status (Models.FAILED); end; -- If the job did not set a completion status, mark it as terminated. if Job.Job.Get_Status = Models.SCHEDULED or Job.Job.Get_Status = Models.RUNNING then Job.Job.Set_Status (Models.TERMINATED); end if; -- And save the job. DB.Begin_Transaction; Job.Job.Set_Finish_Date (ADO.Nullable_Time '(Is_Null => False, Value => Ada.Calendar.Clock)); Job.Save (DB); DB.Commit; end Execute; -- ------------------------------ -- Execute the job associated with the given event. -- ------------------------------ procedure Execute (Event : in AWA.Events.Module_Event'Class) is use AWA.Jobs.Modules; use type AWA.Modules.Module_Access; procedure Free is new Ada.Unchecked_Deallocation (Object => Abstract_Job_Type'Class, Name => Abstract_Job_Access); Ctx : constant ASC.Service_Context_Access := ASC.Current; App : constant AWA.Applications.Application_Access := Ctx.Get_Application; Module : constant AWA.Modules.Module_Access := App.Find_Module (AWA.Jobs.Modules.NAME); DB : ADO.Sessions.Master_Session := ASC.Get_Master_Session (Ctx); Job : AWA.Jobs.Models.Job_Ref; begin if Module = null then Log.Warn ("There is no Job module to execute a job"); raise Execute_Error; end if; if not (Module.all in AWA.Jobs.Modules.Job_Module'Class) then Log.Warn ("The 'job' module is not a valid module for job execution"); raise Execute_Error; end if; DB.Begin_Transaction; Job.Load (Session => DB, Id => Event.Get_Entity_Identifier); Job.Set_Start_Date (ADO.Nullable_Time '(Is_Null => False, Value => Ada.Calendar.Clock)); Job.Set_Status (AWA.Jobs.Models.RUNNING); Job.Save (Session => DB); DB.Commit; declare Name : constant String := Job.Get_Name; begin Log.Info ("Restoring job '{0}'", Name); declare Plugin : constant Job_Module_Access := Job_Module'Class (Module.all)'Access; Factory : constant Job_Factory_Access := Plugin.Find_Factory (Name); Work : AWA.Jobs.Services.Abstract_Job_Access := null; begin if Factory /= null then Work := Factory.Create; Work.Job := Job; Work.Execute (DB); Free (Work); else Log.Error ("There is no factory to execute job '{0}'", Name); Job.Set_Status (AWA.Jobs.Models.FAILED); Job.Set_Finish_Date (ADO.Nullable_Time '(Is_Null => False, Value => Ada.Calendar.Clock)); DB.Begin_Transaction; Job.Save (Session => DB); DB.Commit; end if; end; end; end Execute; function Get_Name (Factory : in Job_Factory'Class) return String is begin return Ada.Tags.Expanded_Name (Factory'Tag); end Get_Name; procedure Set_Work (Job : in out Job_Type; Work : in Work_Factory'Class) is begin Job.Work := Work.Work; Job.Job.Set_Name (Work.Get_Name); end Set_Work; procedure Execute (Job : in out Job_Type) is begin Job.Work (Job); end Execute; overriding function Create (Factory : in Work_Factory) return Abstract_Job_Access is begin return new Job_Type '(Ada.Finalization.Limited_Controlled with Work => Factory.Work, others => <>); end Create; -- ------------------------------ -- Job Declaration -- ------------------------------ -- The <tt>Definition</tt> package must be instantiated with a given job type to -- register the new job definition. package body Definition is function Create (Factory : in Job_Type_Factory) return Abstract_Job_Access is pragma Unreferenced (Factory); begin return new T; end Create; end Definition; end AWA.Jobs.Services;
----------------------------------------------------------------------- -- awa-jobs -- AWA Jobs -- Copyright (C) 2012 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Serialize.Tools; with Util.Log.Loggers; with Ada.Tags; with Ada.Calendar; with Ada.Unchecked_Deallocation; with ADO.Sessions.Entities; with AWA.Users.Models; with AWA.Events.Models; with AWA.Services.Contexts; with AWA.Jobs.Modules; with AWA.Applications; with AWA.Events.Services; with AWA.Modules; package body AWA.Jobs.Services is package ASC renames AWA.Services.Contexts; Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("AWA.Jobs.Services"); -- ------------------------------ -- Set the job parameter identified by the <b>Name</b> to the value given in <b>Value</b>. -- ------------------------------ procedure Set_Parameter (Job : in out Abstract_Job_Type; Name : in String; Value : in String) is begin Job.Set_Parameter (Name, Util.Beans.Objects.To_Object (Value)); end Set_Parameter; -- ------------------------------ -- Set the job parameter identified by the <b>Name</b> to the value given in <b>Value</b>. -- ------------------------------ procedure Set_Parameter (Job : in out Abstract_Job_Type; Name : in String; Value : in Integer) is begin Job.Set_Parameter (Name, Util.Beans.Objects.To_Object (Value)); end Set_Parameter; -- ------------------------------ -- Set the job parameter identified by the <b>Name</b> to the value given in <b>Value</b>. -- The value object can hold any kind of basic value type (integer, enum, date, strings). -- If the value represents a bean, the <tt>Invalid_Value</tt> exception is raised. -- ------------------------------ procedure Set_Parameter (Job : in out Abstract_Job_Type; Name : in String; Value : in Util.Beans.Objects.Object) is begin Job.Props.Include (Name, Value); Job.Props_Modified := True; end Set_Parameter; -- ------------------------------ -- Get the job parameter identified by the <b>Name</b> and convert the value into a string. -- ------------------------------ function Get_Parameter (Job : in Abstract_Job_Type; Name : in String) return String is Value : constant Util.Beans.Objects.Object := Job.Get_Parameter (Name); begin return Util.Beans.Objects.To_String (Value); end Get_Parameter; -- ------------------------------ -- Get the job parameter identified by the <b>Name</b> and convert the value as an integer. -- If the parameter is not defined, return the default value passed in <b>Default</b>. -- ------------------------------ function Get_Parameter (Job : in Abstract_Job_Type; Name : in String; Default : in Integer) return Integer is Pos : constant Util.Beans.Objects.Maps.Cursor := Job.Props.Find (Name); begin if Util.Beans.Objects.Maps.Has_Element (Pos) then declare Value : constant Util.Beans.Objects.Object := Util.Beans.Objects.Maps.Element (Pos); begin if Util.Beans.Objects.Is_Null (Value) then return Default; else return Util.Beans.Objects.To_Integer (Value); end if; end; else return Default; end if; end Get_Parameter; -- ------------------------------ -- Get the job parameter identified by the <b>Name</b> and return it as a typed object. -- ------------------------------ function Get_Parameter (Job : in Abstract_Job_Type; Name : in String) return Util.Beans.Objects.Object is begin return Job.Props.Element (Name); end Get_Parameter; -- ------------------------------ -- Get the job status. -- ------------------------------ function Get_Status (Job : in Abstract_Job_Type) return AWA.Jobs.Models.Job_Status_Type is begin return Job.Job.Get_Status; end Get_Status; -- ------------------------------ -- Set the job status. -- When the job is terminated, it is closed and the job parameters or results cannot be -- changed. -- ------------------------------ procedure Set_Status (Job : in out Abstract_Job_Type; Status : in AWA.Jobs.Models.Job_Status_Type) is begin case Job.Job.Get_Status is when AWA.Jobs.Models.CANCELED | Models.FAILED | Models.TERMINATED => raise Closed_Error; when Models.SCHEDULED | Models.RUNNING => Job.Job.Set_Status (Status); end case; end Set_Status; -- ------------------------------ -- Save the job information in the database. Use the database session defined by <b>DB</b> -- to save the job. -- ------------------------------ procedure Save (Job : in out Abstract_Job_Type; DB : in out ADO.Sessions.Master_Session'Class) is begin if Job.Results_Modified then Job.Job.Set_Results (Util.Serialize.Tools.To_JSON (Job.Results)); Job.Results_Modified := False; end if; Job.Job.Save (DB); end Save; -- Schedule the job. procedure Schedule (Job : in out Abstract_Job_Type; Definition : in Job_Factory'Class) is procedure Set_Event (Manager : in out AWA.Events.Services.Event_Manager); Ctx : constant ASC.Service_Context_Access := ASC.Current; DB : ADO.Sessions.Master_Session := ASC.Get_Master_Session (Ctx); Msg : AWA.Events.Models.Message_Ref; User : constant AWA.Users.Models.User_Ref := Ctx.Get_User; Sess : constant AWA.Users.Models.Session_Ref := Ctx.Get_User_Session; App : constant AWA.Applications.Application_Access := Ctx.Get_Application; procedure Set_Event (Manager : in out AWA.Events.Services.Event_Manager) is begin Manager.Set_Message_Type (Msg, Job_Create_Event.Kind); Manager.Set_Event_Queue (Msg, "job-queue"); end Set_Event; begin if Job.Job.Is_Inserted then Log.Error ("Job is already scheduled"); raise Schedule_Error with "The job is already scheduled."; end if; AWA.Jobs.Modules.Create_Event (Msg); Job.Job.Set_Create_Date (Msg.Get_Create_Date); DB.Begin_Transaction; Job.Job.Set_Name (Definition.Get_Name); Job.Job.Set_User (User); Job.Job.Set_Session (Sess); Job.Save (DB); -- Create the event Msg.Set_Parameters (Util.Serialize.Tools.To_JSON (Job.Props)); App.Do_Event_Manager (Process => Set_Event'Access); Msg.Set_User (User); Msg.Set_Session (Sess); Msg.Set_Entity_Id (Job.Job.Get_Id); Msg.Set_Entity_Type (ADO.Sessions.Entities.Find_Entity_Type (Session => DB, Object => Job.Job.Get_Key)); Msg.Save (DB); Job.Job.Set_Event (Msg); Job.Job.Save (DB); DB.Commit; end Schedule; -- ------------------------------ -- Execute the job and save the job information in the database. -- ------------------------------ procedure Execute (Job : in out Abstract_Job_Type'Class; DB : in out ADO.Sessions.Master_Session'Class) is use type AWA.Jobs.Models.Job_Status_Type; begin -- Execute the job with an exception guard. begin Job.Execute; exception when E : others => Log.Error ("Exception when executing job {0}", Job.Job.Get_Name); Log.Error ("Exception:", E, True); Job.Job.Set_Status (Models.FAILED); end; -- If the job did not set a completion status, mark it as terminated. if Job.Job.Get_Status = Models.SCHEDULED or Job.Job.Get_Status = Models.RUNNING then Job.Job.Set_Status (Models.TERMINATED); end if; -- And save the job. DB.Begin_Transaction; Job.Job.Set_Finish_Date (ADO.Nullable_Time '(Is_Null => False, Value => Ada.Calendar.Clock)); Job.Save (DB); DB.Commit; end Execute; -- ------------------------------ -- Execute the job associated with the given event. -- ------------------------------ procedure Execute (Event : in AWA.Events.Module_Event'Class) is use AWA.Jobs.Modules; use type AWA.Modules.Module_Access; procedure Free is new Ada.Unchecked_Deallocation (Object => Abstract_Job_Type'Class, Name => Abstract_Job_Access); Ctx : constant ASC.Service_Context_Access := ASC.Current; App : constant AWA.Applications.Application_Access := Ctx.Get_Application; Module : constant AWA.Modules.Module_Access := App.Find_Module (AWA.Jobs.Modules.NAME); DB : ADO.Sessions.Master_Session := ASC.Get_Master_Session (Ctx); Job : AWA.Jobs.Models.Job_Ref; begin if Module = null then Log.Warn ("There is no Job module to execute a job"); raise Execute_Error; end if; if not (Module.all in AWA.Jobs.Modules.Job_Module'Class) then Log.Warn ("The 'job' module is not a valid module for job execution"); raise Execute_Error; end if; DB.Begin_Transaction; Job.Load (Session => DB, Id => Event.Get_Entity_Identifier); Job.Set_Start_Date (ADO.Nullable_Time '(Is_Null => False, Value => Ada.Calendar.Clock)); Job.Set_Status (AWA.Jobs.Models.RUNNING); Job.Save (Session => DB); DB.Commit; declare Name : constant String := Job.Get_Name; begin Log.Info ("Restoring job '{0}'", Name); declare Plugin : constant Job_Module_Access := Job_Module'Class (Module.all)'Access; Factory : constant Job_Factory_Access := Plugin.Find_Factory (Name); Work : AWA.Jobs.Services.Abstract_Job_Access := null; begin if Factory /= null then Work := Factory.Create; Work.Job := Job; Event.Copy (Work.Props); Work.Execute (DB); Free (Work); else Log.Error ("There is no factory to execute job '{0}'", Name); Job.Set_Status (AWA.Jobs.Models.FAILED); Job.Set_Finish_Date (ADO.Nullable_Time '(Is_Null => False, Value => Ada.Calendar.Clock)); DB.Begin_Transaction; Job.Save (Session => DB); DB.Commit; end if; end; end; end Execute; function Get_Name (Factory : in Job_Factory'Class) return String is begin return Ada.Tags.Expanded_Name (Factory'Tag); end Get_Name; procedure Set_Work (Job : in out Job_Type; Work : in Work_Factory'Class) is begin Job.Work := Work.Work; Job.Job.Set_Name (Work.Get_Name); end Set_Work; procedure Execute (Job : in out Job_Type) is begin Job.Work (Job); end Execute; overriding function Create (Factory : in Work_Factory) return Abstract_Job_Access is begin return new Job_Type '(Ada.Finalization.Limited_Controlled with Work => Factory.Work, others => <>); end Create; -- ------------------------------ -- Job Declaration -- ------------------------------ -- The <tt>Definition</tt> package must be instantiated with a given job type to -- register the new job definition. package body Definition is function Create (Factory : in Job_Type_Factory) return Abstract_Job_Access is pragma Unreferenced (Factory); begin return new T; end Create; end Definition; end AWA.Jobs.Services;
Copy the event properties to the job properties so that the job parameters are available
Copy the event properties to the job properties so that the job parameters are available
Ada
apache-2.0
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
2c4d8079f873f7ebe084c43df5e26ceb7c51bbc8
regtests/security-testsuite.adb
regtests/security-testsuite.adb
----------------------------------------------------------------------- -- Security testsuite - Ada Security Test suite -- Copyright (C) 2011, 2012, 2013 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Security.OpenID.Tests; with Security.Permissions.Tests; with Security.Policies.Tests; with Security.OAuth.JWT.Tests; package body Security.Testsuite is 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 Security.OAuth.JWT.Tests.Add_Tests (Ret); Security.OpenID.Tests.Add_Tests (Ret); Security.Permissions.Tests.Add_Tests (Ret); Security.Policies.Tests.Add_Tests (Ret); return Ret; end Suite; end Security.Testsuite;
----------------------------------------------------------------------- -- Security testsuite - Ada Security Test suite -- Copyright (C) 2011, 2012, 2013 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Security.OpenID.Tests; with Security.Permissions.Tests; with Security.Policies.Tests; with Security.OAuth.JWT.Tests; with Security.OAuth.Clients.Tests; package body Security.Testsuite is 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 Security.OAuth.JWT.Tests.Add_Tests (Ret); Security.OpenID.Tests.Add_Tests (Ret); Security.Permissions.Tests.Add_Tests (Ret); Security.Policies.Tests.Add_Tests (Ret); Security.OAuth.Clients.Tests.Add_Tests (Ret); return Ret; end Suite; end Security.Testsuite;
Add the new unit tests
Add the new unit tests
Ada
apache-2.0
Letractively/ada-security
38fbc46246eeeec98e4fd02e3d99d2e63e5c57d8
src/gen-commands-database.adb
src/gen-commands-database.adb
----------------------------------------------------------------------- -- gen-commands-database -- Database creation from application model -- 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 GNAT.Command_Line; with GNAT.Expect; with GNAT.OS_Lib; with Ada.Text_IO; with Ada.Strings.Fixed; with Ada.IO_Exceptions; with Ada.Directories; with Ada.Exceptions; with Util.Strings; with Util.Files; with Util.Log.Loggers; with ADO.Drivers.Connections; with ADO.Sessions.Factory; with ADO.Statements; with ADO.Queries; with ADO.Parameters; with System; with Gen.Database.Model; package body Gen.Commands.Database is use GNAT.Command_Line; use Util.Log; Log : constant Loggers.Logger := Loggers.Create ("Gen.Commands.Database"); -- Check if the database with the given name exists. function Has_Database (DB : in ADO.Sessions.Session'Class; Name : in String) return Boolean; -- Check if the database with the given name has some tables. function Has_Tables (DB : in ADO.Sessions.Session'Class; Name : in String) return Boolean; -- Expect filter to print the command output/error procedure Command_Output (Descriptor : in GNAT.Expect.Process_Descriptor'Class; Data : in String; Closure : in System.Address); -- Execute the external command <b>Name</b> with the arguments in <b>Args</b> -- and send the content of the file <b>Input</b> to that command. procedure Execute_Command (Name : in String; Args : in GNAT.OS_Lib.Argument_List; Input : in String); -- Create the MySQL tables in the database. The tables are created by launching -- the external command 'mysql' and using the create-xxx-mysql.sql generated scripts. procedure Create_Mysql_Tables (Name : in String; Model : in String; Config : in ADO.Drivers.Connections.Configuration; Generator : in out Gen.Generator.Handler); -- Create the database identified by the given name. procedure Create_Database (DB : in ADO.Sessions.Master_Session; Name : in String); -- Create the user and grant him access to the database. procedure Create_User_Grant (DB : in ADO.Sessions.Master_Session; Name : in String; User : in String; Password : in String); -- ------------------------------ -- Check if the database with the given name exists. -- ------------------------------ function Has_Database (DB : in ADO.Sessions.Session'Class; Name : in String) return Boolean is Query : ADO.Queries.Context; Stmt : ADO.Statements.Query_Statement; begin Query.Set_Query (Gen.Database.Model.Query_Database_List); Stmt := DB.Create_Statement (Query); Stmt.Execute; while Stmt.Has_Elements loop declare D : constant String := Stmt.Get_String (0); begin if Name = D then return True; end if; end; Stmt.Next; end loop; return False; end Has_Database; -- ------------------------------ -- Check if the database with the given name has some tables. -- ------------------------------ function Has_Tables (DB : in ADO.Sessions.Session'Class; Name : in String) return Boolean is Query : ADO.Queries.Context; Stmt : ADO.Statements.Query_Statement; begin Query.Set_Query (Gen.Database.Model.Query_Table_List); Stmt := DB.Create_Statement (Query); Stmt.Bind_Param ("name", ADO.Parameters.Token (Name)); Stmt.Execute; return Stmt.Has_Elements; end Has_Tables; -- ------------------------------ -- Create the database identified by the given name. -- ------------------------------ procedure Create_Database (DB : in ADO.Sessions.Master_Session; Name : in String) is use Ada.Strings.Unbounded; Query : ADO.Queries.Context; Stmt : ADO.Statements.Query_Statement; begin Log.Info ("Creating database '{0}'", Name); Query.Set_Query (Gen.Database.Model.Query_Create_Database); Stmt := DB.Create_Statement (Query); Stmt.Bind_Param ("name", ADO.Parameters.Token (Name)); Stmt.Execute; end Create_Database; -- ------------------------------ -- Create the user and grant him access to the database. -- ------------------------------ procedure Create_User_Grant (DB : in ADO.Sessions.Master_Session; Name : in String; User : in String; Password : in String) is use Ada.Strings.Unbounded; Query : ADO.Queries.Context; Stmt : ADO.Statements.Query_Statement; begin Log.Info ("Granting access for user '{0}' to database '{1}'", User, Name); if Password'Length > 0 then Query.Set_Query (Gen.Database.Model.Query_Create_User_With_Password); else Query.Set_Query (Gen.Database.Model.Query_Create_User_No_Password); end if; Stmt := DB.Create_Statement (Query); Stmt.Bind_Param ("name", ADO.Parameters.Token (Name)); Stmt.Bind_Param ("user", ADO.Parameters.Token (User)); if Password'Length > 0 then Stmt.Bind_Param ("password", Password); end if; Stmt.Execute; Query.Set_Query (Gen.Database.Model.Query_Flush_Privileges); Stmt := DB.Create_Statement (Query); Stmt.Execute; end Create_User_Grant; -- ------------------------------ -- Expect filter to print the command output/error -- ------------------------------ procedure Command_Output (Descriptor : in GNAT.Expect.Process_Descriptor'Class; Data : in String; Closure : in System.Address) is pragma Unreferenced (Descriptor, Closure); begin Log.Error ("{0}", Data); end Command_Output; -- ------------------------------ -- Execute the external command <b>Name</b> with the arguments in <b>Args</b> -- and send the content of the file <b>Input</b> to that command. -- ------------------------------ procedure Execute_Command (Name : in String; Args : in GNAT.OS_Lib.Argument_List; Input : in String) is Proc : GNAT.Expect.Process_Descriptor; Status : Integer; Func : constant GNAT.Expect.Filter_Function := Command_Output'Access; Result : GNAT.Expect.Expect_Match; Content : Ada.Strings.Unbounded.Unbounded_String; begin Util.Files.Read_File (Path => Input, Into => Content); GNAT.Expect.Non_Blocking_Spawn (Descriptor => Proc, Command => Name, Args => Args, Buffer_Size => 4096, Err_To_Out => True); GNAT.Expect.Add_Filter (Descriptor => Proc, Filter => Func, Filter_On => GNAT.Expect.Output); GNAT.Expect.Send (Descriptor => Proc, Str => Ada.Strings.Unbounded.To_String (Content), Add_LF => False, Empty_Buffer => False); GNAT.Expect.Expect (Proc, Result, ".*"); GNAT.Expect.Close (Descriptor => Proc, Status => Status); if Status = 0 then Log.Info ("Database schema created successfully."); else Log.Error ("Error while creating the database schema."); end if; exception when Ada.IO_Exceptions.Name_Error => Log.Error ("Cannot read {0}", Input); end Execute_Command; -- ------------------------------ -- Create the MySQL tables in the database. The tables are created by launching -- the external command 'mysql' and using the create-xxx-mysql.sql generated scripts. -- ------------------------------ procedure Create_Mysql_Tables (Name : in String; Model : in String; Config : in ADO.Drivers.Connections.Configuration; Generator : in out Gen.Generator.Handler) is Database : constant String := Config.Get_Database; Username : constant String := Config.Get_Property ("user"); Password : constant String := Config.Get_Property ("password"); Dir : constant String := Util.Files.Compose (Model, "mysql"); File : constant String := Util.Files.Compose (Dir, "create-" & Name & "-mysql.sql"); begin Log.Info ("Creating database tables using schema '{0}'", File); if not Ada.Directories.Exists (File) then Generator.Error ("SQL file '{0}' does not exist.", File); Generator.Error ("Please, run the following command: dynamo generate db"); return; end if; if Password'Length > 0 then declare Args : GNAT.OS_Lib.Argument_List (1 .. 3); begin Args (1) := new String '("--user=" & Username); Args (2) := new String '("--password=" & Password); Args (3) := new String '(Database); Execute_Command ("mysql", Args, File); end; else declare Args : GNAT.OS_Lib.Argument_List (1 .. 2); begin Args (1) := new String '("--user=" & Username); Args (2) := new String '(Database); Execute_Command ("mysql", Args, File); end; end if; end Create_Mysql_Tables; -- ------------------------------ -- Execute the command with the arguments. -- ------------------------------ procedure Execute (Cmd : in Command; Generator : in out Gen.Generator.Handler) is pragma Unreferenced (Cmd); use Ada.Strings.Unbounded; procedure Create_Database (Model : in String; Database : in String; Username : in String; Password : in String); -- ------------------------------ -- Create the database, the user and the tables. -- ------------------------------ procedure Create_Database (Model : in String; Database : in String; Username : in String; Password : in String) is Factory : ADO.Sessions.Factory.Session_Factory; Config : ADO.Drivers.Connections.Configuration; Root_Connection : Unbounded_String; Pos : Natural; begin Config.Set_Connection (Database); if Config.Get_Property ("user") = "" then Generator.Error ("Invalid database connection: missing user property"); return; end if; if Config.Get_Database = "" then Generator.Error ("Invalid database connection: no database name specified"); return; end if; -- Build a connection string to create the database. Pos := Util.Strings.Index (Database, ':'); Append (Root_Connection, Database (Database'First .. Pos)); Append (Root_Connection, "//"); Append (Root_Connection, Config.Get_Server); if Config.Get_Port > 0 then Append (Root_Connection, ':'); Append (Root_Connection, Util.Strings.Image (Config.Get_Port)); end if; Append (Root_Connection, "/?user="); Append (Root_Connection, Username); if Password'Length > 0 then Append (Root_Connection, "&password="); Append (Root_Connection, Password); end if; Log.Info ("Connecting to {0}", Root_Connection); -- Initialize the session factory to connect to the -- database defined by root connection (which should allow the database creation). Factory.Create (To_String (Root_Connection)); declare Name : constant String := Generator.Get_Project_Name; DB : constant ADO.Sessions.Master_Session := Factory.Get_Master_Session; begin -- Create the database only if it does not already exists. if not Has_Database (DB, Config.Get_Database) then Create_Database (DB, Config.Get_Database); end if; -- If some tables exist, don't try to create tables again. -- We could improve by reading the current database schema, comparing with our -- schema and create what is missing (new tables, new columns). if Has_Tables (DB, Config.Get_Database) then Generator.Error ("The database {0} exists", Config.Get_Database); else -- Create the user grant. On MySQL, it is safe to do this several times. Create_User_Grant (DB, Config.Get_Database, Config.Get_Property ("user"), Config.Get_Property ("password")); -- And now create the tables by using the SQL script generated by Dyanmo. Create_Mysql_Tables (Name, Model, Config, Generator); end if; -- Remember the database connection string. Generator.Set_Project_Property ("database", Database); Generator.Save_Project; exception when E : others => Generator.Error (Ada.Exceptions.Exception_Message (E)); end; end Create_Database; Model : constant String := Get_Argument; Arg1 : constant String := Get_Argument; Arg2 : constant String := Get_Argument; Arg3 : constant String := Get_Argument; begin Generator.Read_Project ("dynamo.xml"); -- Initialize the database drivers. ADO.Drivers.Initialize (Generator.Get_Properties); -- Check if a database is specified in the command line and use it. if Ada.Strings.Fixed.Index (Arg1, "://") > 0 or Arg3'Length > 0 then Create_Database (Model, Arg1, Arg2, Arg3); else declare Database : constant String := Generator.Get_Project_Property ("database"); begin -- Otherwise, get the database identification from dynamo.xml configuration. if Ada.Strings.Fixed.Index (Database, "://") = 0 then Generator.Error ("No database specified."); return; end if; Create_Database (Model, Database, Arg1, Arg2); end; end if; end Execute; -- ------------------------------ -- Write the help associated with the command. -- ------------------------------ procedure Help (Cmd : in Command; Generator : in out Gen.Generator.Handler) is pragma Unreferenced (Cmd, Generator); use Ada.Text_IO; begin Put_Line ("create-database: Creates the database"); Put_Line ("Usage: create-database MODEL [CONNECTION] ADMIN-USER [ADMIN-PASSWORD]"); New_Line; Put_Line (" Create the database specified by the connection string."); Put_Line (" The connection string has the form:"); Put_Line (" driver://host[:port]/database"); New_Line; Put_Line (" The database must not exist. The user specified in the connection string"); Put_Line (" is granted the access to the new database."); end Help; end Gen.Commands.Database;
----------------------------------------------------------------------- -- gen-commands-database -- Database creation from application model -- 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 GNAT.Command_Line; with GNAT.Expect; with GNAT.OS_Lib; with Ada.Text_IO; with Ada.Strings.Fixed; with Ada.IO_Exceptions; with Ada.Directories; with Ada.Exceptions; with Util.Strings; with Util.Files; with Util.Log.Loggers; with ADO.Drivers.Connections; with ADO.Sessions.Factory; with ADO.Statements; with ADO.Queries; with ADO.Parameters; with System; with Gen.Database.Model; package body Gen.Commands.Database is use GNAT.Command_Line; use Util.Log; Log : constant Loggers.Logger := Loggers.Create ("Gen.Commands.Database"); -- Check if the database with the given name exists. function Has_Database (DB : in ADO.Sessions.Session'Class; Name : in String) return Boolean; -- Check if the database with the given name has some tables. function Has_Tables (DB : in ADO.Sessions.Session'Class; Name : in String) return Boolean; -- Expect filter to print the command output/error procedure Command_Output (Descriptor : in GNAT.Expect.Process_Descriptor'Class; Data : in String; Closure : in System.Address); -- Execute the external command <b>Name</b> with the arguments in <b>Args</b> -- and send the content of the file <b>Input</b> to that command. procedure Execute_Command (Name : in String; Args : in GNAT.OS_Lib.Argument_List; Input : in String); -- Create the MySQL tables in the database. The tables are created by launching -- the external command 'mysql' and using the create-xxx-mysql.sql generated scripts. procedure Create_Mysql_Tables (Name : in String; Model : in String; Config : in ADO.Drivers.Connections.Configuration; Generator : in out Gen.Generator.Handler); -- Create the database identified by the given name. procedure Create_Database (DB : in ADO.Sessions.Master_Session; Name : in String); -- Create the user and grant him access to the database. procedure Create_User_Grant (DB : in ADO.Sessions.Master_Session; Name : in String; User : in String; Password : in String); -- ------------------------------ -- Check if the database with the given name exists. -- ------------------------------ function Has_Database (DB : in ADO.Sessions.Session'Class; Name : in String) return Boolean is Query : ADO.Queries.Context; Stmt : ADO.Statements.Query_Statement; begin Query.Set_Query (Gen.Database.Model.Query_Database_List); Stmt := DB.Create_Statement (Query); Stmt.Execute; while Stmt.Has_Elements loop declare D : constant String := Stmt.Get_String (0); begin if Name = D then return True; end if; end; Stmt.Next; end loop; return False; end Has_Database; -- ------------------------------ -- Check if the database with the given name has some tables. -- ------------------------------ function Has_Tables (DB : in ADO.Sessions.Session'Class; Name : in String) return Boolean is Query : ADO.Queries.Context; Stmt : ADO.Statements.Query_Statement; begin Query.Set_Query (Gen.Database.Model.Query_Table_List); Stmt := DB.Create_Statement (Query); Stmt.Bind_Param ("name", ADO.Parameters.Token (Name)); Stmt.Execute; return Stmt.Has_Elements; end Has_Tables; -- ------------------------------ -- Create the database identified by the given name. -- ------------------------------ procedure Create_Database (DB : in ADO.Sessions.Master_Session; Name : in String) is use Ada.Strings.Unbounded; Query : ADO.Queries.Context; Stmt : ADO.Statements.Query_Statement; begin Log.Info ("Creating database '{0}'", Name); Query.Set_Query (Gen.Database.Model.Query_Create_Database); Stmt := DB.Create_Statement (Query); Stmt.Bind_Param ("name", ADO.Parameters.Token (Name)); Stmt.Execute; end Create_Database; -- ------------------------------ -- Create the user and grant him access to the database. -- ------------------------------ procedure Create_User_Grant (DB : in ADO.Sessions.Master_Session; Name : in String; User : in String; Password : in String) is use Ada.Strings.Unbounded; Query : ADO.Queries.Context; Stmt : ADO.Statements.Query_Statement; begin Log.Info ("Granting access for user '{0}' to database '{1}'", User, Name); if Password'Length > 0 then Query.Set_Query (Gen.Database.Model.Query_Create_User_With_Password); else Query.Set_Query (Gen.Database.Model.Query_Create_User_No_Password); end if; Stmt := DB.Create_Statement (Query); Stmt.Bind_Param ("name", ADO.Parameters.Token (Name)); Stmt.Bind_Param ("user", ADO.Parameters.Token (User)); if Password'Length > 0 then Stmt.Bind_Param ("password", Password); end if; Stmt.Execute; Query.Set_Query (Gen.Database.Model.Query_Flush_Privileges); Stmt := DB.Create_Statement (Query); Stmt.Execute; end Create_User_Grant; -- ------------------------------ -- Expect filter to print the command output/error -- ------------------------------ procedure Command_Output (Descriptor : in GNAT.Expect.Process_Descriptor'Class; Data : in String; Closure : in System.Address) is pragma Unreferenced (Descriptor, Closure); begin Log.Error ("{0}", Data); end Command_Output; -- ------------------------------ -- Execute the external command <b>Name</b> with the arguments in <b>Args</b> -- and send the content of the file <b>Input</b> to that command. -- ------------------------------ procedure Execute_Command (Name : in String; Args : in GNAT.OS_Lib.Argument_List; Input : in String) is Proc : GNAT.Expect.Process_Descriptor; Status : Integer; Func : constant GNAT.Expect.Filter_Function := Command_Output'Access; Result : GNAT.Expect.Expect_Match; Content : Ada.Strings.Unbounded.Unbounded_String; begin Util.Files.Read_File (Path => Input, Into => Content); GNAT.Expect.Non_Blocking_Spawn (Descriptor => Proc, Command => Name, Args => Args, Buffer_Size => 4096, Err_To_Out => True); GNAT.Expect.Add_Filter (Descriptor => Proc, Filter => Func, Filter_On => GNAT.Expect.Output); GNAT.Expect.Send (Descriptor => Proc, Str => Ada.Strings.Unbounded.To_String (Content), Add_LF => False, Empty_Buffer => False); GNAT.Expect.Expect (Proc, Result, ".*"); GNAT.Expect.Close (Descriptor => Proc, Status => Status); if Status = 0 then Log.Info ("Database schema created successfully."); else Log.Error ("Error while creating the database schema."); end if; exception when Ada.IO_Exceptions.Name_Error => Log.Error ("Cannot read {0}", Input); end Execute_Command; -- ------------------------------ -- Create the MySQL tables in the database. The tables are created by launching -- the external command 'mysql' and using the create-xxx-mysql.sql generated scripts. -- ------------------------------ procedure Create_Mysql_Tables (Name : in String; Model : in String; Config : in ADO.Drivers.Connections.Configuration; Generator : in out Gen.Generator.Handler) is Database : constant String := Config.Get_Database; Username : constant String := Config.Get_Property ("user"); Password : constant String := Config.Get_Property ("password"); Dir : constant String := Util.Files.Compose (Model, "mysql"); File : constant String := Util.Files.Compose (Dir, "create-" & Name & "-mysql.sql"); begin Log.Info ("Creating database tables using schema '{0}'", File); if not Ada.Directories.Exists (File) then Generator.Error ("SQL file '{0}' does not exist.", File); Generator.Error ("Please, run the following command: dynamo generate db"); return; end if; if Password'Length > 0 then declare Args : GNAT.OS_Lib.Argument_List (1 .. 3); begin Args (1) := new String '("--user=" & Username); Args (2) := new String '("--password=" & Password); Args (3) := new String '(Database); Execute_Command ("mysql", Args, File); end; else declare Args : GNAT.OS_Lib.Argument_List (1 .. 2); begin Args (1) := new String '("--user=" & Username); Args (2) := new String '(Database); Execute_Command ("mysql", Args, File); end; end if; end Create_Mysql_Tables; -- ------------------------------ -- Execute the command with the arguments. -- ------------------------------ procedure Execute (Cmd : in Command; Generator : in out Gen.Generator.Handler) is pragma Unreferenced (Cmd); use Ada.Strings.Unbounded; procedure Create_Database (Model : in String; Database : in String; Username : in String; Password : in String); -- ------------------------------ -- Create the database, the user and the tables. -- ------------------------------ procedure Create_Database (Model : in String; Database : in String; Username : in String; Password : in String) is Factory : ADO.Sessions.Factory.Session_Factory; Config : ADO.Drivers.Connections.Configuration; Root_Connection : Unbounded_String; Pos : Natural; begin Config.Set_Connection (Database); if Config.Get_Property ("user") = "" then Generator.Error ("Invalid database connection: missing user property"); return; end if; if Config.Get_Database = "" then Generator.Error ("Invalid database connection: no database name specified"); return; end if; -- Build a connection string to create the database. Pos := Util.Strings.Index (Database, ':'); Append (Root_Connection, Database (Database'First .. Pos)); Append (Root_Connection, "//"); Append (Root_Connection, Config.Get_Server); if Config.Get_Port > 0 then Append (Root_Connection, ':'); Append (Root_Connection, Util.Strings.Image (Config.Get_Port)); end if; Append (Root_Connection, "/?user="); Append (Root_Connection, Username); if Password'Length > 0 then Append (Root_Connection, "&password="); Append (Root_Connection, Password); end if; Log.Info ("Connecting to {0} for database setup", Root_Connection); -- Initialize the session factory to connect to the -- database defined by root connection (which should allow the database creation). Factory.Create (To_String (Root_Connection)); declare Name : constant String := Generator.Get_Project_Name; DB : constant ADO.Sessions.Master_Session := Factory.Get_Master_Session; begin -- Create the database only if it does not already exists. if not Has_Database (DB, Config.Get_Database) then Create_Database (DB, Config.Get_Database); end if; -- If some tables exist, don't try to create tables again. -- We could improve by reading the current database schema, comparing with our -- schema and create what is missing (new tables, new columns). if Has_Tables (DB, Config.Get_Database) then Generator.Error ("The database {0} exists", Config.Get_Database); else -- Create the user grant. On MySQL, it is safe to do this several times. Create_User_Grant (DB, Config.Get_Database, Config.Get_Property ("user"), Config.Get_Property ("password")); -- And now create the tables by using the SQL script generated by Dyanmo. Create_Mysql_Tables (Name, Model, Config, Generator); end if; -- Remember the database connection string. Generator.Set_Project_Property ("database", Database); Generator.Save_Project; exception when E : others => Generator.Error (Ada.Exceptions.Exception_Message (E)); end; end Create_Database; Model : constant String := Get_Argument; Arg1 : constant String := Get_Argument; Arg2 : constant String := Get_Argument; Arg3 : constant String := Get_Argument; begin Generator.Read_Project ("dynamo.xml"); -- Initialize the database drivers. ADO.Drivers.Initialize (Generator.Get_Properties); -- Check if a database is specified in the command line and use it. if Ada.Strings.Fixed.Index (Arg1, "://") > 0 or Arg3'Length > 0 then Create_Database (Model, Arg1, Arg2, Arg3); else declare Database : constant String := Generator.Get_Project_Property ("database"); begin -- Otherwise, get the database identification from dynamo.xml configuration. if Ada.Strings.Fixed.Index (Database, "://") = 0 then Generator.Error ("No database specified."); return; end if; Create_Database (Model, Database, Arg1, Arg2); end; end if; end Execute; -- ------------------------------ -- Write the help associated with the command. -- ------------------------------ procedure Help (Cmd : in Command; Generator : in out Gen.Generator.Handler) is pragma Unreferenced (Cmd, Generator); use Ada.Text_IO; begin Put_Line ("create-database: Creates the database"); Put_Line ("Usage: create-database MODEL [CONNECTION] ADMIN-USER [ADMIN-PASSWORD]"); New_Line; Put_Line (" Create the database specified by the connection string."); Put_Line (" The connection string has the form:"); Put_Line (" driver://host[:port]/database"); New_Line; Put_Line (" The database must not exist. The user specified in the connection string"); Put_Line (" is granted the access to the new database."); end Help; end Gen.Commands.Database;
Fix log message
Fix log message
Ada
apache-2.0
Letractively/ada-gen,Letractively/ada-gen,Letractively/ada-gen,Letractively/ada-gen
10c57b6911c2b88219cac264638d3dba2e1eea79
src/sys/os-windows/util-streams-raw.adb
src/sys/os-windows/util-streams-raw.adb
----------------------------------------------------------------------- -- util-streams-raw -- Raw streams for Windows based systems -- Copyright (C) 2011, 2019 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.IO_Exceptions; with System; package body Util.Streams.Raw is use System; use Util.Systems.Os; -- ----------------------- -- Initialize the raw stream to read and write on the given file descriptor. -- ----------------------- procedure Initialize (Stream : in out Raw_Stream; File : in File_Type) is begin if Stream.File /= NO_FILE then raise Ada.IO_Exceptions.Status_Error; end if; Stream.File := File; end Initialize; -- ----------------------- -- Get the file descriptor associated with the stream. -- ----------------------- function Get_File (Stream : in Raw_Stream) return Util.Systems.Os.File_Type is begin return Stream.File; end Get_File; -- ----------------------- -- Set the file descriptor to be used by the stream. -- ----------------------- procedure Set_File (Stream : in out Raw_Stream; File : in Util.Systems.Os.File_Type) is begin Stream.File := File; end Set_File; -- ----------------------- -- Close the stream. -- ----------------------- overriding procedure Close (Stream : in out Raw_Stream) is Error : Integer; begin if Stream.File /= NO_FILE then if Close_Handle (Stream.File) = 0 then Error := Get_Last_Error; if Error /= ERROR_BROKEN_PIPE then raise Ada.IO_Exceptions.Device_Error with "IO error: " & Integer'Image (Error); end if; end if; Stream.File := NO_FILE; end if; end Close; -- ----------------------- -- Write the buffer array to the output stream. -- ----------------------- procedure Write (Stream : in out Raw_Stream; Buffer : in Ada.Streams.Stream_Element_Array) is Res : aliased DWORD := 0; Status : BOOL; begin Status := Write_File (Stream.File, Buffer'Address, Buffer'Length, Res'Unchecked_Access, System.Null_Address); if Status = 0 then raise Ada.IO_Exceptions.Device_Error; end if; end Write; -- ----------------------- -- Read into the buffer as many bytes as possible and return in -- <b>last</b> the position of the last byte read. -- ----------------------- procedure Read (Stream : in out Raw_Stream; Into : out Ada.Streams.Stream_Element_Array; Last : out Ada.Streams.Stream_Element_Offset) is Res : aliased DWORD := 0; Status : BOOL; Error : Integer; begin Status := Read_File (Stream.File, Into'Address, Into'Length, Res'Unchecked_Access, System.Null_Address); if Status = 0 then Error := Get_Last_Error; if Error /= ERROR_BROKEN_PIPE then raise Ada.IO_Exceptions.Device_Error with "IO error: " & Integer'Image (Error); end if; end if; Last := Into'First + Ada.Streams.Stream_Element_Offset (Res) - 1; end Read; -- ----------------------- -- Flush the stream and release the buffer. -- ----------------------- procedure Finalize (Object : in out Raw_Stream) is begin Close (Object); end Finalize; end Util.Streams.Raw;
----------------------------------------------------------------------- -- util-streams-raw -- Raw streams for Windows based systems -- Copyright (C) 2011, 2019 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.IO_Exceptions; with System; package body Util.Streams.Raw is use System; use Util.Systems.Os; use type Util.Systems.Os.HANDLE; -- ----------------------- -- Initialize the raw stream to read and write on the given file descriptor. -- ----------------------- procedure Initialize (Stream : in out Raw_Stream; File : in File_Type) is begin if Stream.File /= NO_FILE then raise Ada.IO_Exceptions.Status_Error; end if; Stream.File := File; end Initialize; -- ----------------------- -- Get the file descriptor associated with the stream. -- ----------------------- function Get_File (Stream : in Raw_Stream) return Util.Systems.Os.File_Type is begin return Stream.File; end Get_File; -- ----------------------- -- Set the file descriptor to be used by the stream. -- ----------------------- procedure Set_File (Stream : in out Raw_Stream; File : in Util.Systems.Os.File_Type) is begin Stream.File := File; end Set_File; -- ----------------------- -- Close the stream. -- ----------------------- overriding procedure Close (Stream : in out Raw_Stream) is Error : Integer; begin if Stream.File /= NO_FILE then if Close_Handle (Stream.File) = 0 then Error := Get_Last_Error; if Error /= ERROR_BROKEN_PIPE then raise Ada.IO_Exceptions.Device_Error with "IO error: " & Integer'Image (Error); end if; end if; Stream.File := NO_FILE; end if; end Close; -- ----------------------- -- Write the buffer array to the output stream. -- ----------------------- procedure Write (Stream : in out Raw_Stream; Buffer : in Ada.Streams.Stream_Element_Array) is Res : aliased DWORD := 0; Status : BOOL; begin Status := Write_File (Stream.File, Buffer'Address, Buffer'Length, Res'Unchecked_Access, System.Null_Address); if Status = 0 then raise Ada.IO_Exceptions.Device_Error; end if; end Write; -- ----------------------- -- Read into the buffer as many bytes as possible and return in -- <b>last</b> the position of the last byte read. -- ----------------------- procedure Read (Stream : in out Raw_Stream; Into : out Ada.Streams.Stream_Element_Array; Last : out Ada.Streams.Stream_Element_Offset) is Res : aliased DWORD := 0; Status : BOOL; Error : Integer; begin Status := Read_File (Stream.File, Into'Address, Into'Length, Res'Unchecked_Access, System.Null_Address); if Status = 0 then Error := Get_Last_Error; if Error /= ERROR_BROKEN_PIPE then raise Ada.IO_Exceptions.Device_Error with "IO error: " & Integer'Image (Error); end if; end if; Last := Into'First + Ada.Streams.Stream_Element_Offset (Res) - 1; end Read; -- ----------------------- -- Flush the stream and release the buffer. -- ----------------------- procedure Finalize (Object : in out Raw_Stream) is begin Close (Object); end Finalize; end Util.Streams.Raw;
Update after HANDLE type change
Update after HANDLE type change
Ada
apache-2.0
stcarrez/ada-util,stcarrez/ada-util
80beb14cf5ef1163c533d7cb9e15b4f4bb0f793d
src/babel-strategies.adb
src/babel-strategies.adb
----------------------------------------------------------------------- -- babel-strategies -- Strategies to backup files -- Copyright (C) 2014 Stephane.Carrez -- Written by Stephane.Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Log.Loggers; with Babel.Files; with Babel.Files.Buffers; with Babel.Files.Lifecycles; with Babel.Stores; package body Babel.Strategies is Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("Babel.Strategies"); -- ------------------------------ -- Allocate a buffer to read the file content. -- ------------------------------ function Allocate_Buffer (Strategy : in Strategy_Type) return Babel.Files.Buffers.Buffer_Access is Result : Babel.Files.Buffers.Buffer_Access; begin Strategy.Buffers.Get_Buffer (Result); return Result; end Allocate_Buffer; -- ------------------------------ -- Release the buffer that was allocated by Allocate_Buffer. -- ------------------------------ procedure Release_Buffer (Strategy : in Strategy_Type; Buffer : in out Babel.Files.Buffers.Buffer_Access) is begin Babel.Files.Buffers.Release (Buffer); Buffer := null; end Release_Buffer; -- ------------------------------ -- Set the buffer pool to be used by Allocate_Buffer. -- ------------------------------ procedure Set_Buffers (Strategy : in out Strategy_Type; Buffers : in Babel.Files.Buffers.Buffer_Pool_Access) is begin Strategy.Buffers := Buffers; end Set_Buffers; -- Read the file from the read store into the local buffer. procedure Read_File (Strategy : in Strategy_Type; File : in Babel.Files.File_Type; Into : in Babel.Files.Buffers.Buffer_Access) is Path : constant String := Babel.Files.Get_Path (File); begin Strategy.Read_Store.Read (Path, Into.all); end Read_File; -- Write the file from the local buffer into the write store. procedure Write_File (Strategy : in Strategy_Type; File : in Babel.Files.File_Type; Content : in Babel.Files.Buffers.Buffer_Access) is Path : constant String := Babel.Files.Get_Path (File); begin Strategy.Write_Store.Write (Path, Content.all); end Write_File; -- Backup the file from the local buffer into the write store. procedure Backup_File (Strategy : in Strategy_Type; File : in Babel.Files.File_Type; Content : in out Babel.Files.Buffers.Buffer_Access) is begin Strategy.Database.Insert (File); if Strategy.Listeners /= null then if Babel.Files.Is_New (File) then Babel.Files.Lifecycles.Notify_Create (Strategy.Listeners.all, File); else Babel.Files.Lifecycles.Notify_Update (Strategy.Listeners.all, File); end if; end if; Strategy.Write_File (File, Content); Strategy.Release_Buffer (Content); end Backup_File; -- Scan the directory procedure Scan (Strategy : in out Strategy_Type; Directory : in Babel.Files.Directory_Type; Container : in out Babel.Files.File_Container'Class) is Path : constant String := Babel.Files.Get_Path (Directory); begin Strategy.Read_Store.Scan (Path, Container, Strategy.Filters.all); end Scan; -- ------------------------------ -- Scan the directories which are defined in the directory queue and -- use the file container to scan the files and directories. -- ------------------------------ procedure Scan (Strategy : in out Strategy_Type; Queue : in out Babel.Files.Queues.Directory_Queue; Container : in out Babel.Files.File_Container'Class) is procedure Append_Directory (Directory : in Babel.Files.Directory_Type) is begin Babel.Files.Queues.Add_Directory (Queue, Directory); end Append_Directory; Dir : Babel.Files.Directory_Type; begin while Babel.Files.Queues.Has_Directory (Queue) loop Babel.Files.Queues.Peek_Directory (Queue, Dir); Container.Set_Directory (Dir); Strategy_Type'Class (Strategy).Scan (Dir, Container); Container.Each_Directory (Append_Directory'Access); end loop; end Scan; -- ------------------------------ -- Set the file filters that will be used when scanning the read store. -- ------------------------------ procedure Set_Filters (Strategy : in out Strategy_Type; Filters : in Babel.Filters.Filter_Type_Access) is begin Strategy.Filters := Filters; end Set_Filters; -- ------------------------------ -- Set the read and write stores that the strategy will use. -- ------------------------------ procedure Set_Stores (Strategy : in out Strategy_Type; Read : in Babel.Stores.Store_Type_Access; Write : in Babel.Stores.Store_Type_Access) is begin Strategy.Read_Store := Read; Strategy.Write_Store := Write; end Set_Stores; -- ------------------------------ -- Set the listeners to inform about changes. -- ------------------------------ procedure Set_Listeners (Strategy : in out Strategy_Type; Listeners : access Util.Listeners.List) is begin Strategy.Listeners := Listeners; end Set_Listeners; -- ------------------------------ -- Set the database for use by the strategy. -- ------------------------------ procedure Set_Database (Strategy : in out Strategy_Type; Database : in Babel.Base.Database_Access) is begin Strategy.Database := Database; end Set_Database; end Babel.Strategies;
----------------------------------------------------------------------- -- babel-strategies -- Strategies to backup files -- Copyright (C) 2014 Stephane.Carrez -- Written by Stephane.Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Log.Loggers; with Babel.Files; with Babel.Files.Buffers; with Babel.Files.Lifecycles; with Babel.Stores; package body Babel.Strategies is Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("Babel.Strategies"); -- ------------------------------ -- Allocate a buffer to read the file content. -- ------------------------------ function Allocate_Buffer (Strategy : in Strategy_Type) return Babel.Files.Buffers.Buffer_Access is Result : Babel.Files.Buffers.Buffer_Access; begin Strategy.Buffers.Get_Buffer (Result); return Result; end Allocate_Buffer; -- ------------------------------ -- Release the buffer that was allocated by Allocate_Buffer. -- ------------------------------ procedure Release_Buffer (Strategy : in Strategy_Type; Buffer : in out Babel.Files.Buffers.Buffer_Access) is begin Babel.Files.Buffers.Release (Buffer); Buffer := null; end Release_Buffer; -- ------------------------------ -- Set the buffer pool to be used by Allocate_Buffer. -- ------------------------------ procedure Set_Buffers (Strategy : in out Strategy_Type; Buffers : in Babel.Files.Buffers.Buffer_Pool_Access) is begin Strategy.Buffers := Buffers; end Set_Buffers; -- Read the file from the read store into the local buffer. procedure Read_File (Strategy : in Strategy_Type; File : in Babel.Files.File_Type; Into : in Babel.Files.Buffers.Buffer_Access) is Path : constant String := Babel.Files.Get_Path (File); begin Strategy.Read_Store.Read (Path, Into.all); end Read_File; -- Write the file from the local buffer into the write store. procedure Write_File (Strategy : in Strategy_Type; File : in Babel.Files.File_Type; Content : in Babel.Files.Buffers.Buffer_Access) is Path : constant String := Babel.Files.Get_Path (File); begin Strategy.Write_Store.Write (Path, Content.all); end Write_File; -- Backup the file from the local buffer into the write store. procedure Backup_File (Strategy : in out Strategy_Type; File : in Babel.Files.File_Type; Content : in out Babel.Files.Buffers.Buffer_Access) is begin Strategy.Database.Insert (File); if Strategy.Listeners /= null then if Babel.Files.Is_New (File) then Babel.Files.Lifecycles.Notify_Create (Strategy.Listeners.all, File); else Babel.Files.Lifecycles.Notify_Update (Strategy.Listeners.all, File); end if; end if; Strategy.Write_File (File, Content); Strategy.Release_Buffer (Content); end Backup_File; -- Scan the directory procedure Scan (Strategy : in out Strategy_Type; Directory : in Babel.Files.Directory_Type; Container : in out Babel.Files.File_Container'Class) is Path : constant String := Babel.Files.Get_Path (Directory); begin Strategy.Read_Store.Scan (Path, Container, Strategy.Filters.all); end Scan; -- ------------------------------ -- Scan the directories which are defined in the directory queue and -- use the file container to scan the files and directories. -- ------------------------------ procedure Scan (Strategy : in out Strategy_Type; Queue : in out Babel.Files.Queues.Directory_Queue; Container : in out Babel.Files.File_Container'Class) is procedure Append_Directory (Directory : in Babel.Files.Directory_Type) is begin Babel.Files.Queues.Add_Directory (Queue, Directory); end Append_Directory; Dir : Babel.Files.Directory_Type; begin while Babel.Files.Queues.Has_Directory (Queue) loop Babel.Files.Queues.Peek_Directory (Queue, Dir); Container.Set_Directory (Dir); Strategy_Type'Class (Strategy).Scan (Dir, Container); Container.Each_Directory (Append_Directory'Access); end loop; end Scan; -- ------------------------------ -- Set the file filters that will be used when scanning the read store. -- ------------------------------ procedure Set_Filters (Strategy : in out Strategy_Type; Filters : in Babel.Filters.Filter_Type_Access) is begin Strategy.Filters := Filters; end Set_Filters; -- ------------------------------ -- Set the read and write stores that the strategy will use. -- ------------------------------ procedure Set_Stores (Strategy : in out Strategy_Type; Read : in Babel.Stores.Store_Type_Access; Write : in Babel.Stores.Store_Type_Access) is begin Strategy.Read_Store := Read; Strategy.Write_Store := Write; end Set_Stores; -- ------------------------------ -- Set the listeners to inform about changes. -- ------------------------------ procedure Set_Listeners (Strategy : in out Strategy_Type; Listeners : access Util.Listeners.List) is begin Strategy.Listeners := Listeners; end Set_Listeners; -- ------------------------------ -- Set the database for use by the strategy. -- ------------------------------ procedure Set_Database (Strategy : in out Strategy_Type; Database : in Babel.Base.Database_Access) is begin -- Strategy.Database := Database; null; end Set_Database; end Babel.Strategies;
Update Backup_File operation so that it uses in out strategy
Update Backup_File operation so that it uses in out strategy
Ada
apache-2.0
stcarrez/babel
8d2a0df1cc5b918881c0059e6cb21f098225274e
src/asf-views-nodes-reader.ads
src/asf-views-nodes-reader.ads
----------------------------------------------------------------------- -- asf -- XHTML Reader -- 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 Sax.Exceptions; with Sax.Locators; with Sax.Readers; with Sax.Attributes; with Unicode.CES; with Input_Sources; with EL.Contexts; with EL.Contexts.Default; with ASF.Factory; private with EL.Functions; private with Util.Strings.Maps; package ASF.Views.Nodes.Reader is type Xhtml_Reader is new Sax.Readers.Reader with private; overriding procedure Warning (Handler : in out Xhtml_Reader; Except : in Sax.Exceptions.Sax_Parse_Exception'Class); overriding procedure Error (Handler : in out Xhtml_Reader; Except : in Sax.Exceptions.Sax_Parse_Exception'Class); overriding procedure Fatal_Error (Handler : in out Xhtml_Reader; Except : in Sax.Exceptions.Sax_Parse_Exception'Class); overriding procedure Set_Document_Locator (Handler : in out Xhtml_Reader; Loc : in out Sax.Locators.Locator); overriding procedure Start_Document (Handler : in out Xhtml_Reader); overriding procedure End_Document (Handler : in out Xhtml_Reader); overriding procedure Start_Prefix_Mapping (Handler : in out Xhtml_Reader; Prefix : in Unicode.CES.Byte_Sequence; URI : in Unicode.CES.Byte_Sequence); overriding procedure End_Prefix_Mapping (Handler : in out Xhtml_Reader; Prefix : in Unicode.CES.Byte_Sequence); overriding procedure Start_Element (Handler : in out Xhtml_Reader; Namespace_URI : in Unicode.CES.Byte_Sequence := ""; Local_Name : in Unicode.CES.Byte_Sequence := ""; Qname : in Unicode.CES.Byte_Sequence := ""; Atts : in Sax.Attributes.Attributes'Class); overriding procedure End_Element (Handler : in out Xhtml_Reader; Namespace_URI : in Unicode.CES.Byte_Sequence := ""; Local_Name : in Unicode.CES.Byte_Sequence := ""; Qname : in Unicode.CES.Byte_Sequence := ""); overriding procedure Characters (Handler : in out Xhtml_Reader; Ch : in Unicode.CES.Byte_Sequence); overriding procedure Ignorable_Whitespace (Handler : in out Xhtml_Reader; Ch : in Unicode.CES.Byte_Sequence); overriding procedure Processing_Instruction (Handler : in out Xhtml_Reader; Target : in Unicode.CES.Byte_Sequence; Data : in Unicode.CES.Byte_Sequence); overriding procedure Skipped_Entity (Handler : in out Xhtml_Reader; Name : in Unicode.CES.Byte_Sequence); overriding procedure Start_Cdata (Handler : in out Xhtml_Reader); overriding procedure End_Cdata (Handler : in out Xhtml_Reader); overriding function Resolve_Entity (Handler : Xhtml_Reader; Public_Id : Unicode.CES.Byte_Sequence; System_Id : Unicode.CES.Byte_Sequence) return Input_Sources.Input_Source_Access; overriding procedure Start_DTD (Handler : in out Xhtml_Reader; Name : Unicode.CES.Byte_Sequence; Public_Id : Unicode.CES.Byte_Sequence := ""; System_Id : Unicode.CES.Byte_Sequence := ""); -- Get the root node that was created upon parsing of the XHTML file. function Get_Root (Reader : Xhtml_Reader) return Tag_Node_Access; -- Set the XHTML reader to ignore or not the white spaces. -- When set to True, the ignorable white spaces will not be kept. procedure Set_Ignore_White_Spaces (Reader : in out Xhtml_Reader; Value : in Boolean); -- Set the XHTML reader to escape or not the unknown tags. -- When set to True, the tags which are not recognized will be -- emitted as a raw text component and they will be escaped using -- the XML escape rules. procedure Set_Escape_Unknown_Tags (Reader : in out Xhtml_Reader; Value : in Boolean); -- Set the XHTML reader to ignore empty lines. procedure Set_Ignore_Empty_Lines (Reader : in out Xhtml_Reader; Value : in Boolean); -- Parse an XML stream, and calls the appropriate SAX callbacks for each -- event. -- This is not re-entrant: you can not call Parse with the same Parser -- argument in one of the SAX callbacks. This has undefined behavior. procedure Parse (Parser : in out Xhtml_Reader; Name : in ASF.Views.File_Info_Access; Input : in out Input_Sources.Input_Source'Class; Factory : access ASF.Factory.Component_Factory; Context : in EL.Contexts.ELContext_Access); private -- Collect the text for an EL expression. The EL expression starts -- with either '#{' or with '${' and ends with the matching '}'. -- If the <b>Value</b> string does not contain the whole EL experssion -- the <b>Expr_Buffer</b> stored in the reader is used to collect -- that expression. procedure Collect_Expression (Handler : in out Xhtml_Reader); -- Collect the raw-text in a buffer. The text must be flushed -- when a new element is started or when an exiting element is closed. procedure Collect_Text (Handler : in out Xhtml_Reader; Value : in Unicode.CES.Byte_Sequence); use EL.Functions; -- use ASF.Components.Factory; package NS_Mapping renames Util.Strings.Maps; -- Skip indicates the number of frames to skip in the saved locations -- stack type NS_Function_Mapper is new Function_Mapper with record Mapping : NS_Mapping.Map; Mapper : Function_Mapper_Access; Factory : access ASF.Factory.Component_Factory; end record; -- Find the function knowing its name. overriding function Get_Function (Mapper : NS_Function_Mapper; Namespace : String; Name : String) return Function_Access; -- Bind a name to a function in the given namespace. overriding procedure Set_Function (Mapper : in out NS_Function_Mapper; Namespace : in String; Name : in String; Func : in Function_Access); -- Find the create function in bound to the name in the given namespace. -- Returns null if no such binding exist. function Find (Mapper : in NS_Function_Mapper; Namespace : in String; Name : in String) return ASF.Views.Nodes.Binding_Access; procedure Set_Namespace (Mapper : in out NS_Function_Mapper; Prefix : in String; URI : in String); -- Remove the namespace prefix binding. procedure Remove_Namespace (Mapper : in out NS_Function_Mapper; Prefix : in String); type Element_Context is record Parent : Tag_Node_Access; Text : Boolean; end record; type Element_Context_Access is access all Element_Context; type Element_Context_Array is array (Natural range <>) of aliased Element_Context; type Element_Context_Array_Access is access all Element_Context_Array; type Text_State is (NO_CONTENT, HAS_CONTENT, PARSE_EXPR); type Xhtml_Reader is new Sax.Readers.Reader with record Locator : Sax.Locators.Locator; Root : Tag_Node_Access; Text : Text_Tag_Node_Access; Current : Element_Context_Access; ELContext : EL.Contexts.ELContext_Access; Functions : aliased NS_Function_Mapper; Context : aliased EL.Contexts.Default.Default_Context; Stack : Element_Context_Array_Access; Stack_Pos : Natural := 0; -- The line and file information. Line : Line_Info; State : Text_State := NO_CONTENT; Default_State : Text_State := NO_CONTENT; -- Current expression buffer (See Collect_Expression) Expr_Buffer : Unbounded_String; -- Some pending white spaces to append to the current text. Spaces : Unbounded_String; -- When not empty, the 'xmlns' attribute to insert in the element. The XML Sax parser -- notifies us about 'xmlns' attributes through the Start_Prefix_Mapping operation. -- When the default namespace with empty prefix is found, we have to add the corresponding -- attribute in Start_Element so that it is written in the facelet tree. Add_NS : Unbounded_String; -- 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; end ASF.Views.Nodes.Reader;
----------------------------------------------------------------------- -- asf -- XHTML Reader -- Copyright (C) 2009, 2010, 2011, 2012, 2013, 2015 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Sax.Exceptions; with Sax.Locators; with Sax.Readers; with Sax.Attributes; with Unicode.CES; with Input_Sources; with EL.Contexts; with EL.Contexts.Default; with ASF.Factory; private with EL.Functions; private with Util.Strings.Maps; package ASF.Views.Nodes.Reader is Parsing_Error : exception; type Xhtml_Reader is new Sax.Readers.Reader with private; overriding procedure Warning (Handler : in out Xhtml_Reader; Except : in Sax.Exceptions.Sax_Parse_Exception'Class); overriding procedure Error (Handler : in out Xhtml_Reader; Except : in Sax.Exceptions.Sax_Parse_Exception'Class); overriding procedure Fatal_Error (Handler : in out Xhtml_Reader; Except : in Sax.Exceptions.Sax_Parse_Exception'Class); overriding procedure Set_Document_Locator (Handler : in out Xhtml_Reader; Loc : in out Sax.Locators.Locator); overriding procedure Start_Document (Handler : in out Xhtml_Reader); overriding procedure End_Document (Handler : in out Xhtml_Reader); overriding procedure Start_Prefix_Mapping (Handler : in out Xhtml_Reader; Prefix : in Unicode.CES.Byte_Sequence; URI : in Unicode.CES.Byte_Sequence); overriding procedure End_Prefix_Mapping (Handler : in out Xhtml_Reader; Prefix : in Unicode.CES.Byte_Sequence); overriding procedure Start_Element (Handler : in out Xhtml_Reader; Namespace_URI : in Unicode.CES.Byte_Sequence := ""; Local_Name : in Unicode.CES.Byte_Sequence := ""; Qname : in Unicode.CES.Byte_Sequence := ""; Atts : in Sax.Attributes.Attributes'Class); overriding procedure End_Element (Handler : in out Xhtml_Reader; Namespace_URI : in Unicode.CES.Byte_Sequence := ""; Local_Name : in Unicode.CES.Byte_Sequence := ""; Qname : in Unicode.CES.Byte_Sequence := ""); overriding procedure Characters (Handler : in out Xhtml_Reader; Ch : in Unicode.CES.Byte_Sequence); overriding procedure Ignorable_Whitespace (Handler : in out Xhtml_Reader; Ch : in Unicode.CES.Byte_Sequence); overriding procedure Processing_Instruction (Handler : in out Xhtml_Reader; Target : in Unicode.CES.Byte_Sequence; Data : in Unicode.CES.Byte_Sequence); overriding procedure Skipped_Entity (Handler : in out Xhtml_Reader; Name : in Unicode.CES.Byte_Sequence); overriding procedure Start_Cdata (Handler : in out Xhtml_Reader); overriding procedure End_Cdata (Handler : in out Xhtml_Reader); overriding function Resolve_Entity (Handler : Xhtml_Reader; Public_Id : Unicode.CES.Byte_Sequence; System_Id : Unicode.CES.Byte_Sequence) return Input_Sources.Input_Source_Access; overriding procedure Start_DTD (Handler : in out Xhtml_Reader; Name : Unicode.CES.Byte_Sequence; Public_Id : Unicode.CES.Byte_Sequence := ""; System_Id : Unicode.CES.Byte_Sequence := ""); -- Get the root node that was created upon parsing of the XHTML file. function Get_Root (Reader : Xhtml_Reader) return Tag_Node_Access; -- Set the XHTML reader to ignore or not the white spaces. -- When set to True, the ignorable white spaces will not be kept. procedure Set_Ignore_White_Spaces (Reader : in out Xhtml_Reader; Value : in Boolean); -- Set the XHTML reader to escape or not the unknown tags. -- When set to True, the tags which are not recognized will be -- emitted as a raw text component and they will be escaped using -- the XML escape rules. procedure Set_Escape_Unknown_Tags (Reader : in out Xhtml_Reader; Value : in Boolean); -- Set the XHTML reader to ignore empty lines. procedure Set_Ignore_Empty_Lines (Reader : in out Xhtml_Reader; Value : in Boolean); -- Parse an XML stream, and calls the appropriate SAX callbacks for each -- event. -- This is not re-entrant: you can not call Parse with the same Parser -- argument in one of the SAX callbacks. This has undefined behavior. procedure Parse (Parser : in out Xhtml_Reader; Name : in ASF.Views.File_Info_Access; Input : in out Input_Sources.Input_Source'Class; Factory : access ASF.Factory.Component_Factory; Context : in EL.Contexts.ELContext_Access); private -- Collect the text for an EL expression. The EL expression starts -- with either '#{' or with '${' and ends with the matching '}'. -- If the <b>Value</b> string does not contain the whole EL experssion -- the <b>Expr_Buffer</b> stored in the reader is used to collect -- that expression. procedure Collect_Expression (Handler : in out Xhtml_Reader); -- Collect the raw-text in a buffer. The text must be flushed -- when a new element is started or when an exiting element is closed. procedure Collect_Text (Handler : in out Xhtml_Reader; Value : in Unicode.CES.Byte_Sequence); use EL.Functions; -- use ASF.Components.Factory; package NS_Mapping renames Util.Strings.Maps; -- Skip indicates the number of frames to skip in the saved locations -- stack type NS_Function_Mapper is new Function_Mapper with record Mapping : NS_Mapping.Map; Mapper : Function_Mapper_Access; Factory : access ASF.Factory.Component_Factory; end record; -- Find the function knowing its name. overriding function Get_Function (Mapper : NS_Function_Mapper; Namespace : String; Name : String) return Function_Access; -- Bind a name to a function in the given namespace. overriding procedure Set_Function (Mapper : in out NS_Function_Mapper; Namespace : in String; Name : in String; Func : in Function_Access); -- Find the create function in bound to the name in the given namespace. -- Returns null if no such binding exist. function Find (Mapper : in NS_Function_Mapper; Namespace : in String; Name : in String) return ASF.Views.Nodes.Binding_Access; procedure Set_Namespace (Mapper : in out NS_Function_Mapper; Prefix : in String; URI : in String); -- Remove the namespace prefix binding. procedure Remove_Namespace (Mapper : in out NS_Function_Mapper; Prefix : in String); type Element_Context is record Parent : Tag_Node_Access; Text : Boolean; end record; type Element_Context_Access is access all Element_Context; type Element_Context_Array is array (Natural range <>) of aliased Element_Context; type Element_Context_Array_Access is access all Element_Context_Array; type Text_State is (NO_CONTENT, HAS_CONTENT, PARSE_EXPR); type Xhtml_Reader is new Sax.Readers.Reader with record Locator : Sax.Locators.Locator; Root : Tag_Node_Access; Text : Text_Tag_Node_Access; Current : Element_Context_Access; ELContext : EL.Contexts.ELContext_Access; Functions : aliased NS_Function_Mapper; Context : aliased EL.Contexts.Default.Default_Context; Stack : Element_Context_Array_Access; Stack_Pos : Natural := 0; -- The line and file information. Line : Line_Info; State : Text_State := NO_CONTENT; Default_State : Text_State := NO_CONTENT; -- Current expression buffer (See Collect_Expression) Expr_Buffer : Unbounded_String; -- Some pending white spaces to append to the current text. Spaces : Unbounded_String; -- When not empty, the 'xmlns' attribute to insert in the element. The XML Sax parser -- notifies us about 'xmlns' attributes through the Start_Prefix_Mapping operation. -- When the default namespace with empty prefix is found, we have to add the corresponding -- attribute in Start_Element so that it is written in the facelet tree. Add_NS : Unbounded_String; -- 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; end ASF.Views.Nodes.Reader;
Declare the Parsing_Error exception
Declare the Parsing_Error exception
Ada
apache-2.0
stcarrez/ada-asf,stcarrez/ada-asf,stcarrez/ada-asf
7f7d84211a4c734815ba7e02dafeaa2a849cbe80
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. It allows to protect an URL by defining permissions that must be granted -- for a user to get access to the URL. A typical example is a web server that has a set of -- administration pages, these pages should be accessed by users having some admin permission. -- -- === 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: -- -- <policy-rules> -- <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> -- ... -- </policy-rules> -- -- 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>. -- The first permission that is granted gives access to the URL. -- -- === Checking for permission === -- To check a URL permission, you must declare a <tt>URL_Permission</tt> object with the URL. -- -- URL : constant String := ...; -- Perm : constant Policies.URLs.URL_Permission (URL'Length) -- := URL_Permission '(Len => URI'Length, URL => URL); -- -- Then, we can check the permission: -- -- Result : Boolean := Security.Contexts.Has_Permission (Perm); -- package Security.Policies.URLs is NAME : constant String := "URL-Policy"; package P_URL is new Security.Permissions.Definition ("url"); -- ------------------------------ -- URL Permission -- ------------------------------ -- Represents a permission to access a given URL. type URL_Permission (Len : Natural) is new Permissions.Permission (P_URL.Permission) with record URL : 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 URL_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); -- 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; 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; Id : Natural := 0; Permissions : Util.Beans.Objects.Vectors.Vector; Patterns : Util.Beans.Objects.Vectors.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; with Security.Contexts; -- == URL Security Policy == -- The <tt>Security.Policies.Urls</tt> implements a security policy intended to be used -- in web servers. It allows to protect an URL by defining permissions that must be granted -- for a user to get access to the URL. A typical example is a web server that has a set of -- administration pages, these pages should be accessed by users having some admin permission. -- -- === 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: -- -- <policy-rules> -- <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> -- ... -- </policy-rules> -- -- 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>. -- The first permission that is granted gives access to the URL. -- -- === Checking for permission === -- To check a URL permission, you must declare a <tt>URL_Permission</tt> object with the URL. -- -- URL : constant String := ...; -- Perm : constant Policies.URLs.URL_Permission (URL'Length) -- := URL_Permission '(Len => URI'Length, URL => URL); -- -- Then, we can check the permission: -- -- Result : Boolean := Security.Contexts.Has_Permission (Perm); -- package Security.Policies.URLs is NAME : constant String := "URL-Policy"; package P_URL is new Security.Permissions.Definition ("url"); -- ------------------------------ -- URL Permission -- ------------------------------ -- Represents a permission to access a given URL. type URL_Permission (Len : Natural) is new Permissions.Permission (P_URL.Permission) with record URL : 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 Contexts.Security_Context'Class; Permission : in URL_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); -- 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; 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; Id : Natural := 0; Permissions : Util.Beans.Objects.Vectors.Vector; Patterns : Util.Beans.Objects.Vectors.Vector; end record; end Security.Policies.URLs;
Change Has_Permission to get a Security Context class as parameter
Change Has_Permission to get a Security Context class as parameter
Ada
apache-2.0
stcarrez/ada-security
47d513c5369dd2d29ac1c9ffbcc055d50c37c525
src/sys/encoders/util-encoders-aes.ads
src/sys/encoders/util-encoders-aes.ads
----------------------------------------------------------------------- -- util-encoders-aes -- AES encryption and decryption -- 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 Ada.Streams; with Interfaces; private with Ada.Finalization; -- The <b>Util.Encodes.SHA1</b> package generates SHA-1 hash according to -- RFC3174 or [FIPS-180-1]. package Util.Encoders.AES is use type Ada.Streams.Stream_Element_Offset; type AES_Mode is (ECB, CBC, PCBC, CFB, OFB, CTR); type Key_Type is private; -- ------------------------------ -- ------------------------------ subtype Block_Type is Ada.Streams.Stream_Element_Array (1 .. 16); subtype AES_128_Key is Ada.Streams.Stream_Element_Array (1 .. 16); subtype AES_192_Key is Ada.Streams.Stream_Element_Array (1 .. 24); subtype AES_256_Key is Ada.Streams.Stream_Element_Array (1 .. 32); type Word_Block_Type is array (1 .. 4) of Interfaces.Unsigned_32; procedure Set_Encrypt_Key (Key : out Key_Type; Data : in Ada.Streams.Stream_Element_Array) with Pre => Data'Length = 16 or Data'Length = 24 or Data'Length = 32; procedure Set_Decrypt_Key (Key : out Key_Type; Data : in Ada.Streams.Stream_Element_Array); procedure Encrypt (Input : in Block_Type; Output : out Block_Type; Key : in Key_Type); procedure Encrypt (Input : in Word_Block_Type; Output : out Word_Block_Type; Key : in Key_Type); procedure Encrypt (Input : in Ada.Streams.Stream_Element_Array; Output : out Ada.Streams.Stream_Element_Array; Last : out Ada.Streams.Stream_Element_Offset; Key : in Key_Type); procedure Decrypt (Input : in Block_Type; Output : out Block_Type; Key : in Key_Type); procedure Decrypt (Input : in Word_Block_Type; Output : out Word_Block_Type; Key : in Key_Type); type Cipher is tagged limited private; -- Set the encryption initialization vector before starting the encryption. procedure Set_IV (E : in out Cipher; IV : in Word_Block_Type); -- ------------------------------ -- AES encoder -- ------------------------------ -- This <b>Encoder</b> translates the (binary) input stream into -- an SHA1 hexadecimal stream. The encoding alphabet is: 0123456789ABCDEF. type Encoder is new Cipher and Util.Encoders.Transformer with private; -- Set the encryption key to use. procedure Set_Key (E : in out Encoder; Data : in Ada.Streams.Stream_Element_Array; Mode : in AES_Mode := CBC); -- Encodes the binary input stream represented by <b>Data</b> into -- an SHA-1 hash output stream <b>Into</b>. -- -- If the transformer does not have enough room to write the result, -- it must return in <b>Encoded</b> the index of the last encoded -- position in the <b>Data</b> stream. -- -- The transformer returns in <b>Last</b> the last valid position -- in the output stream <b>Into</b>. -- -- The <b>Encoding_Error</b> exception is raised if the input -- stream cannot be transformed. overriding procedure Transform (E : in out Encoder; Data : in Ada.Streams.Stream_Element_Array; Into : out Ada.Streams.Stream_Element_Array; Last : out Ada.Streams.Stream_Element_Offset; Encoded : out Ada.Streams.Stream_Element_Offset); -- Finish encoding the input array. overriding procedure Finish (E : in out Encoder; Into : in out Ada.Streams.Stream_Element_Array; Last : in out Ada.Streams.Stream_Element_Offset) with Pre => Into'Length >= Block_Type'Length, Post => Last = Into'First - 1 or Last = Into'First + Block_Type'Length; -- ------------------------------ -- AES encoder -- ------------------------------ -- This <b>Encoder</b> translates the (binary) input stream into -- an SHA1 hexadecimal stream. The encoding alphabet is: 0123456789ABCDEF. type Decoder is new Cipher and Util.Encoders.Transformer with private; -- Set the decryption key to use. procedure Set_Key (E : in out Decoder; Data : in Ada.Streams.Stream_Element_Array; Mode : in AES_Mode := CBC); -- Encodes the binary input stream represented by <b>Data</b> into -- an SHA-1 hash output stream <b>Into</b>. -- -- If the transformer does not have enough room to write the result, -- it must return in <b>Encoded</b> the index of the last encoded -- position in the <b>Data</b> stream. -- -- The transformer returns in <b>Last</b> the last valid position -- in the output stream <b>Into</b>. -- -- The <b>Encoding_Error</b> exception is raised if the input -- stream cannot be transformed. overriding procedure Transform (E : in out Decoder; Data : in Ada.Streams.Stream_Element_Array; Into : out Ada.Streams.Stream_Element_Array; Last : out Ada.Streams.Stream_Element_Offset; Encoded : out Ada.Streams.Stream_Element_Offset); -- Finish encoding the input array. overriding procedure Finish (E : in out Decoder; Into : in out Ada.Streams.Stream_Element_Array; Last : in out Ada.Streams.Stream_Element_Offset); private use Interfaces; type Block_Key is array (0 .. 59) of Unsigned_32; type Key_Type is record Key : Block_Key := (others => 0); Rounds : Natural := 0; end record; type Cipher is limited new Ada.Finalization.Limited_Controlled with record IV : Word_Block_Type; Key : Key_Type; Mode : AES_Mode := CBC; Data_Count : Ada.Streams.Stream_Element_Offset := 0; Data : Block_Type; end record; overriding procedure Finalize (Object : in out Cipher); type Encoder is new Cipher and Util.Encoders.Transformer with null record; type Decoder is new Cipher and Util.Encoders.Transformer with null record; end Util.Encoders.AES;
----------------------------------------------------------------------- -- util-encoders-aes -- AES encryption and decryption -- 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 Interfaces; private with Ada.Finalization; -- The <b>Util.Encodes.SHA1</b> package generates SHA-1 hash according to -- RFC3174 or [FIPS-180-1]. package Util.Encoders.AES is type AES_Mode is (ECB, CBC, PCBC, CFB, OFB, CTR); type Key_Type is private; -- ------------------------------ -- ------------------------------ subtype Block_Type is Ada.Streams.Stream_Element_Array (1 .. 16); AES_128_Length : constant := 16; AES_192_Length : constant := 24; AES_256_Length : constant := 32; subtype AES_128_Key is Ada.Streams.Stream_Element_Array (1 .. 16); subtype AES_192_Key is Ada.Streams.Stream_Element_Array (1 .. 24); subtype AES_256_Key is Ada.Streams.Stream_Element_Array (1 .. 32); type Word_Block_Type is array (1 .. 4) of Interfaces.Unsigned_32; procedure Set_Encrypt_Key (Key : out Key_Type; Data : in Secret_Key) with Pre => Data.Length = 16 or Data.Length = 24 or Data.Length = 32; procedure Set_Decrypt_Key (Key : out Key_Type; Data : in Secret_Key) with Pre => Data.Length = 16 or Data.Length = 24 or Data.Length = 32; procedure Encrypt (Input : in Block_Type; Output : out Block_Type; Key : in Key_Type); procedure Encrypt (Input : in Word_Block_Type; Output : out Word_Block_Type; Key : in Key_Type); procedure Encrypt (Input : in Ada.Streams.Stream_Element_Array; Output : out Ada.Streams.Stream_Element_Array; Last : out Ada.Streams.Stream_Element_Offset; Key : in Key_Type); procedure Decrypt (Input : in Block_Type; Output : out Block_Type; Key : in Key_Type); procedure Decrypt (Input : in Word_Block_Type; Output : out Word_Block_Type; Key : in Key_Type); type Cipher is tagged limited private; -- Set the encryption initialization vector before starting the encryption. procedure Set_IV (E : in out Cipher; IV : in Word_Block_Type); -- ------------------------------ -- AES encoder -- ------------------------------ -- This <b>Encoder</b> translates the (binary) input stream into -- an SHA1 hexadecimal stream. The encoding alphabet is: 0123456789ABCDEF. type Encoder is new Cipher and Util.Encoders.Transformer with private; -- Set the encryption key to use. procedure Set_Key (E : in out Encoder; Data : in Secret_Key; Mode : in AES_Mode := CBC); -- Encodes the binary input stream represented by <b>Data</b> into -- an SHA-1 hash output stream <b>Into</b>. -- -- If the transformer does not have enough room to write the result, -- it must return in <b>Encoded</b> the index of the last encoded -- position in the <b>Data</b> stream. -- -- The transformer returns in <b>Last</b> the last valid position -- in the output stream <b>Into</b>. -- -- The <b>Encoding_Error</b> exception is raised if the input -- stream cannot be transformed. overriding procedure Transform (E : in out Encoder; Data : in Ada.Streams.Stream_Element_Array; Into : out Ada.Streams.Stream_Element_Array; Last : out Ada.Streams.Stream_Element_Offset; Encoded : out Ada.Streams.Stream_Element_Offset); -- Finish encoding the input array. overriding procedure Finish (E : in out Encoder; Into : in out Ada.Streams.Stream_Element_Array; Last : in out Ada.Streams.Stream_Element_Offset) with Pre => Into'Length >= Block_Type'Length, Post => Last = Into'First - 1 or Last = Into'First + Block_Type'Length; -- ------------------------------ -- AES encoder -- ------------------------------ -- This <b>Encoder</b> translates the (binary) input stream into -- an SHA1 hexadecimal stream. The encoding alphabet is: 0123456789ABCDEF. type Decoder is new Cipher and Util.Encoders.Transformer with private; -- Set the decryption key to use. procedure Set_Key (E : in out Decoder; Data : in Secret_Key; Mode : in AES_Mode := CBC); -- Encodes the binary input stream represented by <b>Data</b> into -- an SHA-1 hash output stream <b>Into</b>. -- -- If the transformer does not have enough room to write the result, -- it must return in <b>Encoded</b> the index of the last encoded -- position in the <b>Data</b> stream. -- -- The transformer returns in <b>Last</b> the last valid position -- in the output stream <b>Into</b>. -- -- The <b>Encoding_Error</b> exception is raised if the input -- stream cannot be transformed. overriding procedure Transform (E : in out Decoder; Data : in Ada.Streams.Stream_Element_Array; Into : out Ada.Streams.Stream_Element_Array; Last : out Ada.Streams.Stream_Element_Offset; Encoded : out Ada.Streams.Stream_Element_Offset); -- Finish encoding the input array. overriding procedure Finish (E : in out Decoder; Into : in out Ada.Streams.Stream_Element_Array; Last : in out Ada.Streams.Stream_Element_Offset); private use Interfaces; type Block_Key is array (0 .. 59) of Unsigned_32; type Key_Type is record Key : Block_Key := (others => 0); Rounds : Natural := 0; end record; type Cipher is limited new Ada.Finalization.Limited_Controlled with record IV : Word_Block_Type; Key : Key_Type; Mode : AES_Mode := CBC; Data_Count : Ada.Streams.Stream_Element_Offset := 0; Data : Block_Type; end record; overriding procedure Finalize (Object : in out Cipher); type Encoder is new Cipher and Util.Encoders.Transformer with null record; type Decoder is new Cipher and Util.Encoders.Transformer with null record; end Util.Encoders.AES;
Use Secret_Key type for AES secret keys
Use Secret_Key type for AES secret keys
Ada
apache-2.0
stcarrez/ada-util,stcarrez/ada-util
c83c2ca40c474c9db44fdb99b719b8c418a612e1
mat/src/events/mat-events-targets.ads
mat/src/events/mat-events-targets.ads
----------------------------------------------------------------------- -- mat-events-targets - Events received and collected from a target -- Copyright (C) 2014 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Containers.Ordered_Maps; with Ada.Containers.Vectors; with Util.Concurrent.Counters; with MAT.Frames; package MAT.Events.Targets is Not_Found : exception; type Event_Type is mod 16; type Probe_Index_Type is mod 16; type Event_Id_Type is new Natural; type Probe_Event_Type is record Id : Event_Id_Type; Event : MAT.Types.Uint16; Index : Probe_Index_Type; Time : MAT.Types.Target_Time; Thread : MAT.Types.Target_Thread_Ref; Frame : MAT.Frames.Frame_Type; Addr : MAT.Types.Target_Addr; Size : MAT.Types.Target_Size; Old_Addr : MAT.Types.Target_Addr; end record; subtype Target_Event is Probe_Event_Type; package Target_Event_Vectors is new Ada.Containers.Vectors (Positive, Target_Event); subtype Target_Event_Vector is Target_Event_Vectors.Vector; subtype Target_Event_Cursor is Target_Event_Vectors.Cursor; type Target_Events is tagged limited private; type Target_Events_Access is access all Target_Events'Class; -- Add the event in the list of events and increment the event counter. procedure Insert (Target : in out Target_Events; Event : in Probe_Event_Type); procedure Get_Events (Target : in out Target_Events; Start : in MAT.Types.Target_Time; Finish : in MAT.Types.Target_Time; Into : in out Target_Event_Vector); -- Get the start and finish time for the events that have been received. procedure Get_Time_Range (Target : in out Target_Events; Start : out MAT.Types.Target_Time; Finish : out MAT.Types.Target_Time); -- Get the probe event with the given allocated unique id. function Get_Event (Target : in Target_Events; Id : in Event_Id_Type) return Probe_Event_Type; -- Get the current event counter. function Get_Event_Counter (Target : in Target_Events) return Integer; private EVENT_BLOCK_SIZE : constant Event_Id_Type := 1024; type Probe_Event_Array is array (1 .. EVENT_BLOCK_SIZE) of Probe_Event_Type; type Event_Block is record Start : MAT.Types.Target_Time; Finish : MAT.Types.Target_Time; Count : Event_Id_Type := 0; Events : Probe_Event_Array; end record; type Event_Block_Access is access all Event_Block; use type MAT.Types.Target_Time; package Event_Maps is new Ada.Containers.Ordered_Maps (Key_Type => MAT.Types.Target_Time, Element_Type => Event_Block_Access); subtype Event_Map is Event_Maps.Map; subtype Event_Cursor is Event_Maps.Cursor; package Event_Id_Maps is new Ada.Containers.Ordered_Maps (Key_Type => Event_Id_Type, Element_Type => Event_Block_Access); subtype Event_Id_Map is Event_Id_Maps.Map; subtype Event_Id_Cursor is Event_Id_Maps.Cursor; protected type Event_Collector is -- Add the event in the list of events. procedure Insert (Event : in Probe_Event_Type); procedure Get_Events (Start : in MAT.Types.Target_Time; Finish : in MAT.Types.Target_Time; Into : in out Target_Event_Vector); -- Get the start and finish time for the events that have been received. procedure Get_Time_Range (Start : out MAT.Types.Target_Time; Finish : out MAT.Types.Target_Time); -- Get the probe event with the given allocated unique id. function Get_Event (Id : in Event_Id_Type) return Probe_Event_Type; private Current : Event_Block_Access := null; Events : Event_Map; Ids : Event_Id_Map; Last_Id : Event_Id_Type := 0; end Event_Collector; type Target_Events is tagged limited record Events : Event_Collector; Event_Count : Util.Concurrent.Counters.Counter; end record; end MAT.Events.Targets;
----------------------------------------------------------------------- -- mat-events-targets - Events received and collected from a target -- Copyright (C) 2014 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Containers.Ordered_Maps; with Ada.Containers.Vectors; with Util.Concurrent.Counters; with MAT.Frames; package MAT.Events.Targets is Not_Found : exception; type Event_Type is mod 16; type Probe_Index_Type is mod 16; type Event_Id_Type is new Natural; type Probe_Event_Type is record Id : Event_Id_Type; Event : MAT.Types.Uint16; Index : Probe_Index_Type; Time : MAT.Types.Target_Tick_Ref; Thread : MAT.Types.Target_Thread_Ref; Frame : MAT.Frames.Frame_Type; Addr : MAT.Types.Target_Addr; Size : MAT.Types.Target_Size; Old_Addr : MAT.Types.Target_Addr; end record; subtype Target_Event is Probe_Event_Type; package Target_Event_Vectors is new Ada.Containers.Vectors (Positive, Target_Event); subtype Target_Event_Vector is Target_Event_Vectors.Vector; subtype Target_Event_Cursor is Target_Event_Vectors.Cursor; type Target_Events is tagged limited private; type Target_Events_Access is access all Target_Events'Class; -- Add the event in the list of events and increment the event counter. procedure Insert (Target : in out Target_Events; Event : in Probe_Event_Type); procedure Get_Events (Target : in out Target_Events; Start : in MAT.Types.Target_Time; Finish : in MAT.Types.Target_Time; Into : in out Target_Event_Vector); -- Get the start and finish time for the events that have been received. procedure Get_Time_Range (Target : in out Target_Events; Start : out MAT.Types.Target_Time; Finish : out MAT.Types.Target_Time); -- Get the probe event with the given allocated unique id. function Get_Event (Target : in Target_Events; Id : in Event_Id_Type) return Probe_Event_Type; -- Get the current event counter. function Get_Event_Counter (Target : in Target_Events) return Integer; private EVENT_BLOCK_SIZE : constant Event_Id_Type := 1024; type Probe_Event_Array is array (1 .. EVENT_BLOCK_SIZE) of Probe_Event_Type; type Event_Block is record Start : MAT.Types.Target_Time; Finish : MAT.Types.Target_Time; Count : Event_Id_Type := 0; Events : Probe_Event_Array; end record; type Event_Block_Access is access all Event_Block; use type MAT.Types.Target_Time; package Event_Maps is new Ada.Containers.Ordered_Maps (Key_Type => MAT.Types.Target_Time, Element_Type => Event_Block_Access); subtype Event_Map is Event_Maps.Map; subtype Event_Cursor is Event_Maps.Cursor; package Event_Id_Maps is new Ada.Containers.Ordered_Maps (Key_Type => Event_Id_Type, Element_Type => Event_Block_Access); subtype Event_Id_Map is Event_Id_Maps.Map; subtype Event_Id_Cursor is Event_Id_Maps.Cursor; protected type Event_Collector is -- Add the event in the list of events. procedure Insert (Event : in Probe_Event_Type); procedure Get_Events (Start : in MAT.Types.Target_Time; Finish : in MAT.Types.Target_Time; Into : in out Target_Event_Vector); -- Get the start and finish time for the events that have been received. procedure Get_Time_Range (Start : out MAT.Types.Target_Time; Finish : out MAT.Types.Target_Time); -- Get the probe event with the given allocated unique id. function Get_Event (Id : in Event_Id_Type) return Probe_Event_Type; private Current : Event_Block_Access := null; Events : Event_Map; Ids : Event_Id_Map; Last_Id : Event_Id_Type := 0; end Event_Collector; type Target_Events is tagged limited record Events : Event_Collector; Event_Count : Util.Concurrent.Counters.Counter; end record; end MAT.Events.Targets;
Use MAT.Types.Target_Tick_Ref for the event time
Use MAT.Types.Target_Tick_Ref for the event time
Ada
apache-2.0
stcarrez/mat,stcarrez/mat,stcarrez/mat
016208ccb6d9636388edda62680bbb8a407cd0ba
awa/src/awa-commands-drivers.adb
awa/src/awa-commands-drivers.adb
----------------------------------------------------------------------- -- awa-commands-drivers -- Driver for AWA commands for server or admin tool -- 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 Ada.Command_Line; with Servlet.Core; package body AWA.Commands.Drivers is use Ada.Strings.Unbounded; use AWA.Applications; function "-" (Message : in String) return String is (Message); Help_Command : aliased AWA.Commands.Drivers.Help_Command_Type; -- ------------------------------ -- Setup the command before parsing the arguments and executing it. -- ------------------------------ overriding procedure Setup (Command : in out Command_Type; Config : in out GNAT.Command_Line.Command_Line_Configuration; Context : in out Context_Type) is begin GC.Set_Usage (Config => Config, Usage => Command.Get_Name & " [arguments]", Help => Command.Get_Description); AWA.Commands.Setup_Command (Config, Context); end Setup; -- ------------------------------ -- Write the help associated with the command. -- ------------------------------ overriding procedure Help (Command : in out Command_Type; Name : in String; Context : in out Context_Type) is pragma Unreferenced (Command, Context); begin null; end Help; -- ------------------------------ -- Setup the command before parsing the arguments and executing it. -- ------------------------------ overriding procedure Setup (Command : in out Application_Command_Type; Config : in out GNAT.Command_Line.Command_Line_Configuration; Context : in out Context_Type) is begin GC.Define_Switch (Config => Config, Output => Command.Application_Name'Access, Switch => "-a:", Long_Switch => "--application=", Argument => "NAME", Help => -("Defines the name or URI of the application")); AWA.Commands.Setup_Command (Config, Context); end Setup; function Is_Application (Command : in Application_Command_Type; URI : in String) return Boolean is begin return Command.Application_Name.all = URI; end Is_Application; overriding procedure Execute (Command : in out Application_Command_Type; Name : in String; Args : in Argument_List'Class; Context : in out Context_Type) is pragma Unreferenced (Name); procedure Find (URI : in String; App : in Servlet.Core.Servlet_Registry_Access); Count : Natural := 0; Selected : Application_Access; App_Name : Unbounded_String; procedure Find (URI : in String; App : in Servlet.Core.Servlet_Registry_Access) is begin if App.all in Application'Class then if Command.Is_Application (URI) then App_Name := To_Unbounded_String (URI (URI'First + 1 .. URI'Last)); Selected := Application'Class (App.all)'Unchecked_Access; Count := Count + 1; elsif Command.Application_Name'Length = 0 then App_Name := To_Unbounded_String (URI (URI'First + 1 .. URI'Last)); Selected := Application'Class (App.all)'Unchecked_Access; Count := Count + 1; end if; end if; end Find; begin WS.Iterate (Find'Access); if Count /= 1 then Context.Console.Notice (N_ERROR, -("No application found")); return; end if; Configure (Selected.all, To_String (App_Name), Context); Application_Command_Type'Class (Command).Execute (Selected.all, Args, Context); end Execute; -- ------------------------------ -- Print the command usage. -- ------------------------------ procedure Usage (Args : in Argument_List'Class; Context : in out Context_Type; Name : in String := "") is begin GC.Display_Help (Context.Command_Config); if Name'Length > 0 then Driver.Usage (Args, Context, Name); end if; Ada.Command_Line.Set_Exit_Status (Ada.Command_Line.Failure); end Usage; -- ------------------------------ -- Execute the command with its arguments. -- ------------------------------ procedure Execute (Name : in String; Args : in Argument_List'Class; Context : in out Context_Type) is begin Driver.Execute (Name, Args, Context); end Execute; procedure Run (Context : in out Context_Type; Arguments : out Util.Commands.Dynamic_Argument_List) is begin GC.Getopt (Config => Context.Command_Config); Util.Commands.Parsers.GNAT_Parser.Get_Arguments (Arguments, GC.Get_Argument); if Context.Config_File'Length = 0 then Context.Load_Configuration (Driver_Name & ".properties"); else Context.Load_Configuration (Context.Config_File.all); end if; if Context.Debug or Context.Verbose or Context.Dump then Configure_Logs (Root => Context.Global_Config.Get ("log4j.rootCategory", ""), Debug => Context.Debug, Dump => Context.Dump, Verbose => Context.Verbose); end if; declare Cmd_Name : constant String := Arguments.Get_Command_Name; begin if Cmd_Name'Length = 0 then Context.Console.Notice (N_ERROR, -("Missing command name to execute.")); Usage (Arguments, Context); Ada.Command_Line.Set_Exit_Status (Ada.Command_Line.Failure); return; end if; Execute (Cmd_Name, Arguments, Context); exception when GNAT.Command_Line.Invalid_Parameter => Context.Console.Notice (N_ERROR, -("Missing option parameter")); raise Error; end; end Run; begin Driver.Add_Command ("help", -("print some help"), Help_Command'Access); end AWA.Commands.Drivers;
----------------------------------------------------------------------- -- awa-commands-drivers -- Driver for AWA commands for server or admin tool -- 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 Ada.Command_Line; with Servlet.Core; package body AWA.Commands.Drivers is use Ada.Strings.Unbounded; use AWA.Applications; function "-" (Message : in String) return String is (Message); Help_Command : aliased AWA.Commands.Drivers.Help_Command_Type; -- ------------------------------ -- Setup the command before parsing the arguments and executing it. -- ------------------------------ overriding procedure Setup (Command : in out Command_Type; Config : in out GNAT.Command_Line.Command_Line_Configuration; Context : in out Context_Type) is begin GC.Set_Usage (Config => Config, Usage => Command.Get_Name & " [arguments]", Help => Command.Get_Description); AWA.Commands.Setup_Command (Config, Context); end Setup; -- ------------------------------ -- Write the help associated with the command. -- ------------------------------ overriding procedure Help (Command : in out Command_Type; Name : in String; Context : in out Context_Type) is pragma Unreferenced (Command, Context); begin null; end Help; -- ------------------------------ -- Setup the command before parsing the arguments and executing it. -- ------------------------------ overriding procedure Setup (Command : in out Application_Command_Type; Config : in out GNAT.Command_Line.Command_Line_Configuration; Context : in out Context_Type) is begin GC.Define_Switch (Config => Config, Output => Command.Application_Name'Access, Switch => "-a:", Long_Switch => "--application=", Argument => "NAME", Help => -("Defines the name or URI of the application")); AWA.Commands.Setup_Command (Config, Context); end Setup; function Is_Application (Command : in Application_Command_Type; URI : in String) return Boolean is begin return Command.Application_Name.all = URI; end Is_Application; overriding procedure Execute (Command : in out Application_Command_Type; Name : in String; Args : in Argument_List'Class; Context : in out Context_Type) is pragma Unreferenced (Name); procedure Find (URI : in String; App : in Servlet.Core.Servlet_Registry_Access); Count : Natural := 0; Selected : Application_Access; App_Name : Unbounded_String; procedure Find (URI : in String; App : in Servlet.Core.Servlet_Registry_Access) is begin if App.all in Application'Class then if Command.Is_Application (URI) then App_Name := To_Unbounded_String (URI (URI'First + 1 .. URI'Last)); Selected := Application'Class (App.all)'Unchecked_Access; Count := Count + 1; elsif Command.Application_Name'Length = 0 then App_Name := To_Unbounded_String (URI (URI'First + 1 .. URI'Last)); Selected := Application'Class (App.all)'Unchecked_Access; Count := Count + 1; end if; end if; end Find; begin WS.Iterate (Find'Access); if Count /= 1 then Context.Console.Notice (N_ERROR, -("No application found")); return; end if; Configure (Selected.all, To_String (App_Name), Context); Application_Command_Type'Class (Command).Execute (Selected.all, Args, Context); end Execute; -- ------------------------------ -- Print the command usage. -- ------------------------------ procedure Usage (Args : in Argument_List'Class; Context : in out Context_Type; Name : in String := "") is begin GC.Display_Help (Context.Command_Config); if Name'Length > 0 then Driver.Usage (Args, Context, Name); end if; Ada.Command_Line.Set_Exit_Status (Ada.Command_Line.Failure); end Usage; -- ------------------------------ -- Execute the command with its arguments. -- ------------------------------ procedure Execute (Name : in String; Args : in Argument_List'Class; Context : in out Context_Type) is begin Driver.Execute (Name, Args, Context); end Execute; -- ------------------------------ -- Get the server configuration file path. -- ------------------------------ function Get_Configuration_Path (Context : in out Context_Type) return String is begin if Context.Config_File'Length = 0 then return Driver_Name & ".properties"; else return Context.Config_File.all; end if; end Get_Configuration_Path; procedure Run (Context : in out Context_Type; Arguments : out Util.Commands.Dynamic_Argument_List) is begin GC.Getopt (Config => Context.Command_Config); Util.Commands.Parsers.GNAT_Parser.Get_Arguments (Arguments, GC.Get_Argument); Context.Load_Configuration (Get_Configuration_Path (Context)); if Context.Debug or Context.Verbose or Context.Dump then Configure_Logs (Root => Context.Global_Config.Get ("log4j.rootCategory", ""), Debug => Context.Debug, Dump => Context.Dump, Verbose => Context.Verbose); end if; declare Cmd_Name : constant String := Arguments.Get_Command_Name; begin if Cmd_Name'Length = 0 then Context.Console.Notice (N_ERROR, -("Missing command name to execute.")); Usage (Arguments, Context); Ada.Command_Line.Set_Exit_Status (Ada.Command_Line.Failure); return; end if; Execute (Cmd_Name, Arguments, Context); exception when GNAT.Command_Line.Invalid_Parameter => Context.Console.Notice (N_ERROR, -("Missing option parameter")); raise Error; end; end Run; begin Driver.Add_Command ("help", -("print some help"), Help_Command'Access); end AWA.Commands.Drivers;
Implement Get_Configuration_Path to return the path of the server configuration
Implement Get_Configuration_Path to return the path of the server configuration
Ada
apache-2.0
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
c0676265d2010b36bafa523596bed163a6f3aa9d
src/ado-drivers-connections.adb
src/ado-drivers-connections.adb
----------------------------------------------------------------------- -- 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.Log.Loggers; with Util.Systems.DLLs; with System; with Ada.Strings.Fixed; with Ada.Containers.Doubly_Linked_Lists; with Ada.Exceptions; package body ADO.Drivers.Connections is use Ada.Strings.Fixed; Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("ADO.Drivers.Connections"); -- Load the database driver. procedure Load_Driver (Name : in String); -- ------------------------------ -- Set the connection URL to connect to the database. -- The driver connection is a string of the form: -- -- driver://[host][:port]/[database][?property1][=value1]... -- -- If the string is invalid or if the driver cannot be found, -- the Connection_Error exception is raised. -- ------------------------------ procedure Set_Connection (Controller : in out Configuration; URI : in String) is Pos, Pos2, Slash_Pos, Next : Natural; begin Log.Info ("Set connection URI: {0}", URI); Controller.URI := To_Unbounded_String (URI); Pos := Index (URI, "://"); if Pos <= 1 then Log.Error ("Invalid connection URI: {0}", URI); raise Connection_Error with "Invalid URI: '" & URI & "'"; end if; Controller.Driver := Get_Driver (URI (URI'First .. Pos - 1)); if Controller.Driver = null then Log.Error ("No driver found for connection URI: {0}", URI); raise Connection_Error with "Driver '" & URI (URI'First .. Pos - 1) & "' not found"; end if; Pos := Pos + 3; Slash_Pos := Index (URI, "/", Pos); if Slash_Pos < Pos then Log.Error ("Invalid connection URI: {0}", URI); raise Connection_Error with "Invalid connection URI: '" & URI & "'"; end if; -- Extract the server and port. Pos2 := Index (URI, ":", Pos); if Pos2 > Pos then Controller.Server := To_Unbounded_String (URI (Pos .. Pos2 - 1)); Controller.Port := Integer'Value (URI (Pos2 + 1 .. Slash_Pos - 1)); else Controller.Port := 0; Controller.Server := To_Unbounded_String (URI (Pos .. Slash_Pos - 1)); end if; -- Extract the database name. Pos := Index (URI, "?", Slash_Pos); if Pos - 1 > Slash_Pos + 1 then Controller.Database := To_Unbounded_String (URI (Slash_Pos + 1 .. Pos - 1)); elsif Pos = 0 and Slash_Pos + 1 < URI'Last then Controller.Database := To_Unbounded_String (URI (Slash_Pos + 1 .. URI'Last)); else Controller.Database := Null_Unbounded_String; end if; -- Parse the optional properties if Pos > Slash_Pos then while Pos < URI'Last loop Pos2 := Index (URI, "=", Pos + 1); if Pos2 > Pos then Next := Index (URI, "&", Pos2 + 1); if Next > 0 then Controller.Properties.Set (URI (Pos + 1 .. Pos2 - 1), URI (Pos2 + 1 .. Next - 1)); Pos := Next; else Controller.Properties.Set (URI (Pos + 1 .. Pos2 - 1), URI (Pos2 + 1 .. URI'Last)); Pos := URI'Last; end if; else Controller.Properties.Set (URI (Pos + 1 .. URI'Last), ""); Pos := URI'Last; end if; end loop; end if; end Set_Connection; -- ------------------------------ -- Set a property on the datasource for the driver. -- The driver can retrieve the property to configure and open -- the database connection. -- ------------------------------ procedure Set_Property (Controller : in out Configuration; Name : in String; Value : in String) is begin Controller.Properties.Set (Name, Value); end Set_Property; -- ------------------------------ -- Get a property from the datasource configuration. -- If the property does not exist, an empty string is returned. -- ------------------------------ function Get_Property (Controller : in Configuration; Name : in String) return String is begin return Controller.Properties.Get (Name, ""); end Get_Property; -- ------------------------------ -- Get the server hostname. -- ------------------------------ function Get_Server (Controller : in Configuration) return String is begin return To_String (Controller.Server); end Get_Server; -- ------------------------------ -- Get the server port. -- ------------------------------ function Get_Port (Controller : in Configuration) return Integer is begin return Controller.Port; end Get_Port; -- ------------------------------ -- Get the database name. -- ------------------------------ function Get_Database (Controller : in Configuration) return String is begin return To_String (Controller.Database); end Get_Database; -- ------------------------------ -- Create a new connection using the configuration parameters. -- ------------------------------ procedure Create_Connection (Config : in Configuration'Class; Result : out Database_Connection_Access) is begin if Config.Driver = null then Log.Error ("No driver found for connection {0}", To_String (Config.URI)); raise Connection_Error with "Data source is not initialized: driver not found"; end if; Config.Driver.Create_Connection (Config, Result); Log.Info ("Created connection to '{0}' -> {1}", Config.URI, Result.Ident); exception when others => Log.Info ("Failed to create connection to '{0}'", Config.URI); raise; end Create_Connection; package Driver_List is new Ada.Containers.Doubly_Linked_Lists (Element_Type => Driver_Access); Next_Index : Driver_Index := 1; Drivers : Driver_List.List; -- ------------------------------ -- Get the driver unique index. -- ------------------------------ function Get_Driver_Index (D : in Driver) return Driver_Index is begin return D.Index; end Get_Driver_Index; -- ------------------------------ -- Get the driver name. -- ------------------------------ function Get_Driver_Name (D : in Driver) return String is begin return D.Name.all; end Get_Driver_Name; -- ------------------------------ -- Register a database driver. -- ------------------------------ procedure Register (Driver : in Driver_Access) is begin Log.Info ("Register driver {0}", Driver.Name.all); Driver_List.Prepend (Container => Drivers, New_Item => Driver); Driver.Index := Next_Index; Next_Index := Next_Index + 1; end Register; -- ------------------------------ -- Load the database driver. -- ------------------------------ procedure Load_Driver (Name : in String) is Lib : constant String := "libada_ado_" & Name & Util.Systems.DLLs.Extension; Symbol : constant String := "ado__drivers__connections__" & Name & "__initialize"; Handle : Util.Systems.DLLs.Handle; Addr : System.Address; begin Log.Info ("Loading driver {0}", Lib); Handle := Util.Systems.DLLs.Load (Lib); Addr := Util.Systems.DLLs.Get_Symbol (Handle, Symbol); declare procedure Init; pragma Import (C, Init); for Init'Address use Addr; begin Init; end; exception when Util.Systems.DLLs.Not_Found => Log.Error ("Driver for {0} was loaded but does not define the initialization symbol", Name); when E : Util.Systems.DLLs.Load_Error => Log.Error ("Driver for {0} was not found: {1}", Name, Ada.Exceptions.Exception_Message (E)); end Load_Driver; -- ------------------------------ -- Get a database driver given its name. -- ------------------------------ function Get_Driver (Name : in String) return Driver_Access is begin Log.Info ("Get driver {0}", Name); for Retry in 0 .. 1 loop if Retry > 0 then Load_Driver (Name); end if; declare Iter : Driver_List.Cursor := Driver_List.First (Drivers); begin while Driver_List.Has_Element (Iter) loop declare D : constant Driver_Access := Driver_List.Element (Iter); begin if Name = D.Name.all then return D; end if; end; Driver_List.Next (Iter); end loop; end; end loop; return null; end Get_Driver; end ADO.Drivers.Connections;
----------------------------------------------------------------------- -- ADO Drivers -- Database Drivers -- Copyright (C) 2010, 2011, 2012, 2013, 2015 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Log.Loggers; with Util.Systems.DLLs; with System; with Ada.Strings.Fixed; with Ada.Containers.Doubly_Linked_Lists; with Ada.Exceptions; package body ADO.Drivers.Connections is use Ada.Strings.Fixed; Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("ADO.Drivers.Connections"); -- Load the database driver. procedure Load_Driver (Name : in String); -- ------------------------------ -- Set the connection URL to connect to the database. -- The driver connection is a string of the form: -- -- driver://[host][:port]/[database][?property1][=value1]... -- -- If the string is invalid or if the driver cannot be found, -- the Connection_Error exception is raised. -- ------------------------------ procedure Set_Connection (Controller : in out Configuration; URI : in String) is Pos, Pos2, Slash_Pos, Next : Natural; begin Log.Info ("Set connection URI: {0}", URI); Controller.URI := To_Unbounded_String (URI); Pos := Index (URI, "://"); if Pos <= 1 then Log.Error ("Invalid connection URI: {0}", URI); raise Connection_Error with "Invalid URI: '" & URI & "'"; end if; Controller.Driver := Get_Driver (URI (URI'First .. Pos - 1)); if Controller.Driver = null then Log.Error ("No driver found for connection URI: {0}", URI); raise Connection_Error with "Driver '" & URI (URI'First .. Pos - 1) & "' not found"; end if; Pos := Pos + 3; Slash_Pos := Index (URI, "/", Pos); if Slash_Pos < Pos then Log.Error ("Invalid connection URI: {0}", URI); raise Connection_Error with "Invalid connection URI: '" & URI & "'"; end if; -- Extract the server and port. Pos2 := Index (URI, ":", Pos); if Pos2 >= Pos then Controller.Server := To_Unbounded_String (URI (Pos .. Pos2 - 1)); begin Controller.Port := Integer'Value (URI (Pos2 + 1 .. Slash_Pos - 1)); exception when Constraint_Error => Log.Error ("Invalid port in connection URI: {0}", URI); raise Connection_Error with "Invalid port in connection URI: '" & URI & "'"; end; else Controller.Port := 0; Controller.Server := To_Unbounded_String (URI (Pos .. Slash_Pos - 1)); end if; -- Extract the database name. Pos := Index (URI, "?", Slash_Pos); if Pos - 1 > Slash_Pos + 1 then Controller.Database := To_Unbounded_String (URI (Slash_Pos + 1 .. Pos - 1)); elsif Pos = 0 and Slash_Pos + 1 < URI'Last then Controller.Database := To_Unbounded_String (URI (Slash_Pos + 1 .. URI'Last)); else Controller.Database := Null_Unbounded_String; end if; -- Parse the optional properties if Pos > Slash_Pos then while Pos < URI'Last loop Pos2 := Index (URI, "=", Pos + 1); if Pos2 > Pos then Next := Index (URI, "&", Pos2 + 1); if Next > 0 then Controller.Properties.Set (URI (Pos + 1 .. Pos2 - 1), URI (Pos2 + 1 .. Next - 1)); Pos := Next; else Controller.Properties.Set (URI (Pos + 1 .. Pos2 - 1), URI (Pos2 + 1 .. URI'Last)); Pos := URI'Last; end if; else Controller.Properties.Set (URI (Pos + 1 .. URI'Last), ""); Pos := URI'Last; end if; end loop; end if; end Set_Connection; -- ------------------------------ -- Set a property on the datasource for the driver. -- The driver can retrieve the property to configure and open -- the database connection. -- ------------------------------ procedure Set_Property (Controller : in out Configuration; Name : in String; Value : in String) is begin Controller.Properties.Set (Name, Value); end Set_Property; -- ------------------------------ -- Get a property from the datasource configuration. -- If the property does not exist, an empty string is returned. -- ------------------------------ function Get_Property (Controller : in Configuration; Name : in String) return String is begin return Controller.Properties.Get (Name, ""); end Get_Property; -- ------------------------------ -- Get the server hostname. -- ------------------------------ function Get_Server (Controller : in Configuration) return String is begin return To_String (Controller.Server); end Get_Server; -- ------------------------------ -- Get the server port. -- ------------------------------ function Get_Port (Controller : in Configuration) return Integer is begin return Controller.Port; end Get_Port; -- ------------------------------ -- Get the database name. -- ------------------------------ function Get_Database (Controller : in Configuration) return String is begin return To_String (Controller.Database); end Get_Database; -- ------------------------------ -- Create a new connection using the configuration parameters. -- ------------------------------ procedure Create_Connection (Config : in Configuration'Class; Result : out Database_Connection_Access) is begin if Config.Driver = null then Log.Error ("No driver found for connection {0}", To_String (Config.URI)); raise Connection_Error with "Data source is not initialized: driver not found"; end if; Config.Driver.Create_Connection (Config, Result); Log.Info ("Created connection to '{0}' -> {1}", Config.URI, Result.Ident); exception when others => Log.Info ("Failed to create connection to '{0}'", Config.URI); raise; end Create_Connection; package Driver_List is new Ada.Containers.Doubly_Linked_Lists (Element_Type => Driver_Access); Next_Index : Driver_Index := 1; Drivers : Driver_List.List; -- ------------------------------ -- Get the driver unique index. -- ------------------------------ function Get_Driver_Index (D : in Driver) return Driver_Index is begin return D.Index; end Get_Driver_Index; -- ------------------------------ -- Get the driver name. -- ------------------------------ function Get_Driver_Name (D : in Driver) return String is begin return D.Name.all; end Get_Driver_Name; -- ------------------------------ -- Register a database driver. -- ------------------------------ procedure Register (Driver : in Driver_Access) is begin Log.Info ("Register driver {0}", Driver.Name.all); Driver_List.Prepend (Container => Drivers, New_Item => Driver); Driver.Index := Next_Index; Next_Index := Next_Index + 1; end Register; -- ------------------------------ -- Load the database driver. -- ------------------------------ procedure Load_Driver (Name : in String) is Lib : constant String := "libada_ado_" & Name & Util.Systems.DLLs.Extension; Symbol : constant String := "ado__drivers__connections__" & Name & "__initialize"; Handle : Util.Systems.DLLs.Handle; Addr : System.Address; begin Log.Info ("Loading driver {0}", Lib); Handle := Util.Systems.DLLs.Load (Lib); Addr := Util.Systems.DLLs.Get_Symbol (Handle, Symbol); declare procedure Init; pragma Import (C, Init); for Init'Address use Addr; begin Init; end; exception when Util.Systems.DLLs.Not_Found => Log.Error ("Driver for {0} was loaded but does not define the initialization symbol", Name); when E : Util.Systems.DLLs.Load_Error => Log.Error ("Driver for {0} was not found: {1}", Name, Ada.Exceptions.Exception_Message (E)); end Load_Driver; -- ------------------------------ -- Get a database driver given its name. -- ------------------------------ function Get_Driver (Name : in String) return Driver_Access is begin Log.Info ("Get driver {0}", Name); for Retry in 0 .. 1 loop if Retry > 0 then Load_Driver (Name); end if; declare Iter : Driver_List.Cursor := Driver_List.First (Drivers); begin while Driver_List.Has_Element (Iter) loop declare D : constant Driver_Access := Driver_List.Element (Iter); begin if Name = D.Name.all then return D; end if; end; Driver_List.Next (Iter); end loop; end; end loop; return null; end Get_Driver; end ADO.Drivers.Connections;
Raise a Connection_Error exception if the connection port is invalid
Raise a Connection_Error exception if the connection port is invalid
Ada
apache-2.0
stcarrez/ada-ado
5a25d11845e7bb4818f61320e3af870134d18ad8
awa/plugins/awa-tags/regtests/awa-tags-modules-tests.adb
awa/plugins/awa-tags/regtests/awa-tags-modules-tests.adb
----------------------------------------------------------------------- -- awa-tags-modules-tests -- Unit tests for tags module -- Copyright (C) 2013 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Test_Caller; with Util.Beans.Basic; with Util.Beans.Objects; with Security.Contexts; with AWA.Users.Models; with AWA.Services.Contexts; with AWA.Tests.Helpers.Users; with AWA.Tags.Beans; package body AWA.Tags.Modules.Tests is use Util.Tests; use ADO; package Caller is new Util.Test_Caller (Test, "Tags.Modules"); procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is begin Caller.Add_Test (Suite, "Test AWA.Tags.Modules.Add_Tag", Test_Add_Tag'Access); Caller.Add_Test (Suite, "Test AWA.Tags.Modules.Remove_Tag", Test_Remove_Tag'Access); end Add_Tests; function Create_Tag_List_Bean (Module : in Tag_Module_Access) return AWA.Tags.Beans.Tag_List_Bean_Access is Bean : Util.Beans.Basic.Readonly_Bean_Access := AWA.Tags.Beans.Create_Tag_List_Bean (Module); begin return AWA.Tags.Beans.Tag_List_Bean'Class (Bean.all)'Access; end Create_Tag_List_Bean; -- ------------------------------ -- Test tag creation. -- ------------------------------ procedure Test_Add_Tag (T : in out Test) is Sec_Ctx : Security.Contexts.Security_Context; Context : AWA.Services.Contexts.Service_Context; begin AWA.Tests.Helpers.Users.Login (Context, Sec_Ctx, "[email protected]"); declare Tag_Manager : constant Tag_Module_Access := Get_Tag_Module; User : constant AWA.Users.Models.User_Ref := Context.Get_User; List : AWA.Tags.Beans.Tag_List_Bean_Access; Cleanup : Util.Beans.Objects.Object; begin T.Assert (Tag_Manager /= null, "There is no tag module"); List := Create_Tag_List_Bean (Tag_Manager); Cleanup := Util.Beans.Objects.To_Object (List.all'Access); List.Set_Value ("entity_type", Util.Beans.Objects.To_Object (String '("awa_user"))); -- Create a tag. Tag_Manager.Add_Tag (User.Get_Id, "awa_user", "workspaces-create", "user-tag"); Tag_Manager.Add_Tag (User.Get_Id, "awa_user", "workspaces-create", "user-tag"); -- Load the list. List.Load_Tags (User.Get_Id); Util.Tests.Assert_Equals (T, 1, Integer (List.Get_Count), "Invalid number of tags"); end; end Test_Add_Tag; -- ------------------------------ -- Test tag removal. -- ------------------------------ procedure Test_Remove_Tag (T : in out Test) is Sec_Ctx : Security.Contexts.Security_Context; Context : AWA.Services.Contexts.Service_Context; begin AWA.Tests.Helpers.Users.Login (Context, Sec_Ctx, "[email protected]"); declare Tag_Manager : constant Tag_Module_Access := Get_Tag_Module; User : constant AWA.Users.Models.User_Ref := Context.Get_User; List : AWA.Tags.Beans.Tag_List_Bean_Access; Cleanup : Util.Beans.Objects.Object; begin T.Assert (Tag_Manager /= null, "There is no tag module"); List := Create_Tag_List_Bean (Tag_Manager); Cleanup := Util.Beans.Objects.To_Object (List.all'Access); List.Set_Value ("entity_type", Util.Beans.Objects.To_Object (String '("awa_user"))); Tag_Manager.Add_Tag (User.Get_Id, "awa_user", "workspaces-create", "user-tag-1"); Tag_Manager.Add_Tag (User.Get_Id, "awa_user", "workspaces-create", "user-tag-2"); Tag_Manager.Add_Tag (User.Get_Id, "awa_user", "workspaces-create", "user-tag-3"); Tag_Manager.Remove_Tag (User.Get_Id, "awa_user", "workspaces-create", "user-tag-2"); Tag_Manager.Remove_Tag (User.Get_Id, "awa_user", "workspaces-create", "user-tag-1"); -- Load the list. List.Load_Tags (User.Get_Id); Util.Tests.Assert_Equals (T, 2, Integer (List.Get_Count), "Invalid number of tags"); end; end Test_Remove_Tag; end AWA.Tags.Modules.Tests;
----------------------------------------------------------------------- -- awa-tags-modules-tests -- Unit tests for tags module -- Copyright (C) 2013 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Test_Caller; with Util.Beans.Basic; with Util.Beans.Objects; with Security.Contexts; with AWA.Users.Models; with AWA.Services.Contexts; with AWA.Tests.Helpers.Users; with AWA.Tags.Beans; package body AWA.Tags.Modules.Tests is use Util.Tests; use ADO; package Caller is new Util.Test_Caller (Test, "Tags.Modules"); procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is begin Caller.Add_Test (Suite, "Test AWA.Tags.Modules.Add_Tag", Test_Add_Tag'Access); Caller.Add_Test (Suite, "Test AWA.Tags.Modules.Remove_Tag", Test_Remove_Tag'Access); end Add_Tests; function Create_Tag_List_Bean (Module : in Tag_Module_Access) return AWA.Tags.Beans.Tag_List_Bean_Access is Bean : Util.Beans.Basic.Readonly_Bean_Access := AWA.Tags.Beans.Create_Tag_List_Bean (Module); begin return AWA.Tags.Beans.Tag_List_Bean'Class (Bean.all)'Access; end Create_Tag_List_Bean; -- ------------------------------ -- Test tag creation. -- ------------------------------ procedure Test_Add_Tag (T : in out Test) is Sec_Ctx : Security.Contexts.Security_Context; Context : AWA.Services.Contexts.Service_Context; begin AWA.Tests.Helpers.Users.Login (Context, Sec_Ctx, "[email protected]"); declare Tag_Manager : constant Tag_Module_Access := Get_Tag_Module; User : constant AWA.Users.Models.User_Ref := Context.Get_User; List : AWA.Tags.Beans.Tag_List_Bean_Access; Cleanup : Util.Beans.Objects.Object; begin T.Assert (Tag_Manager /= null, "There is no tag module"); List := Create_Tag_List_Bean (Tag_Manager); Cleanup := Util.Beans.Objects.To_Object (List.all'Access); List.Set_Value ("entity_type", Util.Beans.Objects.To_Object (String '("awa_user"))); -- Create a tag. Tag_Manager.Add_Tag (User.Get_Id, "awa_user", "workspaces-create", "user-tag"); Tag_Manager.Add_Tag (User.Get_Id, "awa_user", "workspaces-create", "user-tag"); -- Load the list. List.Load_Tags (Tag_Manager.Get_Session, User.Get_Id); Util.Tests.Assert_Equals (T, 1, Integer (List.Get_Count), "Invalid number of tags"); end; end Test_Add_Tag; -- ------------------------------ -- Test tag removal. -- ------------------------------ procedure Test_Remove_Tag (T : in out Test) is Sec_Ctx : Security.Contexts.Security_Context; Context : AWA.Services.Contexts.Service_Context; begin AWA.Tests.Helpers.Users.Login (Context, Sec_Ctx, "[email protected]"); declare Tag_Manager : constant Tag_Module_Access := Get_Tag_Module; User : constant AWA.Users.Models.User_Ref := Context.Get_User; List : AWA.Tags.Beans.Tag_List_Bean_Access; Cleanup : Util.Beans.Objects.Object; begin T.Assert (Tag_Manager /= null, "There is no tag module"); List := Create_Tag_List_Bean (Tag_Manager); Cleanup := Util.Beans.Objects.To_Object (List.all'Access); List.Set_Value ("entity_type", Util.Beans.Objects.To_Object (String '("awa_user"))); Tag_Manager.Add_Tag (User.Get_Id, "awa_user", "workspaces-create", "user-tag-1"); Tag_Manager.Add_Tag (User.Get_Id, "awa_user", "workspaces-create", "user-tag-2"); Tag_Manager.Add_Tag (User.Get_Id, "awa_user", "workspaces-create", "user-tag-3"); Tag_Manager.Remove_Tag (User.Get_Id, "awa_user", "workspaces-create", "user-tag-2"); Tag_Manager.Remove_Tag (User.Get_Id, "awa_user", "workspaces-create", "user-tag-1"); -- Load the list. List.Load_Tags (Tag_Manager.Get_Session, User.Get_Id); Util.Tests.Assert_Equals (T, 2, Integer (List.Get_Count), "Invalid number of tags"); end; end Test_Remove_Tag; end AWA.Tags.Modules.Tests;
Update the unit test
Update the unit test
Ada
apache-2.0
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
7531282d92f5dafaad758900653038fe37735bb8
regtests/ado-datasets-tests.adb
regtests/ado-datasets-tests.adb
----------------------------------------------------------------------- -- ado-datasets-tests -- Test executing queries and using datasets -- Copyright (C) 2013, 2014 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Test_Caller; with Util.Properties; with Regtests.Simple.Model; with ADO.Queries.Loaders; package body ADO.Datasets.Tests is package Caller is new Util.Test_Caller (Test, "ADO.Datasets"); package User_List_Query_File is new ADO.Queries.Loaders.File (Path => "regtests/files/user-list.xml", Sha1 => ""); package User_List_Query is new ADO.Queries.Loaders.Query (Name => "user-list", File => User_List_Query_File.File'Access); package User_List_Count_Query is new ADO.Queries.Loaders.Query (Name => "user-list-count", File => User_List_Query_File.File'Access); procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is begin Caller.Add_Test (Suite, "Test ADO.Datasets.List (from <sql>)", Test_List'Access); Caller.Add_Test (Suite, "Test ADO.Datasets.Get_Count (from <sql>)", Test_Count'Access); Caller.Add_Test (Suite, "Test ADO.Datasets.Get_Count (from <sql-count>)", Test_Count_Query'Access); end Add_Tests; procedure Test_List (T : in out Test) is DB : ADO.Sessions.Master_Session := Regtests.Get_Master_Database; Query : ADO.Queries.Context; Count : Natural; Data : ADO.Datasets.Dataset; Props : constant Util.Properties.Manager := Util.Tests.Get_Properties; begin -- Configure the XML query loader. ADO.Queries.Loaders.Initialize (Props.Get ("ado.queries.paths", ".;db"), Props.Get ("ado.queries.load", "false") = "true"); Query.Set_Count_Query (User_List_Query.Query'Access); Query.Bind_Param ("filter", String '("test-list")); Count := ADO.Datasets.Get_Count (DB, Query); for I in 1 .. 100 loop declare User : Regtests.Simple.Model.User_Ref; begin User.Set_Name ("John " & Integer'Image (I)); User.Set_Select_Name ("test-list"); User.Set_Value (ADO.Identifier (I)); User.Save (DB); end; end loop; DB.Commit; Query.Set_Query (User_List_Query.Query'Access); ADO.Datasets.List (Data, DB, Query); Util.Tests.Assert_Equals (T, 100 + Count, Data.Get_Count, "Invalid dataset size"); end Test_List; procedure Test_Count (T : in out Test) is DB : constant ADO.Sessions.Master_Session := Regtests.Get_Master_Database; Query : ADO.Queries.Context; Count : Natural; Props : constant Util.Properties.Manager := Util.Tests.Get_Properties; begin -- Configure the XML query loader. ADO.Queries.Loaders.Initialize (Props.Get ("ado.queries.paths", ".;db"), Props.Get ("ado.queries.load", "false") = "true"); Query.Set_Query (User_List_Count_Query.Query'Access); Count := ADO.Datasets.Get_Count (DB, Query); T.Assert (Count > 0, "The ADO.Datasets.Get_Count query should return a positive count"); end Test_Count; procedure Test_Count_Query (T : in out Test) is DB : constant ADO.Sessions.Master_Session := Regtests.Get_Master_Database; Query : ADO.Queries.Context; Count : Natural; Props : constant Util.Properties.Manager := Util.Tests.Get_Properties; begin -- Configure the XML query loader. ADO.Queries.Loaders.Initialize (Props.Get ("ado.queries.paths", ".;db"), Props.Get ("ado.queries.load", "false") = "true"); Query.Set_Count_Query (User_List_Query.Query'Access); Query.Bind_Param ("filter", String '("test-list")); Count := ADO.Datasets.Get_Count (DB, Query); T.Assert (Count > 0, "The ADO.Datasets.Get_Count query should return a positive count"); end Test_Count_Query; end ADO.Datasets.Tests;
----------------------------------------------------------------------- -- ado-datasets-tests -- Test executing queries and using datasets -- Copyright (C) 2013, 2014, 2015 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Test_Caller; with Util.Properties; with Regtests.Simple.Model; with Regtests.Statements.Model; with ADO.Queries.Loaders; package body ADO.Datasets.Tests is package Caller is new Util.Test_Caller (Test, "ADO.Datasets"); package User_List_Query_File is new ADO.Queries.Loaders.File (Path => "regtests/files/user-list.xml", Sha1 => ""); package User_List_Query is new ADO.Queries.Loaders.Query (Name => "user-list", File => User_List_Query_File.File'Access); package User_List_Count_Query is new ADO.Queries.Loaders.Query (Name => "user-list-count", File => User_List_Query_File.File'Access); procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is begin Caller.Add_Test (Suite, "Test ADO.Datasets.List (from <sql>)", Test_List'Access); Caller.Add_Test (Suite, "Test ADO.Datasets.Get_Count (from <sql>)", Test_Count'Access); Caller.Add_Test (Suite, "Test ADO.Datasets.Get_Count (from <sql-count>)", Test_Count_Query'Access); Caller.Add_Test (Suite, "Test ADO.Datasets.List (<sql> with null)", Test_List_Nullable'Access); end Add_Tests; procedure Test_List (T : in out Test) is DB : ADO.Sessions.Master_Session := Regtests.Get_Master_Database; Query : ADO.Queries.Context; Count : Natural; Data : ADO.Datasets.Dataset; Props : constant Util.Properties.Manager := Util.Tests.Get_Properties; begin -- Configure the XML query loader. ADO.Queries.Loaders.Initialize (Props.Get ("ado.queries.paths", ".;db"), Props.Get ("ado.queries.load", "false") = "true"); Query.Set_Count_Query (User_List_Query.Query'Access); Query.Bind_Param ("filter", String '("test-list")); Count := ADO.Datasets.Get_Count (DB, Query); for I in 1 .. 100 loop declare User : Regtests.Simple.Model.User_Ref; begin User.Set_Name ("John " & Integer'Image (I)); User.Set_Select_Name ("test-list"); User.Set_Value (ADO.Identifier (I)); User.Save (DB); end; end loop; DB.Commit; Query.Set_Query (User_List_Query.Query'Access); ADO.Datasets.List (Data, DB, Query); Util.Tests.Assert_Equals (T, 100 + Count, Data.Get_Count, "Invalid dataset size"); end Test_List; -- ------------------------------ -- Test dataset lists with null columns. -- ------------------------------ procedure Test_List_Nullable (T : in out Test) is DB : ADO.Sessions.Master_Session := Regtests.Get_Master_Database; Query : ADO.Queries.Context; Count : Natural; Data : ADO.Datasets.Dataset; begin Query.Set_SQL ("SELECT COUNT(*) FROM test_nullable_table"); Count := ADO.Datasets.Get_Count (DB, Query); for I in 1 .. 100 loop declare Item : Regtests.Statements.Model.Nullable_Table_Ref; begin Item.Set_Bool_Value (False); if (I mod 2) = 0 then Item.Set_Int_Value (ADO.Nullable_Integer '(123, False)); end if; if (I mod 4) = 0 then Item.Set_Time_Value (ADO.Nullable_Time '(Value => Ada.Calendar.Clock, Is_Null => False)); end if; Item.Save (DB); end; end loop; DB.Commit; Query.Set_SQL ("SELECT * FROM test_nullable_table"); ADO.Datasets.List (Data, DB, Query); Util.Tests.Assert_Equals (T, 100 + Count, Data.Get_Count, "Invalid dataset size"); end Test_List_Nullable; procedure Test_Count (T : in out Test) is DB : constant ADO.Sessions.Master_Session := Regtests.Get_Master_Database; Query : ADO.Queries.Context; Count : Natural; Props : constant Util.Properties.Manager := Util.Tests.Get_Properties; begin -- Configure the XML query loader. ADO.Queries.Loaders.Initialize (Props.Get ("ado.queries.paths", ".;db"), Props.Get ("ado.queries.load", "false") = "true"); Query.Set_Query (User_List_Count_Query.Query'Access); Count := ADO.Datasets.Get_Count (DB, Query); T.Assert (Count > 0, "The ADO.Datasets.Get_Count query should return a positive count"); end Test_Count; procedure Test_Count_Query (T : in out Test) is DB : constant ADO.Sessions.Master_Session := Regtests.Get_Master_Database; Query : ADO.Queries.Context; Count : Natural; Props : constant Util.Properties.Manager := Util.Tests.Get_Properties; begin -- Configure the XML query loader. ADO.Queries.Loaders.Initialize (Props.Get ("ado.queries.paths", ".;db"), Props.Get ("ado.queries.load", "false") = "true"); Query.Set_Count_Query (User_List_Query.Query'Access); Query.Bind_Param ("filter", String '("test-list")); Count := ADO.Datasets.Get_Count (DB, Query); T.Assert (Count > 0, "The ADO.Datasets.Get_Count query should return a positive count"); end Test_Count_Query; end ADO.Datasets.Tests;
Implement a new test to verify the datasets with null columns and different types (date, boolean, integer, strings)
Implement a new test to verify the datasets with null columns and different types (date, boolean, integer, strings)
Ada
apache-2.0
stcarrez/ada-ado
616c9844ccad6fcc35207feb63264673f0c647db
src/asf-components-widgets-factory.adb
src/asf-components-widgets-factory.adb
----------------------------------------------------------------------- -- widgets-factory -- Factory for widget Components -- Copyright (C) 2013 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with ASF.Views.Nodes; with ASF.Components.Base; with ASF.Components.Widgets.Inputs; package body ASF.Components.Widgets.Factory is use ASF.Components.Base; function Create_Input return UIComponent_Access; function Create_Complete return UIComponent_Access; -- ------------------------------ -- Create a UIInput component -- ------------------------------ function Create_Input return UIComponent_Access is begin return new ASF.Components.Widgets.Inputs.UIInput; end Create_Input; -- ------------------------------ -- Create a UIComplete component -- ------------------------------ function Create_Complete return UIComponent_Access is begin return new ASF.Components.Widgets.Inputs.UIComplete; end Create_Complete; use ASF.Views.Nodes; URI : aliased constant String := "http://code.google.com/p/ada-asf/widget"; AUTOCOMPLETE_TAG : aliased constant String := "autocomplete"; INPUT_TEXT_TAG : aliased constant String := "inputText"; Widget_Bindings : aliased constant ASF.Factory.Binding_Array := (1 => (Name => AUTOCOMPLETE_TAG'Access, Component => Create_Complete'Access, Tag => Create_Component_Node'Access), 2 => (Name => INPUT_TEXT_TAG'Access, Component => Create_Input'Access, Tag => Create_Component_Node'Access) ); Core_Factory : aliased constant ASF.Factory.Factory_Bindings := (URI => URI'Access, Bindings => Widget_Bindings'Access); -- ------------------------------ -- Get the widget component factory. -- ------------------------------ function Definition return ASF.Factory.Factory_Bindings_Access is begin return Core_Factory'Access; end Definition; end ASF.Components.Widgets.Factory;
----------------------------------------------------------------------- -- widgets-factory -- Factory for widget Components -- Copyright (C) 2013 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with ASF.Views.Nodes; with ASF.Components.Base; with ASF.Components.Widgets.Inputs; package body ASF.Components.Widgets.Factory is use ASF.Components.Base; function Create_Input return UIComponent_Access; function Create_Input_Date return UIComponent_Access; function Create_Complete return UIComponent_Access; -- ------------------------------ -- Create a UIInput component -- ------------------------------ function Create_Input return UIComponent_Access is begin return new ASF.Components.Widgets.Inputs.UIInput; end Create_Input; -- ------------------------------ -- Create a UIInput component -- ------------------------------ function Create_Input_Date return UIComponent_Access is begin return new ASF.Components.Widgets.Inputs.UIInputDate; end Create_Input_Date; -- ------------------------------ -- Create a UIComplete component -- ------------------------------ function Create_Complete return UIComponent_Access is begin return new ASF.Components.Widgets.Inputs.UIComplete; end Create_Complete; use ASF.Views.Nodes; URI : aliased constant String := "http://code.google.com/p/ada-asf/widget"; AUTOCOMPLETE_TAG : aliased constant String := "autocomplete"; INPUT_DATE_TAG : aliased constant String := "inputDate"; INPUT_TEXT_TAG : aliased constant String := "inputText"; Widget_Bindings : aliased constant ASF.Factory.Binding_Array := (1 => (Name => AUTOCOMPLETE_TAG'Access, Component => Create_Complete'Access, Tag => Create_Component_Node'Access), 2 => (Name => INPUT_DATE_TAG'Access, Component => Create_Input_Date'Access, Tag => Create_Component_Node'Access), 3 => (Name => INPUT_TEXT_TAG'Access, Component => Create_Input'Access, Tag => Create_Component_Node'Access) ); Core_Factory : aliased constant ASF.Factory.Factory_Bindings := (URI => URI'Access, Bindings => Widget_Bindings'Access); -- ------------------------------ -- Get the widget component factory. -- ------------------------------ function Definition return ASF.Factory.Factory_Bindings_Access is begin return Core_Factory'Access; end Definition; end ASF.Components.Widgets.Factory;
Add the inputDate component in the factory
Add the inputDate component in the factory
Ada
apache-2.0
stcarrez/ada-asf,stcarrez/ada-asf,stcarrez/ada-asf
3251d81853ba710291627d2f5e8a906e750b8dbb
src/util-strings-transforms.ads
src/util-strings-transforms.ads
----------------------------------------------------------------------- -- Util-texts -- Various Text Transformation Utilities -- Copyright (C) 2001, 2002, 2003, 2009, 2010 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Texts.Transforms; with Ada.Strings.Unbounded; with Ada.Characters.Handling; package Util.Strings.Transforms is pragma Preelaborate; use Ada.Strings.Unbounded; package TR is new Util.Texts.Transforms (Stream => Unbounded_String, Char => Character, Input => String, Put => Ada.Strings.Unbounded.Append, To_Upper => Ada.Characters.Handling.To_Upper, To_Lower => Ada.Characters.Handling.To_Lower, To_Input => Ada.Strings.Unbounded.To_String); -- Capitalize the string into the result stream. procedure Capitalize (Content : in String; Into : in out Unbounded_String) renames TR.Capitalize; function Capitalize (Content : String) return String renames TR.Capitalize; -- Translate the input string into an upper case string in the result stream. procedure To_Upper_Case (Content : in String; Into : in out Unbounded_String) renames TR.To_Upper_Case; function To_Upper_Case (Content : String) return String renames TR.To_Upper_Case; -- Translate the input string into a lower case string in the result stream. procedure To_Lower_Case (Content : in String; Into : in out Unbounded_String) renames TR.To_Lower_Case; function To_Lower_Case (Content : String) return String renames TR.To_Lower_Case; -- Write in the output stream the value as a \uNNNN encoding form. procedure To_Hex (Into : in out Unbounded_String; Value : in Character) renames TR.To_Hex; -- Escape the content into the result stream using the JavaScript -- escape rules. procedure Escape_Javascript (Content : in String; Into : in out Unbounded_String) renames TR.Escape_Java_Script; function Escape_Javascript (Content : String) return String renames TR.Escape_Java_Script; -- Escape the content into the result stream using the Java -- escape rules. procedure Escape_Java (Content : in String; Into : in out Unbounded_String) renames TR.Escape_Java; function Escape_Java (Content : String) return String renames TR.Escape_Java; -- Escape the content into the result stream using the XML -- escape rules: -- '<' -> '&lt;' -- '>' -> '&gt;' -- ''' -> '&apos;' -- '&' -> '&amp;' -- -> '&#nnn;' if Character'Pos >= 128 procedure Escape_Xml (Content : in String; Into : in out Unbounded_String) renames TR.Escape_Xml; function Escape_Xml (Content : String) return String renames TR.Escape_Xml; procedure Translate_Xml_Entity (Entity : in String; Into : in out Unbounded_String) renames TR.Translate_Xml_Entity; procedure Unescape_Xml (Content : in String; Translator : not null access procedure (Entity : in String; Into : in out Unbounded_String) := Translate_Xml_Entity'Access; Into : in out Unbounded_String) renames TR.Unescape_Xml; end Util.Strings.Transforms;
----------------------------------------------------------------------- -- Util-texts -- Various Text Transformation Utilities -- Copyright (C) 2001, 2002, 2003, 2009, 2010, 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.Texts.Transforms; with Ada.Strings.Unbounded; with Ada.Characters.Handling; package Util.Strings.Transforms is pragma Preelaborate; use Ada.Strings.Unbounded; package TR is new Util.Texts.Transforms (Stream => Unbounded_String, Char => Character, Input => String, Put => Ada.Strings.Unbounded.Append, To_Upper => Ada.Characters.Handling.To_Upper, To_Lower => Ada.Characters.Handling.To_Lower); -- Capitalize the string into the result stream. procedure Capitalize (Content : in String; Into : in out Unbounded_String) renames TR.Capitalize; function Capitalize (Content : String) return String renames TR.Capitalize; -- Translate the input string into an upper case string in the result stream. procedure To_Upper_Case (Content : in String; Into : in out Unbounded_String) renames TR.To_Upper_Case; function To_Upper_Case (Content : String) return String renames TR.To_Upper_Case; -- Translate the input string into a lower case string in the result stream. procedure To_Lower_Case (Content : in String; Into : in out Unbounded_String) renames TR.To_Lower_Case; function To_Lower_Case (Content : String) return String renames TR.To_Lower_Case; -- Write in the output stream the value as a \uNNNN encoding form. procedure To_Hex (Into : in out Unbounded_String; Value : in Character) renames TR.To_Hex; -- Escape the content into the result stream using the JavaScript -- escape rules. procedure Escape_Javascript (Content : in String; Into : in out Unbounded_String) renames TR.Escape_Java_Script; function Escape_Javascript (Content : String) return String; -- Escape the content into the result stream using the Java -- escape rules. procedure Escape_Java (Content : in String; Into : in out Unbounded_String) renames TR.Escape_Java; function Escape_Java (Content : String) return String; -- Escape the content into the result stream using the XML -- escape rules: -- '<' -> '&lt;' -- '>' -> '&gt;' -- ''' -> '&apos;' -- '&' -> '&amp;' -- -> '&#nnn;' if Character'Pos >= 128 procedure Escape_Xml (Content : in String; Into : in out Unbounded_String) renames TR.Escape_Xml; function Escape_Xml (Content : String) return String; procedure Translate_Xml_Entity (Entity : in String; Into : in out Unbounded_String) renames TR.Translate_Xml_Entity; procedure Unescape_Xml (Content : in String; Translator : not null access procedure (Entity : in String; Into : in out Unbounded_String) := Translate_Xml_Entity'Access; Into : in out Unbounded_String) renames TR.Unescape_Xml; end Util.Strings.Transforms;
Change Escape_Javascript, Escape_Java, Escape_Xml function to real function declaration (instead of renames)
Change Escape_Javascript, Escape_Java, Escape_Xml function to real function declaration (instead of renames)
Ada
apache-2.0
stcarrez/ada-util,stcarrez/ada-util
f9be2ec16867fd81e2f9ee12bde703a5ec755ab4
src/oto-alc.ads
src/oto-alc.ads
pragma License (Modified_GPL); ------------------------------------------------------------------------------ -- EMAIL: <[email protected]> -- -- License: Modified GNU GPLv3 or any later as published by Free Software -- -- Foundation (GMGPL, see COPYING file). -- -- -- -- Copyright © 2014 darkestkhan -- ------------------------------------------------------------------------------ -- This Program is Free Software: You can redistribute it and/or modify -- -- it under the terms of The GNU General Public License as published by -- -- the Free Software Foundation: either version 3 of the license, or -- -- (at your option) any later version. -- -- -- -- This Program is distributed in the hope that it will be useful, -- -- but WITHOUT ANY WARRANTY; without even the implied warranty of -- -- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -- -- GNU General Public License for more details. -- -- -- -- You should have received a copy of the GNU General Public License -- -- along with this program. If not, see <http://www.gnu.org/licenses/>. -- -- -- -- As a special exception, if other files instantiate generics from this -- -- unit, or you link this unit with other files to produce an executable, -- -- this unit does not by itself cause the resulting executable to be -- -- covered by the GNU General Public License. This exception does not -- -- however invalidate any other reasons why the executable file might be -- -- covered by the GNU Public License. -- ------------------------------------------------------------------------------ with System; with Oto.Binary; use Oto; package Oto.ALC is --------------------------------------------------------------------------- --------------- -- T Y P E S -- --------------- --------------------------------------------------------------------------- -- Due to the fact that only pointers to device and context are passed -- we ar going to use System.Address for them. subtype Context is System.Address; subtype Device is System.Address; subtype Bool is Binary.Byte; subtype Char is Binary.S_Byte; subtype Double is Long_Float; subtype Enum is Binary.S_Word; subtype Int is Integer; subtype Short is Binary.S_Short; subtype SizeI is Integer; subtype UByte is Binary.Byte; subtype UInt is Binary.Word; subtype UShort is Binary.Short; --------------------------------------------------------------------------- end OTO.ALC;
pragma License (Modified_GPL); ------------------------------------------------------------------------------ -- EMAIL: <[email protected]> -- -- License: Modified GNU GPLv3 or any later as published by Free Software -- -- Foundation (GMGPL, see COPYING file). -- -- -- -- Copyright © 2014 darkestkhan -- ------------------------------------------------------------------------------ -- This Program is Free Software: You can redistribute it and/or modify -- -- it under the terms of The GNU General Public License as published by -- -- the Free Software Foundation: either version 3 of the license, or -- -- (at your option) any later version. -- -- -- -- This Program is distributed in the hope that it will be useful, -- -- but WITHOUT ANY WARRANTY; without even the implied warranty of -- -- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -- -- GNU General Public License for more details. -- -- -- -- You should have received a copy of the GNU General Public License -- -- along with this program. If not, see <http://www.gnu.org/licenses/>. -- -- -- -- As a special exception, if other files instantiate generics from this -- -- unit, or you link this unit with other files to produce an executable, -- -- this unit does not by itself cause the resulting executable to be -- -- covered by the GNU General Public License. This exception does not -- -- however invalidate any other reasons why the executable file might be -- -- covered by the GNU Public License. -- ------------------------------------------------------------------------------ with System; with Oto.Binary; use Oto; package Oto.ALC is --------------------------------------------------------------------------- --------------- -- T Y P E S -- --------------- --------------------------------------------------------------------------- -- Due to the fact that only pointers to device and context are passed -- we ar going to use System.Address for them. subtype Context is System.Address; subtype Device is System.Address; subtype Bool is Binary.Byte; subtype Char is Binary.S_Byte; subtype Double is Long_Float; subtype Enum is Binary.S_Word; subtype Int is Integer; subtype Short is Binary.S_Short; subtype SizeI is Integer; subtype UByte is Binary.Byte; subtype UInt is Binary.Word; subtype UShort is Binary.Short; --------------------------------------------------------------------------- ----------------------- -- C O N S T A N T S -- ----------------------- --------------------------------------------------------------------------- -- Bool constants. ALC_FALSE : constant Bool := 0; ALC_TRUE : constant Bool := 1; -- Followed by <Int> Hz ALC_FREQUENCY : constant Enum := 16#1007#; -- Followed by <Int> Hz ALC_REFRESH : constant Enum := 16#1008#; -- Followed by AL_TRUE, AL_FALSE ALC_SYNC : constant Enum := 16#1009#; -- Followed by <Int> Num of requested Mono (3D) Sources ALC_MONO_SOURCES : constant Enum := 16#1010#; -- Followed by <Int> Num of requested Stereo Sources ALC_STEREO_SOURCES : constant Enum := 16#1011#; -- Errors -- No error ALC_NO_ERROR : constant Enum := 0; -- No device ALC_INVALID_DEVICE : constant Enum := 16#A001#; -- Invalid context ID ALC_INVALID_CONTEXT : constant Enum := 16#A002#; -- Bad enum ALC_INVALID_ENUM : constant Enum := 16#A003#; -- Bad value ALC_INVALID_VALUE : constant Enum := 16#A004#; -- Out of memory. ALC_OUT_OF_MEMORY : constant Enum := 16#A005#; -- The Specifier string for default device ALC_DEFAULT_DEVICE_SPECIFIER : constant Enum := 16#1004#; ALC_DEVICE_SPECIFIER : constant Enum := 16#1005#; ALC_EXTENSIONS : constant Enum := 16#1006#; ALC_MAJOR_VERSION : constant Enum := 16#1000#; ALC_MINOR_VERSION : constant Enum := 16#1001#; ALC_ATTRIBUTES_SIZE : constant Enum := 16#1002#; ALC_ALL_ATTRIBUTES : constant Enum := 16#1003#; -- Capture extension ALC_EXT_CAPTURE : constant Enum := 1; ALC_CAPTURE_DEVICE_SPECIFIER : constant Enum := 16#310#; ALC_CAPTURE_DEFAULT_DEVICE_SPECIFIER : constant Enum := 16#311#; ALC_CAPTURE_SAMPLES : constant Enum := 16#312#; -- ALC_ENUMERATE_ALL_EXT enums ALC_ENUMERATE_ALL_EXT : constant Enum := 1; ALC_DEFAULT_ALL_DEVICES_SPECIFIER : constant Enum := 16#1012#; ALC_ALL_DEVICES_SPECIFIER : constant Enum := 16#1013#; --------------------------------------------------------------------------- end OTO.ALC;
Add constants definitions.
ALC: Add constants definitions. Signed-off-by: darkestkhan <[email protected]>
Ada
isc
darkestkhan/oto
76c12d50497cbfde38cfe28a444b6b20f7c884cd
src/util-concurrent.ads
src/util-concurrent.ads
----------------------------------------------------------------------- -- Util.Concurrent -- Concurrent Tools -- Copyright (C) 2001, 2002, 2003, 2009, 2010 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- package Util.Concurrent is pragma Pure; end Util.Concurrent;
----------------------------------------------------------------------- -- util-concurrent -- Concurrent Tools -- Copyright (C) 2001, 2002, 2003, 2009, 2010, 2017 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- package Util.Concurrent is pragma Pure; end Util.Concurrent;
Update the header
Update the header
Ada
apache-2.0
stcarrez/ada-util,stcarrez/ada-util
fc3bd910e926d34766ace612e8ee30074d7e2050
src/natools-web-fallback_render.adb
src/natools-web-fallback_render.adb
------------------------------------------------------------------------------ -- Copyright (c) 2015-2017, Natacha Porté -- -- -- -- Permission to use, copy, modify, and distribute this software for any -- -- purpose with or without fee is hereby granted, provided that the above -- -- copyright notice and this permission notice appear in all copies. -- -- -- -- THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES -- -- WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF -- -- MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR -- -- ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES -- -- WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN -- -- ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF -- -- OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. -- ------------------------------------------------------------------------------ with Ada.Calendar; with Natools.S_Expressions.Atom_Refs; with Natools.S_Expressions.Caches; with Natools.S_Expressions.Templates.Dates; with Natools.Static_Maps.Web.Fallback_Render; with Natools.Web.ACL; with Natools.Web.Comment_Cookies; with Natools.Web.Escapes; with Natools.Web.Filters.Stores; with Natools.Web.Tags; with Natools.Web.String_Tables; procedure Natools.Web.Fallback_Render (Exchange : in out Natools.Web.Sites.Exchange; Name : in Natools.S_Expressions.Atom; Arguments : in out Natools.S_Expressions.Lockable.Descriptor'Class; Context : in String := ""; Re_Enter : access procedure (Exchange : in out Natools.Web.Sites.Exchange; Expression : in out Natools.S_Expressions.Lockable.Descriptor'Class) := null; Elements : in Natools.Web.Containers.Expression_Maps.Constant_Map := Natools.Web.Containers.Expression_Maps.Empty_Constant_Map; Severity : in Severities.Code := Severities.Error) is package Commands renames Natools.Static_Maps.Web.Fallback_Render; use type S_Expressions.Events.Event; procedure Render_Ref (Ref : in S_Expressions.Atom_Refs.Immutable_Reference); procedure Report_Unknown_Command; procedure Render_Ref (Ref : in S_Expressions.Atom_Refs.Immutable_Reference) is begin if not Ref.Is_Empty then Escapes.Write (Exchange, S_Expressions.To_String (Ref.Query), Escapes.HTML_Attribute); elsif Re_Enter /= null then Re_Enter (Exchange, Arguments); end if; end Render_Ref; procedure Report_Unknown_Command is begin if Context /= "" then Log (Severity, "Unknown render command """ & S_Expressions.To_String (Name) & """ in " & Context); end if; end Report_Unknown_Command; begin case Commands.To_Command (S_Expressions.To_String (Name)) is when Commands.Unknown => Report_Unknown_Command; when Commands.Current_Time => S_Expressions.Templates.Dates.Render (Exchange, Arguments, Ada.Calendar.Clock); when Commands.Cookies => String_Tables.Render (Exchange, String_Tables.Create (Exchange.Cookie_Table), Arguments); when Commands.Comment_Cookie_Filter => Render_Ref (Comment_Cookies.Filter (Sites.Comment_Info (Exchange))); when Commands.Comment_Cookie_Link => Render_Ref (Comment_Cookies.Link (Sites.Comment_Info (Exchange))); when Commands.Comment_Cookie_Mail => Render_Ref (Comment_Cookies.Mail (Sites.Comment_Info (Exchange))); when Commands.Comment_Cookie_Name => Render_Ref (Comment_Cookies.Name (Sites.Comment_Info (Exchange))); when Commands.Element => if Re_Enter = null then Report_Unknown_Command; else declare Template : S_Expressions.Caches.Cursor := Exchange.Site.Get_Template (Elements, Arguments, Lookup_Template => False); begin Re_Enter (Exchange, Template); end; end if; when Commands.Element_Or_Template => if Re_Enter = null then Report_Unknown_Command; else declare Template : S_Expressions.Caches.Cursor := Exchange.Site.Get_Template (Elements, Arguments); begin Re_Enter (Exchange, Template); end; end if; when Commands.Filter => if Re_Enter = null then Report_Unknown_Command; elsif Arguments.Current_Event = S_Expressions.Events.Add_Atom then begin declare Filter : Filters.Filter'Class := Exchange.Site.Get_Filter (Arguments.Current_Atom); begin Arguments.Next; Exchange.Insert_Filter (Filter); Re_Enter (Exchange, Arguments); Exchange.Remove_Filter (Filter); end; exception when Filters.Stores.No_Filter => null; end; end if; when Commands.If_Has_Element => if Re_Enter = null then Report_Unknown_Command; elsif Arguments.Current_Event = S_Expressions.Events.Add_Atom and then Elements.Contains (Arguments.Current_Atom) then Arguments.Next; Re_Enter (Exchange, Arguments); end if; when Commands.If_Has_Not_Element => if Re_Enter = null then Report_Unknown_Command; elsif Arguments.Current_Event = S_Expressions.Events.Add_Atom and then not Elements.Contains (Arguments.Current_Atom) then Arguments.Next; Re_Enter (Exchange, Arguments); end if; when Commands.If_Parameter_Is => if Re_Enter = null then Report_Unknown_Command; elsif Arguments.Current_Event = S_Expressions.Events.Add_Atom then declare Param_Value : constant String := Exchange.Parameter (S_Expressions.To_String (Arguments.Current_Atom)); Event : S_Expressions.Events.Event; begin Arguments.Next (Event); if Event = S_Expressions.Events.Add_Atom and then Param_Value = S_Expressions.To_String (Arguments.Current_Atom) then Arguments.Next; Re_Enter (Exchange, Arguments); end if; end; end if; when Commands.Load_Date => S_Expressions.Templates.Dates.Render (Exchange, Arguments, Exchange.Site.Load_Date); when Commands.Parameter => if Arguments.Current_Event = S_Expressions.Events.Add_Atom then Escapes.Write (Exchange, Exchange.Parameter (S_Expressions.To_String (Arguments.Current_Atom)), Escapes.HTML_Attribute); end if; when Commands.Set_MIME_Type => if Arguments.Current_Event = S_Expressions.Events.Add_Atom then Exchange.Set_MIME_Type (Arguments.Current_Atom); end if; when Commands.Tags => Tags.Render (Exchange, Exchange.Site.Get_Tags, Arguments); when Commands.Template => if Re_Enter = null then Report_Unknown_Command; else declare Template : S_Expressions.Caches.Cursor := Exchange.Site.Get_Template (Elements, Arguments, Lookup_Element => False); begin Re_Enter (Exchange, Template); end; end if; when Commands.User => if Re_Enter = null then Report_Unknown_Command; else declare Match : Boolean := False; begin ACL.Match (Sites.Identity (Exchange), Arguments, Match); if Match then Arguments.Next; Re_Enter (Exchange, Arguments); end if; end; end if; end case; end Natools.Web.Fallback_Render;
------------------------------------------------------------------------------ -- Copyright (c) 2015-2017, Natacha Porté -- -- -- -- Permission to use, copy, modify, and distribute this software for any -- -- purpose with or without fee is hereby granted, provided that the above -- -- copyright notice and this permission notice appear in all copies. -- -- -- -- THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES -- -- WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF -- -- MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR -- -- ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES -- -- WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN -- -- ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF -- -- OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. -- ------------------------------------------------------------------------------ with Ada.Calendar; with Natools.S_Expressions.Atom_Refs; with Natools.S_Expressions.Caches; with Natools.S_Expressions.Templates.Dates; with Natools.Static_Maps.Web.Fallback_Render; with Natools.Web.ACL; with Natools.Web.Comment_Cookies; with Natools.Web.Escapes; with Natools.Web.Filters.Stores; with Natools.Web.Tags; with Natools.Web.String_Tables; procedure Natools.Web.Fallback_Render (Exchange : in out Natools.Web.Sites.Exchange; Name : in Natools.S_Expressions.Atom; Arguments : in out Natools.S_Expressions.Lockable.Descriptor'Class; Context : in String := ""; Re_Enter : access procedure (Exchange : in out Natools.Web.Sites.Exchange; Expression : in out Natools.S_Expressions.Lockable.Descriptor'Class) := null; Elements : in Natools.Web.Containers.Expression_Maps.Constant_Map := Natools.Web.Containers.Expression_Maps.Empty_Constant_Map; Severity : in Severities.Code := Severities.Error) is package Commands renames Natools.Static_Maps.Web.Fallback_Render; use type S_Expressions.Events.Event; procedure Render_Ref (Ref : in S_Expressions.Atom_Refs.Immutable_Reference); procedure Report_Unknown_Command; procedure Render_Ref (Ref : in S_Expressions.Atom_Refs.Immutable_Reference) is begin if not Ref.Is_Empty then Escapes.Write (Exchange, S_Expressions.To_String (Ref.Query), Escapes.HTML_Attribute); elsif Re_Enter /= null then Re_Enter (Exchange, Arguments); end if; end Render_Ref; procedure Report_Unknown_Command is begin if Context /= "" then Log (Severity, "Unknown render command """ & S_Expressions.To_String (Name) & """ in " & Context); end if; end Report_Unknown_Command; begin case Commands.To_Command (S_Expressions.To_String (Name)) is when Commands.Unknown => Report_Unknown_Command; when Commands.Current_Time => S_Expressions.Templates.Dates.Render (Exchange, Arguments, Ada.Calendar.Clock); when Commands.Cookies => String_Tables.Render (Exchange, String_Tables.Create (Exchange.Cookie_Table), Arguments); when Commands.Comment_Cookie_Filter => Render_Ref (Comment_Cookies.Filter (Sites.Comment_Info (Exchange))); when Commands.Comment_Cookie_Link => Render_Ref (Comment_Cookies.Link (Sites.Comment_Info (Exchange))); when Commands.Comment_Cookie_Mail => Render_Ref (Comment_Cookies.Mail (Sites.Comment_Info (Exchange))); when Commands.Comment_Cookie_Name => Render_Ref (Comment_Cookies.Name (Sites.Comment_Info (Exchange))); when Commands.Element => if Re_Enter = null then Report_Unknown_Command; else declare Template : S_Expressions.Caches.Cursor := Exchange.Site.Get_Template (Elements, Arguments, Lookup_Template => False); begin Re_Enter (Exchange, Template); end; end if; when Commands.Element_Or_Template => if Re_Enter = null then Report_Unknown_Command; else declare Template : S_Expressions.Caches.Cursor := Exchange.Site.Get_Template (Elements, Arguments); begin Re_Enter (Exchange, Template); end; end if; when Commands.Filter => if Re_Enter = null then Report_Unknown_Command; elsif Arguments.Current_Event = S_Expressions.Events.Add_Atom then begin declare Filter : Filters.Filter'Class := Exchange.Site.Get_Filter (Arguments.Current_Atom); begin Arguments.Next; Exchange.Insert_Filter (Filter); Re_Enter (Exchange, Arguments); Exchange.Remove_Filter (Filter); end; exception when Filters.Stores.No_Filter => null; end; end if; when Commands.If_Has_Element => if Re_Enter = null then Report_Unknown_Command; elsif Arguments.Current_Event = S_Expressions.Events.Add_Atom and then Elements.Contains (Arguments.Current_Atom) then Arguments.Next; Re_Enter (Exchange, Arguments); end if; when Commands.If_Has_Not_Element => if Re_Enter = null then Report_Unknown_Command; elsif Arguments.Current_Event = S_Expressions.Events.Add_Atom and then not Elements.Contains (Arguments.Current_Atom) then Arguments.Next; Re_Enter (Exchange, Arguments); end if; when Commands.If_Parameter_Is => if Re_Enter = null then Report_Unknown_Command; elsif Arguments.Current_Event = S_Expressions.Events.Add_Atom then declare Param_Value : constant String := Exchange.Parameter (S_Expressions.To_String (Arguments.Current_Atom)); Event : S_Expressions.Events.Event; begin Arguments.Next (Event); if Event = S_Expressions.Events.Add_Atom and then Param_Value = S_Expressions.To_String (Arguments.Current_Atom) then Arguments.Next; Re_Enter (Exchange, Arguments); end if; end; end if; when Commands.Load_Date => S_Expressions.Templates.Dates.Render (Exchange, Arguments, Exchange.Site.Load_Date); when Commands.Parameter => if Arguments.Current_Event = S_Expressions.Events.Add_Atom then declare Parameter_Name : constant String := S_Expressions.To_String (Arguments.Current_Atom); begin if Exchange.Has_Parameter (Parameter_Name) then Escapes.Write (Exchange, Exchange.Parameter (Parameter_Name), Escapes.HTML_Attribute); elsif Re_Enter /= null then Arguments.Next; Re_Enter (Exchange, Arguments); end if; end; end if; when Commands.Set_MIME_Type => if Arguments.Current_Event = S_Expressions.Events.Add_Atom then Exchange.Set_MIME_Type (Arguments.Current_Atom); end if; when Commands.Tags => Tags.Render (Exchange, Exchange.Site.Get_Tags, Arguments); when Commands.Template => if Re_Enter = null then Report_Unknown_Command; else declare Template : S_Expressions.Caches.Cursor := Exchange.Site.Get_Template (Elements, Arguments, Lookup_Element => False); begin Re_Enter (Exchange, Template); end; end if; when Commands.User => if Re_Enter = null then Report_Unknown_Command; else declare Match : Boolean := False; begin ACL.Match (Sites.Identity (Exchange), Arguments, Match); if Match then Arguments.Next; Re_Enter (Exchange, Arguments); end if; end; end if; end case; end Natools.Web.Fallback_Render;
add fallback on non-existing parameters
fallback_render: add fallback on non-existing parameters
Ada
isc
faelys/natools-web,faelys/natools-web
b8f0aa088789d29a48dd6366694c162ca5d71794
src/security.ads
src/security.ads
----------------------------------------------------------------------- -- security -- Security -- Copyright (C) 2010, 2011, 2012 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- -- == Introduction == -- The <tt>Security</tt> package provides a security framework that allows -- an application to use OpenID or OAuth security frameworks. This security -- framework was first developed within the Ada Server Faces project. -- This package defines abstractions that are close or similar to Java -- security package. -- -- === Principal === -- The <tt>Principal</tt> is the entity that can be authenticated. A principal is obtained -- after successful authentication of a user or of a system through an authorization process. -- The OpenID or OAuth authentication processes generate such security principal. -- -- === Permission === -- The <tt>Permission</tt> represents an access to a system or application resource. -- A permission is checked by using the security manager. The security manager uses a -- security controller to enforce the permission. -- -- @include security-permissions.ads -- @include security-openid.ads -- @include security-oauth.ads -- @include security-contexts.ads -- @include security-controllers.ads package Security is -- ------------------------------ -- Principal -- ------------------------------ type Principal is limited interface; type Principal_Access is access all Principal'Class; -- Get the principal name. function Get_Name (From : in Principal) return String is abstract; end Security;
----------------------------------------------------------------------- -- security -- Security -- Copyright (C) 2010, 2011, 2012 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- -- == Introduction == -- The <tt>Security</tt> package provides a security framework that allows -- an application to use OpenID or OAuth security frameworks. This security -- framework was first developed within the Ada Server Faces project. -- This package defines abstractions that are close or similar to Java -- security package. -- -- === Policy and policy manager === -- The <tt>Policy</tt> defines and implements the set of security rules that specify how to -- protect the system or resources. The <tt>Policy_Manager</tt> maintains the security policies. -- -- === Principal === -- The <tt>Principal</tt> is the entity that can be authenticated. A principal is obtained -- after successful authentication of a user or of a system through an authorization process. -- The OpenID or OAuth authentication processes generate such security principal. -- -- === Permission === -- The <tt>Permission</tt> represents an access to a system or application resource. -- A permission is checked by using the security policy manager. The policy manager uses a -- security controller to enforce the permission. -- -- === Security Context === -- The <tt>Security_Context</tt> holds the contextual information that the security controller -- can use to verify the permission. The security context is associated with a principal and -- a set of policy context. -- -- -- [http://ada-security.googlecode.com/svn/wiki/ModelOverview.png] -- -- @include security-permissions.ads -- @include security-openid.ads -- @include security-oauth.ads -- @include security-contexts.ads -- @include security-controllers.ads package Security is -- ------------------------------ -- Principal -- ------------------------------ type Principal is limited interface; type Principal_Access is access all Principal'Class; -- Get the principal name. function Get_Name (From : in Principal) return String is abstract; end Security;
Document the policy and policy manager
Document the policy and policy manager
Ada
apache-2.0
Letractively/ada-security
bda0942401d847c2e2277a0f2bc3f9bb9c6baa3e
mat/src/mat-expressions.ads
mat/src/mat-expressions.ads
----------------------------------------------------------------------- -- mat-expressions -- Expressions for memory slot selection -- Copyright (C) 2014 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with MAT.Types; with MAT.Memory; package MAT.Expressions is type Context_Type is record Addr : MAT.Types.Target_Addr; Allocation : MAT.Memory.Allocation; end record; type Kind_Type is (N_NOT, N_OR, N_AND, N_TRUE, N_FALSE, N_IN_FILE, N_IN_FILE_DIRECT, N_IN_FUNC, N_IN_FUNC_DIRECT, N_RANGE_SIZE, N_RANGE_ADDR, N_CONDITION, N_THREAD); type Expression_Type is tagged private; -- Create a new expression node. function Create (Kind : in Kind_Type; Expr : in Expression_Type) return Expression_Type; -- Evaluate the expression to check if the memory slot described by the -- context is selected. Returns True if the memory slot is selected. function Is_Selected (Node : in Expression_Type; Context : in Context_Type) return Boolean; private type Node_Type (Kind : Kind_Type) is tagged limited record N : Natural; end record; type Node_Type_Access is access all Node_Type'Class; function Is_Selected (Node : in Node_Type; Context : in Context_Type) return Boolean; type Expression_Type is tagged record Node : Node_Type_Access; end record; end MAT.Expressions;
----------------------------------------------------------------------- -- mat-expressions -- Expressions for memory slot selection -- Copyright (C) 2014 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Strings.Unbounded; with MAT.Types; with MAT.Memory; package MAT.Expressions is type Context_Type is record Addr : MAT.Types.Target_Addr; Allocation : MAT.Memory.Allocation; end record; type Kind_Type is (N_NOT, N_OR, N_AND, N_TRUE, N_FALSE, N_IN_FILE, N_IN_FILE_DIRECT, N_CALL_ADDR, N_CALL_ADDR_DIRECT, N_IN_FUNC, N_IN_FUNC_DIRECT, N_RANGE_SIZE, N_RANGE_ADDR, N_CONDITION, N_THREAD); type Expression_Type is tagged private; -- Create a new expression node. function Create (Kindx : in Kind_Type; Expr : in Expression_Type) return Expression_Type; -- Evaluate the expression to check if the memory slot described by the -- context is selected. Returns True if the memory slot is selected. function Is_Selected (Node : in Expression_Type; Context : in Context_Type) return Boolean; private type Node_Type; type Node_Type_Access is access all Node_Type'Class; type Node_Type (Kind : Kind_Type) is tagged limited record case Kind is when N_NOT => Expr : Node_Type_Access; when N_OR | N_AND => Left, Right : Node_Type_Access; when N_IN_FILE | N_IN_FILE_DIRECT | N_IN_FUNC | N_IN_FUNC_DIRECT => Name : Ada.Strings.Unbounded.Unbounded_String; when N_RANGE_SIZE => Min_Size : MAT.Types.Target_Size; Max_Size : MAT.Types.Target_Size; when N_RANGE_ADDR | N_CALL_ADDR | N_CALL_ADDR_DIRECT => Min_Addr : MAT.Types.Target_Addr; Max_Addr : MAT.Types.Target_Addr; when N_THREAD => Thread : MAT.Types.Target_Thread_Ref; when others => null; end case; end record; function Is_Selected (Node : in Node_Type; Context : in Context_Type) return Boolean; type Expression_Type is tagged record Node : Node_Type_Access; end record; end MAT.Expressions;
Define the Node_Type
Define the Node_Type
Ada
apache-2.0
stcarrez/mat,stcarrez/mat,stcarrez/mat
44994b6c0ed94f2c64ed213c98ff659d86f55062
awa/src/awa-commands-start.ads
awa/src/awa-commands-start.ads
----------------------------------------------------------------------- -- awa-commands-start -- Command to start the web server -- 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 GNAT.Command_Line; with GNAT.Strings; with AWA.Commands.Drivers; generic with package Command_Drivers is new AWA.Commands.Drivers (<>); package AWA.Commands.Start is type Command_Type is new Command_Drivers.Command_Type with record Management_Port : aliased Integer := 0; Listening_Port : aliased Integer := 8080; Upload_Size_Limit : aliased Integer := 16#500_000#; Max_Connection : aliased Integer := 5; TCP_No_Delay : aliased Boolean := False; Upload : aliased GNAT.Strings.String_Access; end record; -- Start the server and all the application that have been registered. overriding procedure Execute (Command : in out Command_Type; Name : in String; Args : in Argument_List'Class; Context : in out Context_Type); -- Setup the command before parsing the arguments and executing it. overriding procedure Setup (Command : in out Command_Type; Config : in out GNAT.Command_Line.Command_Line_Configuration; Context : in out Context_Type); -- Write the help associated with the command. overriding procedure Help (Command : in out Command_Type; Name : in String; Context : in out Context_Type); Command : aliased Command_Type; end AWA.Commands.Start;
----------------------------------------------------------------------- -- awa-commands-start -- Command to start the web server -- 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 GNAT.Command_Line; with GNAT.Strings; with AWA.Commands.Drivers; generic with package Command_Drivers is new AWA.Commands.Drivers (<>); package AWA.Commands.Start is type Command_Type is new Command_Drivers.Command_Type with record Management_Port : aliased Integer := 0; Listening_Port : aliased Integer := 8080; Upload_Size_Limit : aliased Integer := 16#500_000#; Max_Connection : aliased Integer := 5; TCP_No_Delay : aliased Boolean := False; Daemon : aliased Boolean := False; Upload : aliased GNAT.Strings.String_Access; end record; -- Start the server and all the application that have been registered. overriding procedure Execute (Command : in out Command_Type; Name : in String; Args : in Argument_List'Class; Context : in out Context_Type); -- Setup the command before parsing the arguments and executing it. overriding procedure Setup (Command : in out Command_Type; Config : in out GNAT.Command_Line.Command_Line_Configuration; Context : in out Context_Type); -- Write the help associated with the command. overriding procedure Help (Command : in out Command_Type; Name : in String; Context : in out Context_Type); Command : aliased Command_Type; end AWA.Commands.Start;
Add Daemon boolean
Add Daemon boolean
Ada
apache-2.0
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
5cf885d95f706862a42b48ad1c3bb71c0658f924
awa/src/awa-commands-start.ads
awa/src/awa-commands-start.ads
----------------------------------------------------------------------- -- awa-commands-start -- Command to start the web server -- 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 GNAT.Command_Line; with GNAT.Strings; with AWA.Commands.Drivers; generic with package Command_Drivers is new AWA.Commands.Drivers (<>); package AWA.Commands.Start is type Command_Type is new Command_Drivers.Command_Type with record Management_Port : aliased Integer := 0; Listening_Port : aliased Integer := 8080; Upload_Size_Limit : aliased Integer := 16#500_000#; Max_Connection : aliased Integer := 5; TCP_No_Delay : aliased Boolean := False; Daemon : aliased Boolean := False; Upload : aliased GNAT.Strings.String_Access; end record; -- Start the server and all the application that have been registered. overriding procedure Execute (Command : in out Command_Type; Name : in String; Args : in Argument_List'Class; Context : in out Context_Type); -- Start the server and all the application that have been registered. procedure Start_Server (Command : in out Command_Type; Context : in out Context_Type); -- Wait for the server to shutdown. procedure Wait_Server (Command : in out Command_Type; Context : in out Context_Type); -- Setup the command before parsing the arguments and executing it. overriding procedure Setup (Command : in out Command_Type; Config : in out GNAT.Command_Line.Command_Line_Configuration; Context : in out Context_Type); -- Write the help associated with the command. overriding procedure Help (Command : in out Command_Type; Name : in String; Context : in out Context_Type); Command : aliased Command_Type; end AWA.Commands.Start;
----------------------------------------------------------------------- -- awa-commands-start -- Command to start the web server -- 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 GNAT.Command_Line; with GNAT.Strings; with AWA.Commands.Drivers; generic with package Command_Drivers is new AWA.Commands.Drivers (<>); package AWA.Commands.Start is type Command_Type is new Command_Drivers.Command_Type with record Management_Port : aliased Integer := 0; Listening_Port : aliased Integer := 8080; Upload_Size_Limit : aliased Integer := 16#500_000#; Max_Connection : aliased Integer := 5; TCP_No_Delay : aliased Boolean := False; Daemon : aliased Boolean := False; Upload : aliased GNAT.Strings.String_Access; end record; -- Start the server and all the application that have been registered. overriding procedure Execute (Command : in out Command_Type; Name : in String; Args : in Argument_List'Class; Context : in out Context_Type); -- Configure the web server container before applications are registered. procedure Configure_Server (Command : in out Command_Type; Context : in out Context_Type); -- Configure all registered applications. procedure Configure_Applications (Command : in out Command_Type; Context : in out Context_Type); -- Start the web server. procedure Start_Server (Command : in out Command_Type; Context : in out Context_Type); -- Wait for the server to shutdown. procedure Wait_Server (Command : in out Command_Type; Context : in out Context_Type); -- Setup the command before parsing the arguments and executing it. overriding procedure Setup (Command : in out Command_Type; Config : in out GNAT.Command_Line.Command_Line_Configuration; Context : in out Context_Type); -- Write the help associated with the command. overriding procedure Help (Command : in out Command_Type; Name : in String; Context : in out Context_Type); Command : aliased Command_Type; end AWA.Commands.Start;
Add Configure_Server and Configure_Applications
Add Configure_Server and Configure_Applications
Ada
apache-2.0
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
96b5d8460d1a628d5b435306255abdf22aa26471
src/wiki-render-html.ads
src/wiki-render-html.ads
----------------------------------------------------------------------- -- wiki-render-html -- Wiki HTML renderer -- Copyright (C) 2011, 2012, 2013, 2015, 2016 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Wiki.Attributes; with Wiki.Streams.Html; with Wiki.Strings; -- == HTML Renderer == -- The <tt>Text_Renderer</tt> allows to render a wiki document into a text content. -- The formatting rules are ignored except for the paragraphs and sections. package Wiki.Render.Html is -- ------------------------------ -- Wiki to HTML renderer -- ------------------------------ type Html_Renderer is new Renderer with private; -- Set the output stream. procedure Set_Output_Stream (Engine : in out Html_Renderer; Stream : in Wiki.Streams.Html.Html_Output_Stream_Access); -- Set the link renderer. procedure Set_Link_Renderer (Engine : in out Html_Renderer; Links : in Link_Renderer_Access); -- Render the node instance from the document. overriding procedure Render (Engine : in out Html_Renderer; Doc : in Wiki.Documents.Document; Node : in Wiki.Nodes.Node_Type); -- 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 Html_Renderer; Level : in Natural); -- Render 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 Render_List_Item (Engine : in out Html_Renderer; Level : in Positive; Ordered : in Boolean); -- Add a text block with the given format. procedure Add_Text (Engine : in out Html_Renderer; Text : in Wiki.Strings.WString; Format : in Wiki.Format_Map); -- Render a text block that is pre-formatted. procedure Render_Preformatted (Engine : in out Html_Renderer; Text : in Wiki.Strings.WString; Format : in Wiki.Strings.WString); -- Finish the document after complete wiki text has been parsed. overriding procedure Finish (Engine : in out Html_Renderer; Doc : in Wiki.Documents.Document); private procedure Close_Paragraph (Engine : in out Html_Renderer); procedure Open_Paragraph (Engine : in out Html_Renderer); type List_Style_Array is array (1 .. 32) of Boolean; Default_Links : aliased Default_Link_Renderer; type Html_Renderer is new Renderer with record Output : Wiki.Streams.Html.Html_Output_Stream_Access := null; Format : Wiki.Format_Map := (others => False); Links : Link_Renderer_Access := Default_Links'Access; Has_Paragraph : Boolean := False; Need_Paragraph : Boolean := False; Has_Item : Boolean := False; Current_Level : Natural := 0; List_Styles : List_Style_Array := (others => False); Quote_Level : Natural := 0; Html_Level : Natural := 0; end record; procedure Render_Tag (Engine : in out Html_Renderer; Doc : in Wiki.Documents.Document; Node : in Wiki.Nodes.Node_Type); -- Render a section header in the document. procedure Render_Header (Engine : in out Html_Renderer; Header : in Wiki.Strings.WString; Level : in Positive); -- Render the table of content. procedure Render_TOC (Engine : in out Html_Renderer; Doc : in Wiki.Documents.Document; Level : in Natural); -- Render a link. procedure Render_Link (Engine : in out Html_Renderer; Doc : in Wiki.Documents.Document; Title : in Wiki.Strings.WString; Attr : in Wiki.Attributes.Attribute_List); -- Render an image. procedure Render_Image (Engine : in out Html_Renderer; Doc : in Wiki.Documents.Document; Title : in Wiki.Strings.WString; Attr : in Wiki.Attributes.Attribute_List); -- Render a quote. procedure Render_Quote (Engine : in out Html_Renderer; Doc : in Wiki.Documents.Document; Title : in Wiki.Strings.WString; Attr : in Wiki.Attributes.Attribute_List); end Wiki.Render.Html;
----------------------------------------------------------------------- -- wiki-render-html -- Wiki HTML renderer -- Copyright (C) 2011, 2012, 2013, 2015, 2016 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Wiki.Attributes; with Wiki.Streams.Html; with Wiki.Strings; -- == HTML Renderer == -- The <tt>Text_Renderer</tt> allows to render a wiki document into a text content. -- The formatting rules are ignored except for the paragraphs and sections. package Wiki.Render.Html is -- ------------------------------ -- Wiki to HTML renderer -- ------------------------------ type Html_Renderer is new Renderer with private; -- Set the output stream. procedure Set_Output_Stream (Engine : in out Html_Renderer; Stream : in Wiki.Streams.Html.Html_Output_Stream_Access); -- Set the link renderer. procedure Set_Link_Renderer (Engine : in out Html_Renderer; Links : in Link_Renderer_Access); -- Set the render TOC flag that controls the TOC rendering. procedure Set_Render_TOC (Engine : in out Html_Renderer; State : in Boolean); -- Render the node instance from the document. overriding procedure Render (Engine : in out Html_Renderer; Doc : in Wiki.Documents.Document; Node : in Wiki.Nodes.Node_Type); -- 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 Html_Renderer; Level : in Natural); -- Render 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 Render_List_Item (Engine : in out Html_Renderer; Level : in Positive; Ordered : in Boolean); -- Add a text block with the given format. procedure Add_Text (Engine : in out Html_Renderer; Text : in Wiki.Strings.WString; Format : in Wiki.Format_Map); -- Render a text block that is pre-formatted. procedure Render_Preformatted (Engine : in out Html_Renderer; Text : in Wiki.Strings.WString; Format : in Wiki.Strings.WString); -- Finish the document after complete wiki text has been parsed. overriding procedure Finish (Engine : in out Html_Renderer; Doc : in Wiki.Documents.Document); private procedure Close_Paragraph (Engine : in out Html_Renderer); procedure Open_Paragraph (Engine : in out Html_Renderer); type List_Style_Array is array (1 .. 32) of Boolean; Default_Links : aliased Default_Link_Renderer; type Html_Renderer is new Renderer with record Output : Wiki.Streams.Html.Html_Output_Stream_Access := null; Format : Wiki.Format_Map := (others => False); Links : Link_Renderer_Access := Default_Links'Access; Has_Paragraph : Boolean := False; Need_Paragraph : Boolean := False; Has_Item : Boolean := False; Enable_Render_TOC : Boolean := False; Current_Level : Natural := 0; List_Styles : List_Style_Array := (others => False); Quote_Level : Natural := 0; Html_Level : Natural := 0; end record; procedure Render_Tag (Engine : in out Html_Renderer; Doc : in Wiki.Documents.Document; Node : in Wiki.Nodes.Node_Type); -- Render a section header in the document. procedure Render_Header (Engine : in out Html_Renderer; Header : in Wiki.Strings.WString; Level : in Positive); -- Render the table of content. procedure Render_TOC (Engine : in out Html_Renderer; Doc : in Wiki.Documents.Document; Level : in Natural); -- Render a link. procedure Render_Link (Engine : in out Html_Renderer; Doc : in Wiki.Documents.Document; Title : in Wiki.Strings.WString; Attr : in Wiki.Attributes.Attribute_List); -- Render an image. procedure Render_Image (Engine : in out Html_Renderer; Doc : in Wiki.Documents.Document; Title : in Wiki.Strings.WString; Attr : in Wiki.Attributes.Attribute_List); -- Render a quote. procedure Render_Quote (Engine : in out Html_Renderer; Doc : in Wiki.Documents.Document; Title : in Wiki.Strings.WString; Attr : in Wiki.Attributes.Attribute_List); end Wiki.Render.Html;
Declare Set_Render_TOC procedure and add a Enable_Render_TOC member to the Html_Renderer
Declare Set_Render_TOC procedure and add a Enable_Render_TOC member to the Html_Renderer
Ada
apache-2.0
stcarrez/ada-wiki,stcarrez/ada-wiki
149acb682fbe4718df2cc75581ae2734d70540a8
src/util-properties-bundles.adb
src/util-properties-bundles.adb
----------------------------------------------------------------------- -- properties -- Generic name/value property management -- Copyright (C) 2001, 2002, 2003, 2006, 2008, 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 Ada.Unchecked_Deallocation; with Ada.Unchecked_Conversion; with Ada.Directories; with Ada.Containers.Vectors; with Ada.Strings.Fixed; with Util.Log.Loggers; with Util.Files; package body Util.Properties.Bundles is Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("Util.Properties.Bundles"); procedure Free is new Ada.Unchecked_Deallocation (Manager'Class, Bundle_Manager_Access); -- Implementation of the Bundle -- (this allows to decouples the implementation from the API) package Interface_P is type Manager is new Util.Properties.Interface_P.Manager with private; type Manager_Object_Access is access all Manager; -- Returns TRUE if the property exists. function Exists (Self : in Manager; Name : in Value) return Boolean; -- Returns the property value. Raises an exception if not found. function Get (Self : in Manager; Name : in Value) return Value; procedure Insert (Self : in out Manager; Name : in Value; Item : in Value); -- Set the value of the property. The property is created if it -- does not exists. procedure Set (Self : in out Manager; Name : in Value; Item : in Value); -- Remove the property given its name. procedure Remove (Self : in out Manager; Name : in Value); -- Iterate over the properties and execute the given procedure passing the -- property name and its value. procedure Iterate (Self : in Manager; Process : access procedure (Name, Item : Value)); procedure Load_Properties (Self : in out Manager; File : in String); -- Deep copy of properties stored in 'From' to 'To'. function Create_Copy (Self : in Manager) return Util.Properties.Interface_P.Manager_Access; procedure Delete (Self : in Manager; Obj : in out Util.Properties.Interface_P.Manager_Access); function Get_Names (Self : in Manager; Prefix : in String) return Name_Array; procedure Add_Bundle (Self : in out Manager; Props : in Util.Properties.Manager_Access); private use type Util.Properties.Manager_Access; package PropertyList is new Ada.Containers.Vectors (Element_Type => Util.Properties.Manager_Access, Index_Type => Natural, "=" => "="); type Manager is new Util.Properties.Interface_P.Manager with record List : PropertyList.Vector; Props : aliased Util.Properties.Manager; end record; procedure Free is new Ada.Unchecked_Deallocation (Manager, Manager_Object_Access); end Interface_P; procedure Add_Bundle (Self : in out Manager; Props : in Manager_Access) is use type Util.Properties.Interface_P.Manager_Access; begin Interface_P.Manager'Class (Self.Impl.all).Add_Bundle (Props); end Add_Bundle; procedure Initialize (Object : in out Manager) is use Util.Properties.Interface_P; begin Object.Impl := new Util.Properties.Bundles.Interface_P.Manager; Object.Impl.Count := 1; end Initialize; procedure Adjust (Object : in out Manager) is use Util.Properties.Interface_P; begin if Object.Impl /= null then Object.Impl.Count := Object.Impl.Count + 1; else Object.Impl := new Util.Properties.Bundles.Interface_P.Manager; Object.Impl.Count := 1; end if; end Adjust; -- ------------------------------ -- Initialize the bundle factory and specify where the property files are stored. -- ------------------------------ procedure Initialize (Factory : in out Loader; Path : in String) is begin Log.Info ("Initialize bundle factory to load from {0}", Path); Factory.Path := To_Unbounded_String (Path); end Initialize; -- ------------------------------ -- Load the bundle with the given name and for the given locale name. -- ------------------------------ procedure Load_Bundle (Factory : in out Loader; Name : in String; Locale : in String; Bundle : out Manager'Class) is Found : Boolean := False; begin Log.Info ("Load bundle {0} for language {1}", Name, Locale); Find_Bundle (Factory, Name, Locale, Bundle, Found); if not Found then Load_Bundle (Factory, Name, Found); if not Found then Log.Error ("Bundle {0} not found", Name); raise NO_BUNDLE with "No bundle '" & Name & "'"; end if; Find_Bundle (Factory, Name, Locale, Bundle, Found); if not Found then Log.Error ("Bundle {0} not found", Name); raise NO_BUNDLE with "No bundle '" & Name & "'"; end if; end if; end Load_Bundle; -- ------------------------------ -- Find the bundle with the given name and for the given locale name. -- ------------------------------ procedure Find_Bundle (Factory : in out Loader; Name : in String; Locale : in String; Bundle : out Manager'Class; Found : out Boolean) is use Ada.Strings; use type Util.Properties.Manager_Access; Loc_Name : constant String := '_' & Locale; Last_Pos : Integer := Loc_Name'Last; begin Log.Info ("Looking for bundle {0} and language {1}", Name, Locale); Found := False; Factory.Lock.Read; declare Pos : Bundle_Map.Cursor; begin while Last_Pos + 1 >= Loc_Name'First loop declare Bundle_Name : aliased constant String := Name & Loc_Name (Loc_Name'First .. Last_Pos); begin Log.Debug ("Searching for {0}", Bundle_Name); Pos := Factory.Bundles.Find (Bundle_Name'Unrestricted_Access); if Bundle_Map.Has_Element (Pos) then Bundle.Finalize; Bundle.Impl := Bundle_Map.Element (Pos).Impl; Bundle.Impl.Count := Bundle.Impl.Count + 1; Found := True; exit; end if; end; if Last_Pos > Loc_Name'First then Last_Pos := Fixed.Index (Loc_Name, "_", Last_Pos - 1, Backward) - 1; else Last_Pos := Last_Pos - 1; end if; end loop; exception when others => Factory.Lock.Release_Read; raise; end; Factory.Lock.Release_Read; end Find_Bundle; -- ------------------------------ -- Load the bundle with the given name and for the given locale name. -- ------------------------------ procedure Load_Bundle (Factory : in out Loader; Name : in String; Found : out Boolean) is use Ada.Directories; use Ada.Strings; use Util.Strings; use Ada.Containers; use Util.Strings.String_Set; use Bundle_Map; procedure Process_File (Name : in String; File_Path : in String; Done : out Boolean); Path : constant String := To_String (Factory.Path); Pattern : constant String := Name & "*.properties"; Names : Util.Strings.String_Set.Set; procedure Process_File (Name : in String; File_Path : in String; Done : out Boolean) is subtype Cursor is Bundle_Map.Cursor; Base_Name : aliased constant String := Name (Name'First .. Name'Last - 11); Pos : constant Cursor := Factory.Bundles.Find (Base_Name'Unchecked_Access); Bundle_Name : Name_Access; Bundle : Bundle_Manager_Access; begin Log.Debug ("Loading file {0}", File_Path); if Bundle_Map.Has_Element (Pos) then Bundle := Bundle_Map.Element (Pos); else Bundle := new Manager; Bundle_Name := new String '(Base_Name); Factory.Bundles.Include (Key => Bundle_Name, New_Item => Bundle); Names.Insert (Bundle_Name); end if; Interface_P.Manager'Class (Bundle.Impl.all).Load_Properties (File_Path); Found := True; Done := False; end Process_File; begin Log.Info ("Reading bundle {1} in directory {0}", Path, Name); Found := False; Factory.Lock.Write; begin Util.Files.Iterate_Files_Path (Pattern => Pattern, Path => Path, Process => Process_File'Access, Going => Ada.Strings.Backward); -- Link the property files to implement the localization default rules. while Names.Length > 0 loop declare Name_Pos : String_Set.Cursor := Names.First; Bundle_Name : constant Name_Access := String_Set.Element (Name_Pos); Idx : Natural := Fixed.Index (Bundle_Name.all, "_", Backward); Bundle_Pos : constant Bundle_Map.Cursor := Factory.Bundles.Find (Bundle_Name); Bundle : constant Bundle_Manager_Access := Element (Bundle_Pos); begin Names.Delete (Name_Pos); -- Associate the property bundle to the first existing parent -- Ex: message_fr_CA -> message_fr -- message_fr_CA -> message while Idx > 0 loop declare Name : aliased constant String := Bundle_Name (Bundle_Name'First .. Idx - 1); Pos : constant Bundle_Map.Cursor := Factory.Bundles.Find (Name'Unchecked_Access); begin if Bundle_Map.Has_Element (Pos) then Bundle.Add_Bundle (Bundle_Map.Element (Pos).all'Access); Idx := 0; else Idx := Fixed.Index (Bundle_Name.all, "_", Idx - 1, Backward); end if; end; end loop; end; end loop; exception when others => Factory.Lock.Release_Write; raise; end; Factory.Lock.Release_Write; exception when Name_Error => Log.Error ("Cannot read directory: {0}", Path); end Load_Bundle; -- Implementation of the Bundle -- (this allows to decouples the implementation from the API) package body Interface_P is use PropertyList; -- ------------------------------ -- Returns TRUE if the property exists. -- ------------------------------ function Exists (Self : in Manager; Name : in Value) return Boolean is Iter : Cursor := Self.List.First; begin if Self.Props.Exists (Name) then return True; end if; while Has_Element (Iter) loop if Element (Iter).Exists (Name) then return True; end if; Iter := Next (Iter); end loop; return False; end Exists; -- ------------------------------ -- Returns the property value. Raises an exception if not found. -- ------------------------------ function Get (Self : in Manager; Name : in Value) return Value is begin return Self.Props.Get (Name); exception when NO_PROPERTY => declare Iter : Cursor := Self.List.First; begin while Has_Element (Iter) loop begin return Element (Iter).all.Get (Name); exception when NO_PROPERTY => Iter := Next (Iter); end; end loop; end; raise; end Get; procedure Load_Properties (Self : in out Manager; File : in String) is begin Self.Props.Load_Properties (File); end Load_Properties; procedure Insert (Self : in out Manager; Name : in Value; Item : in Value) is pragma Unreferenced (Self); pragma Unreferenced (Name); pragma Unreferenced (Item); begin raise NOT_WRITEABLE with "Bundle is readonly"; end Insert; -- ------------------------------ -- Set the value of the property. The property is created if it -- does not exists. -- ------------------------------ procedure Set (Self : in out Manager; Name : in Value; Item : in Value) is begin raise NOT_WRITEABLE with "Bundle is readonly"; end Set; -- ------------------------------ -- Remove the property given its name. -- ------------------------------ procedure Remove (Self : in out Manager; Name : in Value) is begin raise NOT_WRITEABLE with "Bundle is readonly"; end Remove; -- Iterate over the properties and execute the given procedure passing the -- property name and its value. procedure Iterate (Self : in Manager; Process : access procedure (Name, Item : Value)) is begin raise Program_Error with "Iterate is not implemented on Bundle"; end Iterate; -- ------------------------------ -- Deep copy of properties stored in 'From' to 'To'. -- ------------------------------ function Create_Copy (Self : in Manager) return Util.Properties.Interface_P.Manager_Access is pragma Unreferenced (Self); begin return null; end Create_Copy; procedure Delete (Self : in Manager; Obj : in out Util.Properties.Interface_P.Manager_Access) is pragma Unreferenced (Self); Item : Manager_Object_Access := Manager (Obj.all)'Access; begin Free (Item); end Delete; function Get_Names (Self : in Manager; Prefix : in String) return Name_Array is Result : Name_Array (1 .. 2); Iter : constant Cursor := Self.List.First; begin while Has_Element (Iter) loop declare M : constant Util.Properties.Manager_Access := Element (Iter); N : constant Name_Array := M.Get_Names (Prefix); begin return N; end; end loop; return Result; end Get_Names; procedure Add_Bundle (Self : in out Manager; Props : in Util.Properties.Manager_Access) is begin Self.List.Append (Props); end Add_Bundle; end Interface_P; -- ------------------------------ -- Clear the bundle cache -- ------------------------------ procedure Clear_Cache (Factory : in out Loader) is use Util.Strings; use Bundle_Map; function To_String_Access is new Ada.Unchecked_Conversion (Source => Util.Strings.Name_Access, Target => Ada.Strings.Unbounded.String_Access); begin Log.Info ("Clearing bundle cache"); Factory.Lock.Write; loop declare Pos : Bundle_Map.Cursor := Factory.Bundles.First; Name : Ada.Strings.Unbounded.String_Access; Node : Bundle_Manager_Access; begin exit when not Has_Element (Pos); Node := Element (Pos); Name := To_String_Access (Key (Pos)); Factory.Bundles.Delete (Pos); Free (Node); Free (Name); end; end loop; Factory.Lock.Release_Write; end Clear_Cache; -- ------------------------------ -- Finalize the bundle loader and clear the cache -- ------------------------------ procedure Finalize (Factory : in out Loader) is begin Clear_Cache (Factory); end Finalize; end Util.Properties.Bundles;
----------------------------------------------------------------------- -- properties -- Generic name/value property management -- Copyright (C) 2001, 2002, 2003, 2006, 2008, 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 Ada.Unchecked_Deallocation; with Ada.Unchecked_Conversion; with Ada.Directories; with Ada.Containers.Vectors; with Ada.Strings.Fixed; with Util.Log.Loggers; with Util.Files; package body Util.Properties.Bundles is Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("Util.Properties.Bundles"); procedure Free is new Ada.Unchecked_Deallocation (Manager'Class, Bundle_Manager_Access); -- Implementation of the Bundle -- (this allows to decouples the implementation from the API) package Interface_P is type Manager is new Util.Properties.Interface_P.Manager with private; type Manager_Object_Access is access all Manager; -- Returns TRUE if the property exists. function Exists (Self : in Manager; Name : in Value) return Boolean; -- Returns the property value. Raises an exception if not found. function Get (Self : in Manager; Name : in Value) return Value; procedure Insert (Self : in out Manager; Name : in Value; Item : in Value); -- Set the value of the property. The property is created if it -- does not exists. procedure Set (Self : in out Manager; Name : in Value; Item : in Value); -- Remove the property given its name. procedure Remove (Self : in out Manager; Name : in Value); -- Iterate over the properties and execute the given procedure passing the -- property name and its value. procedure Iterate (Self : in Manager; Process : access procedure (Name, Item : Value)); procedure Load_Properties (Self : in out Manager; File : in String); -- Deep copy of properties stored in 'From' to 'To'. function Create_Copy (Self : in Manager) return Util.Properties.Interface_P.Manager_Access; procedure Delete (Self : in Manager; Obj : in out Util.Properties.Interface_P.Manager_Access); function Get_Names (Self : in Manager; Prefix : in String) return Name_Array; procedure Add_Bundle (Self : in out Manager; Props : in Util.Properties.Manager_Access); private use type Util.Properties.Manager_Access; package PropertyList is new Ada.Containers.Vectors (Element_Type => Util.Properties.Manager_Access, Index_Type => Natural, "=" => "="); type Manager is new Util.Properties.Interface_P.Manager with record List : PropertyList.Vector; Props : aliased Util.Properties.Manager; end record; procedure Free is new Ada.Unchecked_Deallocation (Manager, Manager_Object_Access); end Interface_P; procedure Add_Bundle (Self : in out Manager; Props : in Manager_Access) is use type Util.Properties.Interface_P.Manager_Access; begin Interface_P.Manager'Class (Self.Impl.all).Add_Bundle (Props); end Add_Bundle; procedure Initialize (Object : in out Manager) is use Util.Properties.Interface_P; begin Object.Impl := new Util.Properties.Bundles.Interface_P.Manager; Util.Concurrent.Counters.Increment (Object.Impl.Count); end Initialize; procedure Adjust (Object : in out Manager) is use Util.Properties.Interface_P; begin if Object.Impl = null then Object.Impl := new Util.Properties.Bundles.Interface_P.Manager; end if; Util.Concurrent.Counters.Increment (Object.Impl.Count); end Adjust; -- ------------------------------ -- Initialize the bundle factory and specify where the property files are stored. -- ------------------------------ procedure Initialize (Factory : in out Loader; Path : in String) is begin Log.Info ("Initialize bundle factory to load from {0}", Path); Factory.Path := To_Unbounded_String (Path); end Initialize; -- ------------------------------ -- Load the bundle with the given name and for the given locale name. -- ------------------------------ procedure Load_Bundle (Factory : in out Loader; Name : in String; Locale : in String; Bundle : out Manager'Class) is Found : Boolean := False; begin Log.Info ("Load bundle {0} for language {1}", Name, Locale); Find_Bundle (Factory, Name, Locale, Bundle, Found); if not Found then Load_Bundle (Factory, Name, Found); if not Found then Log.Error ("Bundle {0} not found", Name); raise NO_BUNDLE with "No bundle '" & Name & "'"; end if; Find_Bundle (Factory, Name, Locale, Bundle, Found); if not Found then Log.Error ("Bundle {0} not found", Name); raise NO_BUNDLE with "No bundle '" & Name & "'"; end if; end if; end Load_Bundle; -- ------------------------------ -- Find the bundle with the given name and for the given locale name. -- ------------------------------ procedure Find_Bundle (Factory : in out Loader; Name : in String; Locale : in String; Bundle : out Manager'Class; Found : out Boolean) is use Ada.Strings; use type Util.Properties.Manager_Access; Loc_Name : constant String := '_' & Locale; Last_Pos : Integer := Loc_Name'Last; begin Log.Info ("Looking for bundle {0} and language {1}", Name, Locale); Found := False; Factory.Lock.Read; declare Pos : Bundle_Map.Cursor; begin while Last_Pos + 1 >= Loc_Name'First loop declare Bundle_Name : aliased constant String := Name & Loc_Name (Loc_Name'First .. Last_Pos); begin Log.Debug ("Searching for {0}", Bundle_Name); Pos := Factory.Bundles.Find (Bundle_Name'Unrestricted_Access); if Bundle_Map.Has_Element (Pos) then Bundle.Finalize; Bundle.Impl := Bundle_Map.Element (Pos).Impl; Util.Concurrent.Counters.Increment (Bundle.Impl.Count); Found := True; exit; end if; end; if Last_Pos > Loc_Name'First then Last_Pos := Fixed.Index (Loc_Name, "_", Last_Pos - 1, Backward) - 1; else Last_Pos := Last_Pos - 1; end if; end loop; exception when others => Factory.Lock.Release_Read; raise; end; Factory.Lock.Release_Read; end Find_Bundle; -- ------------------------------ -- Load the bundle with the given name and for the given locale name. -- ------------------------------ procedure Load_Bundle (Factory : in out Loader; Name : in String; Found : out Boolean) is use Ada.Directories; use Ada.Strings; use Util.Strings; use Ada.Containers; use Util.Strings.String_Set; use Bundle_Map; procedure Process_File (Name : in String; File_Path : in String; Done : out Boolean); Path : constant String := To_String (Factory.Path); Pattern : constant String := Name & "*.properties"; Names : Util.Strings.String_Set.Set; procedure Process_File (Name : in String; File_Path : in String; Done : out Boolean) is subtype Cursor is Bundle_Map.Cursor; Base_Name : aliased constant String := Name (Name'First .. Name'Last - 11); Pos : constant Cursor := Factory.Bundles.Find (Base_Name'Unchecked_Access); Bundle_Name : Name_Access; Bundle : Bundle_Manager_Access; begin Log.Debug ("Loading file {0}", File_Path); if Bundle_Map.Has_Element (Pos) then Bundle := Bundle_Map.Element (Pos); else Bundle := new Manager; Bundle_Name := new String '(Base_Name); Factory.Bundles.Include (Key => Bundle_Name, New_Item => Bundle); Names.Insert (Bundle_Name); end if; Interface_P.Manager'Class (Bundle.Impl.all).Load_Properties (File_Path); Found := True; Done := False; end Process_File; begin Log.Info ("Reading bundle {1} in directory {0}", Path, Name); Found := False; Factory.Lock.Write; begin Util.Files.Iterate_Files_Path (Pattern => Pattern, Path => Path, Process => Process_File'Access, Going => Ada.Strings.Backward); -- Link the property files to implement the localization default rules. while Names.Length > 0 loop declare Name_Pos : String_Set.Cursor := Names.First; Bundle_Name : constant Name_Access := String_Set.Element (Name_Pos); Idx : Natural := Fixed.Index (Bundle_Name.all, "_", Backward); Bundle_Pos : constant Bundle_Map.Cursor := Factory.Bundles.Find (Bundle_Name); Bundle : constant Bundle_Manager_Access := Element (Bundle_Pos); begin Names.Delete (Name_Pos); -- Associate the property bundle to the first existing parent -- Ex: message_fr_CA -> message_fr -- message_fr_CA -> message while Idx > 0 loop declare Name : aliased constant String := Bundle_Name (Bundle_Name'First .. Idx - 1); Pos : constant Bundle_Map.Cursor := Factory.Bundles.Find (Name'Unchecked_Access); begin if Bundle_Map.Has_Element (Pos) then Bundle.Add_Bundle (Bundle_Map.Element (Pos).all'Access); Idx := 0; else Idx := Fixed.Index (Bundle_Name.all, "_", Idx - 1, Backward); end if; end; end loop; end; end loop; exception when others => Factory.Lock.Release_Write; raise; end; Factory.Lock.Release_Write; exception when Name_Error => Log.Error ("Cannot read directory: {0}", Path); end Load_Bundle; -- Implementation of the Bundle -- (this allows to decouples the implementation from the API) package body Interface_P is use PropertyList; -- ------------------------------ -- Returns TRUE if the property exists. -- ------------------------------ function Exists (Self : in Manager; Name : in Value) return Boolean is Iter : Cursor := Self.List.First; begin if Self.Props.Exists (Name) then return True; end if; while Has_Element (Iter) loop if Element (Iter).Exists (Name) then return True; end if; Iter := Next (Iter); end loop; return False; end Exists; -- ------------------------------ -- Returns the property value. Raises an exception if not found. -- ------------------------------ function Get (Self : in Manager; Name : in Value) return Value is begin return Self.Props.Get (Name); exception when NO_PROPERTY => declare Iter : Cursor := Self.List.First; begin while Has_Element (Iter) loop begin return Element (Iter).all.Get (Name); exception when NO_PROPERTY => Iter := Next (Iter); end; end loop; end; raise; end Get; procedure Load_Properties (Self : in out Manager; File : in String) is begin Self.Props.Load_Properties (File); end Load_Properties; procedure Insert (Self : in out Manager; Name : in Value; Item : in Value) is pragma Unreferenced (Self); pragma Unreferenced (Name); pragma Unreferenced (Item); begin raise NOT_WRITEABLE with "Bundle is readonly"; end Insert; -- ------------------------------ -- Set the value of the property. The property is created if it -- does not exists. -- ------------------------------ procedure Set (Self : in out Manager; Name : in Value; Item : in Value) is begin raise NOT_WRITEABLE with "Bundle is readonly"; end Set; -- ------------------------------ -- Remove the property given its name. -- ------------------------------ procedure Remove (Self : in out Manager; Name : in Value) is begin raise NOT_WRITEABLE with "Bundle is readonly"; end Remove; -- Iterate over the properties and execute the given procedure passing the -- property name and its value. procedure Iterate (Self : in Manager; Process : access procedure (Name, Item : Value)) is begin raise Program_Error with "Iterate is not implemented on Bundle"; end Iterate; -- ------------------------------ -- Deep copy of properties stored in 'From' to 'To'. -- ------------------------------ function Create_Copy (Self : in Manager) return Util.Properties.Interface_P.Manager_Access is pragma Unreferenced (Self); begin return null; end Create_Copy; procedure Delete (Self : in Manager; Obj : in out Util.Properties.Interface_P.Manager_Access) is pragma Unreferenced (Self); Item : Manager_Object_Access := Manager (Obj.all)'Access; begin Free (Item); end Delete; function Get_Names (Self : in Manager; Prefix : in String) return Name_Array is Result : Name_Array (1 .. 2); Iter : constant Cursor := Self.List.First; begin while Has_Element (Iter) loop declare M : constant Util.Properties.Manager_Access := Element (Iter); N : constant Name_Array := M.Get_Names (Prefix); begin return N; end; end loop; return Result; end Get_Names; procedure Add_Bundle (Self : in out Manager; Props : in Util.Properties.Manager_Access) is begin Self.List.Append (Props); end Add_Bundle; end Interface_P; -- ------------------------------ -- Clear the bundle cache -- ------------------------------ procedure Clear_Cache (Factory : in out Loader) is use Util.Strings; use Bundle_Map; function To_String_Access is new Ada.Unchecked_Conversion (Source => Util.Strings.Name_Access, Target => Ada.Strings.Unbounded.String_Access); begin Log.Info ("Clearing bundle cache"); Factory.Lock.Write; loop declare Pos : Bundle_Map.Cursor := Factory.Bundles.First; Name : Ada.Strings.Unbounded.String_Access; Node : Bundle_Manager_Access; begin exit when not Has_Element (Pos); Node := Element (Pos); Name := To_String_Access (Key (Pos)); Factory.Bundles.Delete (Pos); Free (Node); Free (Name); end; end loop; Factory.Lock.Release_Write; end Clear_Cache; -- ------------------------------ -- Finalize the bundle loader and clear the cache -- ------------------------------ procedure Finalize (Factory : in out Loader) is begin Clear_Cache (Factory); end Finalize; end Util.Properties.Bundles;
Update to use the concurrent counters
Update to use the concurrent counters
Ada
apache-2.0
flottokarotto/ada-util,Letractively/ada-util,Letractively/ada-util,flottokarotto/ada-util
f79a9c46e70079fb5bfc29ef9d6aa97963047c26
src/sys/streams/util-streams-buffered.ads
src/sys/streams/util-streams-buffered.ads
----------------------------------------------------------------------- -- util-streams-buffered -- Buffered streams utilities -- Copyright (C) 2010, 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 Ada.Strings.Unbounded; with Ada.Finalization; -- == Buffered Streams == -- The `Output_Buffer_Stream` and `Input_Buffer_Stream` implement an output -- and input stream respectively which manages an output or input buffer. The data is -- first written to the buffer and when the buffer is full or flushed, it gets written -- to the target output stream. -- -- The `Output_Buffer_Stream` must be initialized to indicate the buffer size as well -- as the target output stream onto which the data will be flushed. For example, a -- pipe stream could be created and configured to use the buffer as follows: -- -- with Util.Streams.Buffered; -- with Util.Streams.Pipes; -- ... -- Pipe : aliased Util.Streams.Pipes.Pipe_Stream; -- Buffer : Util.Streams.Buffered.Output_Buffer_Stream; -- ... -- Buffer.Initialize (Output => Pipe'Unchecked_Access, -- Size => 1024); -- -- In this example, the buffer of 1024 bytes is configured to flush its content to the -- pipe input stream so that what is written to the buffer will be received as input by -- the program. -- The `Output_Buffer_Stream` provides write operation that deal only with binary data -- (`Stream_Element`). To write text, it is best to use the `Print_Stream` type from -- the `Util.Streams.Texts` package as it extends the `Output_Buffer_Stream` and provides -- several operations to write character and strings. -- -- The `Input_Buffer_Stream` must also be initialized to also indicate the buffer size -- and either an input stream or an input content. When configured, the input stream is used -- to fill the input stream buffer. The buffer configuration is very similar as the -- output stream: -- -- with Util.Streams.Buffered; -- with Util.Streams.Pipes; -- ... -- Pipe : aliased Util.Streams.Pipes.Pipe_Stream; -- Buffer : Util.Streams.Buffered.Input_Buffer_Stream; -- ... -- Buffer.Initialize (Input => Pipe'Unchecked_Access, Size => 1024); -- -- In this case, the buffer of 1024 bytes is filled by reading the pipe stream, and thus -- getting the program's output. package Util.Streams.Buffered is pragma Preelaborate; type Buffer_Access is access Ada.Streams.Stream_Element_Array; -- ----------------------- -- Output buffer stream -- ----------------------- -- The <b>Output_Buffer_Stream</b> is an output stream which uses -- an intermediate buffer to write the data. -- -- It is necessary to call <b>Flush</b> to make sure the data -- is written to the target stream. The <b>Flush</b> operation will -- be called when finalizing the output buffer stream. type Output_Buffer_Stream is limited new Output_Stream with private; -- Initialize the stream to write on the given streams. -- An internal buffer is allocated for writing the stream. procedure Initialize (Stream : in out Output_Buffer_Stream; Output : in Output_Stream_Access; Size : in Positive); -- Initialize the stream with a buffer of <b>Size</b> bytes. procedure Initialize (Stream : in out Output_Buffer_Stream; Size : in Positive); -- Close the sink. overriding procedure Close (Stream : in out Output_Buffer_Stream); -- Get the direct access to the buffer. function Get_Buffer (Stream : in Output_Buffer_Stream) return Buffer_Access; -- Write the buffer array to the output stream. overriding procedure Write (Stream : in out Output_Buffer_Stream; Buffer : in Ada.Streams.Stream_Element_Array); -- Flush the buffer by writing on the output stream. -- Raises Data_Error if there is no output stream. overriding procedure Flush (Stream : in out Output_Buffer_Stream); -- Flush the buffer in the <tt>Into</tt> array and return the index of the -- last element (inclusive) in <tt>Last</tt>. procedure Flush (Stream : in out Output_Buffer_Stream; Into : out Ada.Streams.Stream_Element_Array; Last : out Ada.Streams.Stream_Element_Offset); -- Flush the buffer stream to the unbounded string. procedure Flush (Stream : in out Output_Buffer_Stream; Into : out Ada.Strings.Unbounded.Unbounded_String); -- Get the number of element in the stream. function Get_Size (Stream : in Output_Buffer_Stream) return Natural; type Input_Buffer_Stream is limited new Input_Stream with private; -- Initialize the stream to read from the string. procedure Initialize (Stream : in out Input_Buffer_Stream; Content : in String); -- Initialize the stream to read the given streams. procedure Initialize (Stream : in out Input_Buffer_Stream; Input : in Input_Stream_Access; Size : in Positive); -- Fill the buffer by reading the input stream. -- Raises Data_Error if there is no input stream; procedure Fill (Stream : in out Input_Buffer_Stream); -- Read one character from the input stream. procedure Read (Stream : in out Input_Buffer_Stream; Char : out Character); -- 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 Input_Buffer_Stream; Into : out Ada.Streams.Stream_Element_Array; Last : out Ada.Streams.Stream_Element_Offset); -- 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 Input_Buffer_Stream; Into : in out Ada.Strings.Unbounded.Unbounded_String); -- Returns True if the end of the stream is reached. function Is_Eof (Stream : in Input_Buffer_Stream) return Boolean; private use Ada.Streams; type Output_Buffer_Stream is limited new Ada.Finalization.Limited_Controlled and Output_Stream with record -- The buffer where the data is written before being flushed. Buffer : Buffer_Access := null; -- The next write position within the buffer. Write_Pos : Stream_Element_Offset := 0; -- The next read position within the buffer. Read_Pos : Stream_Element_Offset := 1; -- The last valid write position within the buffer. Last : Stream_Element_Offset := 0; -- The output stream to use for flushing the buffer. Output : Output_Stream_Access := null; No_Flush : Boolean := False; end record; -- Flush the stream and release the buffer. overriding procedure Finalize (Object : in out Output_Buffer_Stream); type Input_Buffer_Stream is limited new Ada.Finalization.Limited_Controlled and Input_Stream with record -- The buffer where the data is written before being flushed. Buffer : Buffer_Access := null; -- The next write position within the buffer. Write_Pos : Stream_Element_Offset := 0; -- The next read position within the buffer. Read_Pos : Stream_Element_Offset := 1; -- The last valid write position within the buffer. Last : Stream_Element_Offset := 0; -- The input stream to use to fill the buffer. Input : Input_Stream_Access := null; -- Reached end of file when reading. Eof : Boolean := False; end record; -- Release the buffer. overriding procedure Finalize (Object : in out Input_Buffer_Stream); end Util.Streams.Buffered;
----------------------------------------------------------------------- -- util-streams-buffered -- Buffered streams utilities -- Copyright (C) 2010, 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 Ada.Strings.Unbounded; with Ada.Finalization; -- == Buffered Streams == -- The `Output_Buffer_Stream` and `Input_Buffer_Stream` implement an output -- and input stream respectively which manages an output or input buffer. The data is -- first written to the buffer and when the buffer is full or flushed, it gets written -- to the target output stream. -- -- The `Output_Buffer_Stream` must be initialized to indicate the buffer size as well -- as the target output stream onto which the data will be flushed. For example, a -- pipe stream could be created and configured to use the buffer as follows: -- -- with Util.Streams.Buffered; -- with Util.Streams.Pipes; -- ... -- Pipe : aliased Util.Streams.Pipes.Pipe_Stream; -- Buffer : Util.Streams.Buffered.Output_Buffer_Stream; -- ... -- Buffer.Initialize (Output => Pipe'Unchecked_Access, -- Size => 1024); -- -- In this example, the buffer of 1024 bytes is configured to flush its content to the -- pipe input stream so that what is written to the buffer will be received as input by -- the program. -- The `Output_Buffer_Stream` provides write operation that deal only with binary data -- (`Stream_Element`). To write text, it is best to use the `Print_Stream` type from -- the `Util.Streams.Texts` package as it extends the `Output_Buffer_Stream` and provides -- several operations to write character and strings. -- -- The `Input_Buffer_Stream` must also be initialized to also indicate the buffer size -- and either an input stream or an input content. When configured, the input stream is used -- to fill the input stream buffer. The buffer configuration is very similar as the -- output stream: -- -- with Util.Streams.Buffered; -- with Util.Streams.Pipes; -- ... -- Pipe : aliased Util.Streams.Pipes.Pipe_Stream; -- Buffer : Util.Streams.Buffered.Input_Buffer_Stream; -- ... -- Buffer.Initialize (Input => Pipe'Unchecked_Access, Size => 1024); -- -- In this case, the buffer of 1024 bytes is filled by reading the pipe stream, and thus -- getting the program's output. package Util.Streams.Buffered is pragma Preelaborate; type Buffer_Access is access Ada.Streams.Stream_Element_Array; -- ----------------------- -- Output buffer stream -- ----------------------- -- The <b>Output_Buffer_Stream</b> is an output stream which uses -- an intermediate buffer to write the data. -- -- It is necessary to call <b>Flush</b> to make sure the data -- is written to the target stream. The <b>Flush</b> operation will -- be called when finalizing the output buffer stream. type Output_Buffer_Stream is limited new Output_Stream with private; -- Initialize the stream to write on the given streams. -- An internal buffer is allocated for writing the stream. procedure Initialize (Stream : in out Output_Buffer_Stream; Output : access Output_Stream'Class; Size : in Positive); -- Initialize the stream with a buffer of <b>Size</b> bytes. procedure Initialize (Stream : in out Output_Buffer_Stream; Size : in Positive); -- Close the sink. overriding procedure Close (Stream : in out Output_Buffer_Stream); -- Get the direct access to the buffer. function Get_Buffer (Stream : in Output_Buffer_Stream) return Buffer_Access; -- Write the buffer array to the output stream. overriding procedure Write (Stream : in out Output_Buffer_Stream; Buffer : in Ada.Streams.Stream_Element_Array); -- Flush the buffer by writing on the output stream. -- Raises Data_Error if there is no output stream. overriding procedure Flush (Stream : in out Output_Buffer_Stream); -- Flush the buffer in the <tt>Into</tt> array and return the index of the -- last element (inclusive) in <tt>Last</tt>. procedure Flush (Stream : in out Output_Buffer_Stream; Into : out Ada.Streams.Stream_Element_Array; Last : out Ada.Streams.Stream_Element_Offset); -- Flush the buffer stream to the unbounded string. procedure Flush (Stream : in out Output_Buffer_Stream; Into : out Ada.Strings.Unbounded.Unbounded_String); -- Get the number of element in the stream. function Get_Size (Stream : in Output_Buffer_Stream) return Natural; type Input_Buffer_Stream is limited new Input_Stream with private; -- Initialize the stream to read from the string. procedure Initialize (Stream : in out Input_Buffer_Stream; Content : in String); -- Initialize the stream to read the given streams. procedure Initialize (Stream : in out Input_Buffer_Stream; Input : access Input_Stream'Class; Size : in Positive); -- Fill the buffer by reading the input stream. -- Raises Data_Error if there is no input stream; procedure Fill (Stream : in out Input_Buffer_Stream); -- Read one character from the input stream. procedure Read (Stream : in out Input_Buffer_Stream; Char : out Character); -- 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 Input_Buffer_Stream; Into : out Ada.Streams.Stream_Element_Array; Last : out Ada.Streams.Stream_Element_Offset); -- 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 Input_Buffer_Stream; Into : in out Ada.Strings.Unbounded.Unbounded_String); -- Returns True if the end of the stream is reached. function Is_Eof (Stream : in Input_Buffer_Stream) return Boolean; private use Ada.Streams; type Output_Buffer_Stream is limited new Ada.Finalization.Limited_Controlled and Output_Stream with record -- The buffer where the data is written before being flushed. Buffer : Buffer_Access := null; -- The next write position within the buffer. Write_Pos : Stream_Element_Offset := 0; -- The next read position within the buffer. Read_Pos : Stream_Element_Offset := 1; -- The last valid write position within the buffer. Last : Stream_Element_Offset := 0; -- The output stream to use for flushing the buffer. Output : access Output_Stream'Class; No_Flush : Boolean := False; end record; -- Flush the stream and release the buffer. overriding procedure Finalize (Object : in out Output_Buffer_Stream); type Input_Buffer_Stream is limited new Ada.Finalization.Limited_Controlled and Input_Stream with record -- The buffer where the data is written before being flushed. Buffer : Buffer_Access := null; -- The next write position within the buffer. Write_Pos : Stream_Element_Offset := 0; -- The next read position within the buffer. Read_Pos : Stream_Element_Offset := 1; -- The last valid write position within the buffer. Last : Stream_Element_Offset := 0; -- The input stream to use to fill the buffer. Input : access Input_Stream'Class; -- Reached end of file when reading. Eof : Boolean := False; end record; -- Release the buffer. overriding procedure Finalize (Object : in out Input_Buffer_Stream); end Util.Streams.Buffered;
Use anonymous access type for the input and output streams
Use anonymous access type for the input and output streams
Ada
apache-2.0
stcarrez/ada-util,stcarrez/ada-util
398fd68804f69f8ede1707c244c85e39221dead8
src/security-policies-roles.ads
src/security-policies-roles.ads
----------------------------------------------------------------------- -- security-policies-roles -- Role based policies -- Copyright (C) 2010, 2011, 2012 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Strings.Unbounded; -- == Role Based Security Policy == -- The <tt>Security.Policies.Roles</tt> package implements a role based security policy. -- In this policy, users are assigned one or several roles and permissions are -- associated with roles. A permission is granted if the user has one of the roles required -- by the permission. -- -- === Policy creation === -- An instance of the <tt>Role_Policy</tt> must be created and registered in the policy manager. -- Get or declare the following variables: -- -- Manager : Security.Policies.Policy_Manager; -- Policy : Security.Policies.Roles.Role_Policy_Access; -- -- Create the role policy and register it in the policy manager as follows: -- -- Policy := new Role_Policy; -- Manager.Add_Policy (Policy.all'Access); -- -- === Policy Configuration === -- A role is represented by a name in security configuration files. A role based permission -- is associated with a list of roles. The permission is granted if the user has one of these -- roles. When the role based policy is registered in the policy manager, the following -- XML configuration is used: -- -- <policy-rules> -- <security-role> -- <role-name>admin</role-name> -- </security-role> -- <security-role> -- <role-name>manager</role-name> -- </security-role> -- <role-permission> -- <name>create-workspace</name> -- <role>admin</role> -- <role>manager</role> -- </role-permission> -- ... -- </policy-rules> -- -- This definition declares two roles: <tt>admin</tt> and <tt>manager</tt> -- It defines a permission <b>create-workspace</b> that will be granted if the -- user has either the <b>admin</b> or the <b>manager</b> role. -- -- Each role is identified by a name in the configuration file. It is represented by -- a <tt>Role_Type</tt>. To provide an efficient implementation, the <tt>Role_Type</tt> -- is represented as an integer with a limit of 64 different roles. -- -- === Assigning roles to users === -- A <tt>Security_Context</tt> must be associated with a set of roles before checking the -- permission. This is done by using the <tt>Set_Role_Context</tt> operation: -- -- Security.Policies.Roles.Set_Role_Context (Security.Contexts.Current, "admin"); -- package Security.Policies.Roles is NAME : constant String := "Role-Policy"; -- Each role is represented by a <b>Role_Type</b> number to provide a fast -- and efficient role check. type Role_Type is new Natural range 0 .. 63; for Role_Type'Size use 8; type Role_Type_Array is array (Positive range <>) of Role_Type; -- The <b>Role_Map</b> represents a set of roles which are assigned to a user. -- Each role is represented by a boolean in the map. The implementation is limited -- to 64 roles (the number of different permissions can be higher). type Role_Map is array (Role_Type'Range) of Boolean; pragma Pack (Role_Map); -- ------------------------------ -- Role principal context -- ------------------------------ -- The <tt>Role_Principal_Context</tt> interface must be implemented by the user -- <tt>Principal</tt> to be able to use the role based policy. The role based policy -- controller will first check that the <tt>Principal</tt> implements that interface. -- It uses the <tt>Get_Roles</tt> function to get the current roles assigned to the user. type Role_Principal_Context is limited interface; function Get_Roles (User : in Role_Principal_Context) return Role_Map is abstract; -- ------------------------------ -- Policy context -- ------------------------------ -- The <b>Role_Policy_Context</b> gives security context information that the role -- based policy can use to verify the permission. type Role_Policy_Context is new Policy_Context with record Roles : Role_Map; end record; type Role_Policy_Context_Access is access all Role_Policy_Context'Class; -- Set the roles which are assigned to the user in the security context. -- The role policy will use these roles to verify a permission. procedure Set_Role_Context (Context : in out Security.Contexts.Security_Context'Class; Roles : in Role_Map); -- Set the roles which are assigned to the user in the security context. -- The role policy will use these roles to verify a permission. procedure Set_Role_Context (Context : in out Security.Contexts.Security_Context'Class; Roles : in String); -- ------------------------------ -- Role based policy -- ------------------------------ type Role_Policy is new Policy with private; type Role_Policy_Access is access all Role_Policy'Class; Invalid_Name : exception; -- Get the policy name. overriding function Get_Name (From : in Role_Policy) return String; -- Find the role type associated with the role name identified by <b>Name</b>. -- Raises <b>Invalid_Name</b> if there is no role type. function Find_Role (Manager : in Role_Policy; Name : in String) return Role_Type; -- Get the role name. function Get_Role_Name (Manager : in Role_Policy; Role : in Role_Type) return String; -- Create a role procedure Create_Role (Manager : in out Role_Policy; Name : in String; Role : out Role_Type); -- Get or add a role type for the given name. procedure Add_Role_Type (Manager : in out Role_Policy; Name : in String; Result : out Role_Type); -- Set the roles specified in the <tt>Roles</tt> parameter. Each role is represented by -- its name and multiple roles are separated by ','. -- Raises Invalid_Name if a role was not found. procedure Set_Roles (Manager : in Role_Policy; Roles : in String; Into : out Role_Map); -- Setup the XML parser to read the <b>role-permission</b> description. overriding procedure Prepare_Config (Policy : in out Role_Policy; Reader : in out Util.Serialize.IO.XML.Parser); -- Finalize the policy manager. overriding procedure Finalize (Policy : in out Role_Policy); -- Get the role policy associated with the given policy manager. -- Returns the role policy instance or null if it was not registered in the policy manager. function Get_Role_Policy (Manager : in Security.Policies.Policy_Manager'Class) return Role_Policy_Access; private type Role_Name_Array is array (Role_Type'Range) of Ada.Strings.Unbounded.String_Access; type Role_Policy is new Policy with record Names : Role_Name_Array; Next_Role : Role_Type := Role_Type'First; Name : Util.Beans.Objects.Object; Roles : Role_Type_Array (1 .. Integer (Role_Type'Last)); Count : Natural := 0; end record; end Security.Policies.Roles;
----------------------------------------------------------------------- -- security-policies-roles -- Role based policies -- Copyright (C) 2010, 2011, 2012 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Strings.Unbounded; -- == Role Based Security Policy == -- The <tt>Security.Policies.Roles</tt> package implements a role based security policy. -- In this policy, users are assigned one or several roles and permissions are -- associated with roles. A permission is granted if the user has one of the roles required -- by the permission. -- -- === Policy creation === -- An instance of the <tt>Role_Policy</tt> must be created and registered in the policy manager. -- Get or declare the following variables: -- -- Manager : Security.Policies.Policy_Manager; -- Policy : Security.Policies.Roles.Role_Policy_Access; -- -- Create the role policy and register it in the policy manager as follows: -- -- Policy := new Role_Policy; -- Manager.Add_Policy (Policy.all'Access); -- -- === Policy Configuration === -- A role is represented by a name in security configuration files. A role based permission -- is associated with a list of roles. The permission is granted if the user has one of these -- roles. When the role based policy is registered in the policy manager, the following -- XML configuration is used: -- -- <policy-rules> -- <security-role> -- <role-name>admin</role-name> -- </security-role> -- <security-role> -- <role-name>manager</role-name> -- </security-role> -- <role-permission> -- <name>create-workspace</name> -- <role>admin</role> -- <role>manager</role> -- </role-permission> -- ... -- </policy-rules> -- -- This definition declares two roles: <tt>admin</tt> and <tt>manager</tt> -- It defines a permission <b>create-workspace</b> that will be granted if the -- user has either the <b>admin</b> or the <b>manager</b> role. -- -- Each role is identified by a name in the configuration file. It is represented by -- a <tt>Role_Type</tt>. To provide an efficient implementation, the <tt>Role_Type</tt> -- is represented as an integer with a limit of 64 different roles. -- -- === Assigning roles to users === -- A <tt>Security_Context</tt> must be associated with a set of roles before checking the -- permission. This is done by using the <tt>Set_Role_Context</tt> operation: -- -- Security.Policies.Roles.Set_Role_Context (Security.Contexts.Current, "admin"); -- package Security.Policies.Roles is NAME : constant String := "Role-Policy"; -- Each role is represented by a <b>Role_Type</b> number to provide a fast -- and efficient role check. type Role_Type is new Natural range 0 .. 63; for Role_Type'Size use 8; type Role_Type_Array is array (Positive range <>) of Role_Type; -- The <b>Role_Map</b> represents a set of roles which are assigned to a user. -- Each role is represented by a boolean in the map. The implementation is limited -- to 64 roles (the number of different permissions can be higher). type Role_Map is array (Role_Type'Range) of Boolean; pragma Pack (Role_Map); -- ------------------------------ -- Role principal context -- ------------------------------ -- The <tt>Role_Principal_Context</tt> interface must be implemented by the user -- <tt>Principal</tt> to be able to use the role based policy. The role based policy -- controller will first check that the <tt>Principal</tt> implements that interface. -- It uses the <tt>Get_Roles</tt> function to get the current roles assigned to the user. type Role_Principal_Context is limited interface; function Get_Roles (User : in Role_Principal_Context) return Role_Map is abstract; -- ------------------------------ -- Policy context -- ------------------------------ -- The <b>Role_Policy_Context</b> gives security context information that the role -- based policy can use to verify the permission. type Role_Policy_Context is new Policy_Context with record Roles : Role_Map; end record; type Role_Policy_Context_Access is access all Role_Policy_Context'Class; -- Set the roles which are assigned to the user in the security context. -- The role policy will use these roles to verify a permission. procedure Set_Role_Context (Context : in out Security.Contexts.Security_Context'Class; Roles : in Role_Map); -- Set the roles which are assigned to the user in the security context. -- The role policy will use these roles to verify a permission. procedure Set_Role_Context (Context : in out Security.Contexts.Security_Context'Class; Roles : in String); -- ------------------------------ -- Role based policy -- ------------------------------ type Role_Policy is new Policy with private; type Role_Policy_Access is access all Role_Policy'Class; Invalid_Name : exception; -- Get the policy name. overriding function Get_Name (From : in Role_Policy) return String; -- Find the role type associated with the role name identified by <b>Name</b>. -- Raises <b>Invalid_Name</b> if there is no role type. function Find_Role (Manager : in Role_Policy; Name : in String) return Role_Type; -- Get the role name. function Get_Role_Name (Manager : in Role_Policy; Role : in Role_Type) return String; -- Create a role procedure Create_Role (Manager : in out Role_Policy; Name : in String; Role : out Role_Type); -- Get or add a role type for the given name. procedure Add_Role_Type (Manager : in out Role_Policy; Name : in String; Result : out Role_Type); -- Set the roles specified in the <tt>Roles</tt> parameter. Each role is represented by -- its name and multiple roles are separated by ','. -- Raises Invalid_Name if a role was not found. procedure Set_Roles (Manager : in Role_Policy; Roles : in String; Into : out Role_Map); -- Setup the XML parser to read the <b>role-permission</b> description. overriding procedure Prepare_Config (Policy : in out Role_Policy; Reader : in out Util.Serialize.IO.XML.Parser); -- Finalize the policy manager. overriding procedure Finalize (Policy : in out Role_Policy); -- Get the role policy associated with the given policy manager. -- Returns the role policy instance or null if it was not registered in the policy manager. function Get_Role_Policy (Manager : in Security.Policies.Policy_Manager'Class) return Role_Policy_Access; private type Role_Name_Array is array (Role_Type'Range) of Ada.Strings.Unbounded.String_Access; type Role_Policy is new Policy with record Names : Role_Name_Array := (others => null); Next_Role : Role_Type := Role_Type'First; Name : Util.Beans.Objects.Object; Roles : Role_Type_Array (1 .. Integer (Role_Type'Last)) := (others => 0); Count : Natural := 0; end record; end Security.Policies.Roles;
Fix some default initialization
Fix some default initialization
Ada
apache-2.0
Letractively/ada-security
7332b248c711d787fcfa20c22869118a09eaddeb
src/ado-queries-loaders.adb
src/ado-queries-loaders.adb
----------------------------------------------------------------------- -- ado-queries-loaders -- Loader for Database Queries -- Copyright (C) 2011- 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 Interfaces; with Ada.IO_Exceptions; with Ada.Directories; with Util.Files; with Util.Log.Loggers; with Util.Beans.Objects; with Util.Serialize.IO.XML; with Util.Serialize.Mappers.Record_Mapper; with ADO.Configs; package body ADO.Queries.Loaders is use Util.Log; use ADO.Connections; use Interfaces; use Ada.Calendar; Log : constant Loggers.Logger := Loggers.Create ("ADO.Queries.Loaders"); Base_Time : constant Ada.Calendar.Time := Ada.Calendar.Time_Of (Year => 1970, Month => 1, Day => 1); -- Check for file modification time at most every 60 seconds. FILE_CHECK_DELTA_TIME : constant Unsigned_32 := 60; -- The list of query files defined by the application. Query_Files : Query_File_Access := null; Last_Query : Query_Index := 0; Last_File : File_Index := 0; -- Convert a Time to an Unsigned_32. function To_Unsigned_32 (T : in Ada.Calendar.Time) return Unsigned_32; pragma Inline_Always (To_Unsigned_32); -- Get the modification time of the XML query file associated with the query. function Modification_Time (File : in Query_File_Info) return Unsigned_32; -- Initialize the query SQL pattern with the value procedure Set_Query_Pattern (Into : in out Query_Pattern; Value : in Util.Beans.Objects.Object); -- ------------------------------ -- Register the query definition in the query file. Registration is done -- in the package elaboration phase. -- ------------------------------ procedure Register (File : in Query_File_Access; Query : in Query_Definition_Access) is begin Last_Query := Last_Query + 1; Query.File := File; Query.Next := File.Queries; Query.Query := Last_Query; File.Queries := Query; if File.Next = null and then Query_Files /= File then Last_File := Last_File + 1; File.Next := Query_Files; File.File := Last_File; Query_Files := File; end if; end Register; function Find_Driver (Name : in String) return Integer; function Find_Driver (Name : in String) return Integer is begin if Name'Length = 0 then return 0; end if; declare Driver : constant Connections.Driver_Access := Connections.Get_Driver (Name); begin if Driver = null then -- There is no problem to have an SQL query for unsupported drivers, but still -- report some warning. Log.Warn ("Database driver {0} not found", Name); return -1; end if; return Integer (Driver.Get_Driver_Index); end; end Find_Driver; -- ------------------------------ -- Convert a Time to an Unsigned_32. -- ------------------------------ function To_Unsigned_32 (T : in Ada.Calendar.Time) return Unsigned_32 is D : constant Duration := Duration '(T - Base_Time); begin return Unsigned_32 (D); end To_Unsigned_32; -- ------------------------------ -- Get the modification time of the XML query file associated with the query. -- ------------------------------ function Modification_Time (File : in Query_File_Info) return Unsigned_32 is Path : constant String := To_String (File.Path); begin return To_Unsigned_32 (Ada.Directories.Modification_Time (Path)); exception when Ada.IO_Exceptions.Name_Error => Log.Error ("XML query file '{0}' does not exist", Path); return 0; end Modification_Time; -- ------------------------------ -- Returns True if the XML query file must be reloaded. -- ------------------------------ function Is_Modified (File : in out Query_File_Info) return Boolean is Now : constant Unsigned_32 := To_Unsigned_32 (Ada.Calendar.Clock); begin -- Have we passed the next check time? if File.Next_Check > Now then return False; end if; -- Next check in N seconds (60 by default). File.Next_Check := Now + FILE_CHECK_DELTA_TIME; -- See if the file was changed. declare M : constant Unsigned_32 := Modification_Time (File); begin if File.Last_Modified = M then return False; end if; File.Last_Modified := M; return True; end; end Is_Modified; -- ------------------------------ -- Initialize the query SQL pattern with the value -- ------------------------------ procedure Set_Query_Pattern (Into : in out Query_Pattern; Value : in Util.Beans.Objects.Object) is begin Into.SQL := Util.Beans.Objects.To_Unbounded_String (Value); end Set_Query_Pattern; procedure Read_Query (Manager : in Query_Manager; File : in out Query_File_Info) is type Query_Info_Fields is (FIELD_CLASS_NAME, FIELD_PROPERTY_TYPE, FIELD_PROPERTY_NAME, FIELD_QUERY_NAME, FIELD_SQL_DRIVER, FIELD_SQL, FIELD_SQL_COUNT, FIELD_QUERY); -- The Query_Loader holds context and state information for loading -- the XML query file and initializing the Query_Definition. type Query_Loader is record -- File : Query_File_Access; Hash_Value : Unbounded_String; Query_Def : Query_Definition_Access; Query : Query_Info_Ref.Ref; Driver : Integer; end record; type Query_Loader_Access is access all Query_Loader; procedure Set_Member (Into : in out Query_Loader; Field : in Query_Info_Fields; Value : in Util.Beans.Objects.Object); -- ------------------------------ -- Called by the de-serialization when a given field is recognized. -- ------------------------------ procedure Set_Member (Into : in out Query_Loader; Field : in Query_Info_Fields; Value : in Util.Beans.Objects.Object) is begin case Field is when FIELD_CLASS_NAME => Append (Into.Hash_Value, " class="); Append (Into.Hash_Value, Util.Beans.Objects.To_Unbounded_String (Value)); when FIELD_PROPERTY_TYPE => Append (Into.Hash_Value, " type="); Append (Into.Hash_Value, Util.Beans.Objects.To_Unbounded_String (Value)); when FIELD_PROPERTY_NAME => Append (Into.Hash_Value, " name="); Append (Into.Hash_Value, Util.Beans.Objects.To_Unbounded_String (Value)); when FIELD_QUERY_NAME => Into.Query_Def := Find_Query (File, Util.Beans.Objects.To_String (Value)); Into.Driver := 0; if Into.Query_Def /= null then Into.Query := Query_Info_Ref.Create; end if; when FIELD_SQL_DRIVER => Into.Driver := Find_Driver (Util.Beans.Objects.To_String (Value)); when FIELD_SQL => if not Into.Query.Is_Null and Into.Driver >= 0 and Into.Query_Def /= null then Set_Query_Pattern (Into.Query.Value.Main_Query (Driver_Index (Into.Driver)), Value); end if; Into.Driver := 0; when FIELD_SQL_COUNT => if not Into.Query.Is_Null and Into.Driver >= 0 and Into.Query_Def /= null then Set_Query_Pattern (Into.Query.Value.Count_Query (Driver_Index (Into.Driver)), Value); end if; Into.Driver := 0; when FIELD_QUERY => if Into.Query_Def /= null then -- Now we can safely setup the query info associated with the query definition. Manager.Queries (Into.Query_Def.Query) := Into.Query; end if; Into.Query_Def := null; end case; end Set_Member; package Query_Mapper is new Util.Serialize.Mappers.Record_Mapper (Element_Type => Query_Loader, Element_Type_Access => Query_Loader_Access, Fields => Query_Info_Fields, Set_Member => Set_Member); Loader : aliased Query_Loader; Sql_Mapper : aliased Query_Mapper.Mapper; Reader : Util.Serialize.IO.XML.Parser; Mapper : Util.Serialize.Mappers.Processing; Path : constant String := To_String (File.Path); begin Log.Info ("Reading XML query {0}", Path); -- Loader.File := Into; Loader.Driver := 0; -- Create the mapping to load the XML query file. Sql_Mapper.Add_Mapping ("class/@name", FIELD_CLASS_NAME); Sql_Mapper.Add_Mapping ("class/property/@type", FIELD_PROPERTY_TYPE); Sql_Mapper.Add_Mapping ("class/property/@name", FIELD_PROPERTY_NAME); Sql_Mapper.Add_Mapping ("query/@name", FIELD_QUERY_NAME); Sql_Mapper.Add_Mapping ("query/sql", FIELD_SQL); Sql_Mapper.Add_Mapping ("query/sql/@driver", FIELD_SQL_DRIVER); Sql_Mapper.Add_Mapping ("query/sql-count", FIELD_SQL_COUNT); Sql_Mapper.Add_Mapping ("query/sql-count/@driver", FIELD_SQL_DRIVER); Sql_Mapper.Add_Mapping ("query", FIELD_QUERY); Mapper.Add_Mapping ("query-mapping", Sql_Mapper'Unchecked_Access); -- Set the context for Set_Member. Query_Mapper.Set_Context (Mapper, Loader'Access); -- Read the XML query file. if Ada.Directories.Exists (Path) then Reader.Parse (Path, Mapper); File.Next_Check := To_Unsigned_32 (Ada.Calendar.Clock) + FILE_CHECK_DELTA_TIME; return; end if; if Manager.Loader = null then Log.Error ("XML query file '{0}' does not exist", Path); File.Next_Check := To_Unsigned_32 (Ada.Calendar.Clock) + FILE_CHECK_DELTA_TIME; return; end if; Log.Info ("Loading query {0} from static loader", File.File.Name.all); declare Content : constant access constant String := Manager.Loader (File.File.Name.all); begin if Content /= null then Reader.Parse_String (Content.all, Mapper); else Log.Error ("XML query file '{0}' does not exist", Path); end if; File.Next_Check := To_Unsigned_32 (Ada.Calendar.Clock) + FILE_CHECK_DELTA_TIME; end; end Read_Query; -- ------------------------------ -- Read the query definition. -- ------------------------------ procedure Read_Query (Manager : in Query_Manager; Into : in Query_Definition_Access) is begin if Manager.Queries (Into.Query).Is_Null or else Is_Modified (Manager.Files (Into.File.File)) then Read_Query (Manager, Manager.Files (Into.File.File)); end if; end Read_Query; -- ------------------------------ -- Initialize the queries to look in the list of directories specified by <b>Paths</b>. -- Each search directory is separated by ';' (yes, even on Unix). -- When <b>Load</b> is true, read the XML query file and initialize the query -- definitions from that file. -- ------------------------------ procedure Initialize (Manager : in out Query_Manager; Config : in ADO.Connections.Configuration'Class) is function Get_Config (Name : in String) return String; function Get_Config (Name : in String) return String is Value : constant String := Config.Get_Property (Name); begin if Value'Length > 0 then return Value; else return ADO.Configs.Get_Config (Name); end if; end Get_Config; Paths : constant String := Get_Config (Configs.QUERY_PATHS_CONFIG); Load : constant Boolean := Get_Config (Configs.QUERY_LOAD_CONFIG) = "true"; File : Query_File_Access := Query_Files; begin Log.Info ("Initializing query search paths to {0}", Paths); if Manager.Queries = null then Manager.Queries := new Query_Table (1 .. Last_Query); end if; if Manager.Files = null then Manager.Files := new File_Table (1 .. Last_File); end if; Manager.Driver := Config.Get_Driver; while File /= null loop declare Path : constant String := Util.Files.Find_File_Path (Name => File.Name.all, Paths => Paths); begin Manager.Files (File.File).File := File; Manager.Files (File.File).Last_Modified := 0; Manager.Files (File.File).Next_Check := 0; Manager.Files (File.File).Path := To_Unbounded_String (Path); if Load then Read_Query (Manager, Manager.Files (File.File)); end if; end; File := File.Next; end loop; end Initialize; -- ------------------------------ -- Find the query identified by the given name. -- ------------------------------ function Find_Query (Name : in String) return Query_Definition_Access is File : Query_File_Access := Query_Files; begin while File /= null loop declare Query : Query_Definition_Access := File.Queries; begin while Query /= null loop if Query.Name.all = Name then return Query; end if; Query := Query.Next; end loop; end; File := File.Next; end loop; Log.Warn ("Query {0} not found", Name); return null; end Find_Query; package body File is begin File.Name := Name'Access; File.Sha1_Map := Hash'Access; end File; package body Query is begin Query.Name := Query_Name'Access; Query.File := File; Register (File => File, Query => Query'Access); end Query; end ADO.Queries.Loaders;
----------------------------------------------------------------------- -- ado-queries-loaders -- Loader for Database Queries -- Copyright (C) 2011- 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.IO_Exceptions; with Ada.Directories; with Util.Files; with Util.Log.Loggers; with Util.Beans.Objects; with Util.Serialize.IO.XML; with Util.Serialize.Mappers.Record_Mapper; with ADO.Configs; package body ADO.Queries.Loaders is use Util.Log; use ADO.Connections; use Ada.Calendar; Log : constant Loggers.Logger := Loggers.Create ("ADO.Queries.Loaders"); Init_Time : constant Ada.Calendar.Time := Ada.Calendar.Time_Of (Year => Ada.Calendar.Year_Number'First, Month => 1, Day => 1); Infinity_Time : constant Ada.Calendar.Time := Ada.Calendar.Time_Of (Year => Ada.Calendar.Year_Number'Last, Month => 1, Day => 1); -- Check for file modification time at most every 60 seconds. FILE_CHECK_DELTA_TIME : constant Duration := 60.0; -- The list of query files defined by the application. Query_Files : Query_File_Access := null; Last_Query : Query_Index := 0; Last_File : File_Index := 0; -- Get the modification time of the XML query file associated with the query. function Modification_Time (File : in Query_File_Info) return Ada.Calendar.Time; -- Initialize the query SQL pattern with the value procedure Set_Query_Pattern (Into : in out Query_Pattern; Value : in Util.Beans.Objects.Object); -- ------------------------------ -- Register the query definition in the query file. Registration is done -- in the package elaboration phase. -- ------------------------------ procedure Register (File : in Query_File_Access; Query : in Query_Definition_Access) is begin Last_Query := Last_Query + 1; Query.File := File; Query.Next := File.Queries; Query.Query := Last_Query; File.Queries := Query; if File.Next = null and then Query_Files /= File then Last_File := Last_File + 1; File.Next := Query_Files; File.File := Last_File; Query_Files := File; end if; end Register; function Find_Driver (Name : in String) return Integer; function Find_Driver (Name : in String) return Integer is begin if Name'Length = 0 then return 0; end if; declare Driver : constant Connections.Driver_Access := Connections.Get_Driver (Name); begin if Driver = null then -- There is no problem to have an SQL query for unsupported drivers, but still -- report some warning. Log.Warn ("Database driver {0} not found", Name); return -1; end if; return Integer (Driver.Get_Driver_Index); end; end Find_Driver; -- ------------------------------ -- Get the modification time of the XML query file associated with the query. -- ------------------------------ function Modification_Time (File : in Query_File_Info) return Ada.Calendar.Time is Path : constant String := To_String (File.Path); begin return Ada.Directories.Modification_Time (Path); exception when Ada.IO_Exceptions.Name_Error => Log.Error ("XML query file '{0}' does not exist", Path); return Init_Time; end Modification_Time; -- ------------------------------ -- Returns True if the XML query file must be reloaded. -- ------------------------------ function Is_Modified (File : in out Query_File_Info) return Boolean is Now : constant Ada.Calendar.Time := Ada.Calendar.Clock; begin -- Have we passed the next check time? if File.Next_Check > Now then return False; end if; -- Next check in N seconds (60 by default). File.Next_Check := Now + FILE_CHECK_DELTA_TIME; -- See if the file was changed. declare M : constant Ada.Calendar.Time := Modification_Time (File); begin if File.Last_Modified = M then return False; end if; File.Last_Modified := M; return True; end; end Is_Modified; -- ------------------------------ -- Initialize the query SQL pattern with the value -- ------------------------------ procedure Set_Query_Pattern (Into : in out Query_Pattern; Value : in Util.Beans.Objects.Object) is begin Into.SQL := Util.Beans.Objects.To_Unbounded_String (Value); end Set_Query_Pattern; procedure Read_Query (Manager : in Query_Manager; File : in out Query_File_Info) is type Query_Info_Fields is (FIELD_CLASS_NAME, FIELD_PROPERTY_TYPE, FIELD_PROPERTY_NAME, FIELD_QUERY_NAME, FIELD_SQL_DRIVER, FIELD_SQL, FIELD_SQL_COUNT, FIELD_QUERY); -- The Query_Loader holds context and state information for loading -- the XML query file and initializing the Query_Definition. type Query_Loader is limited record Hash_Value : Unbounded_String; Query_Def : Query_Definition_Access; Query : Query_Info_Ref.Ref; Driver : Integer; end record; type Query_Loader_Access is access all Query_Loader; procedure Set_Member (Into : in out Query_Loader; Field : in Query_Info_Fields; Value : in Util.Beans.Objects.Object); -- ------------------------------ -- Called by the de-serialization when a given field is recognized. -- ------------------------------ procedure Set_Member (Into : in out Query_Loader; Field : in Query_Info_Fields; Value : in Util.Beans.Objects.Object) is begin case Field is when FIELD_CLASS_NAME => Append (Into.Hash_Value, " class="); Append (Into.Hash_Value, Util.Beans.Objects.To_Unbounded_String (Value)); when FIELD_PROPERTY_TYPE => Append (Into.Hash_Value, " type="); Append (Into.Hash_Value, Util.Beans.Objects.To_Unbounded_String (Value)); when FIELD_PROPERTY_NAME => Append (Into.Hash_Value, " name="); Append (Into.Hash_Value, Util.Beans.Objects.To_Unbounded_String (Value)); when FIELD_QUERY_NAME => Into.Query_Def := Find_Query (File, Util.Beans.Objects.To_String (Value)); Into.Driver := 0; if Into.Query_Def /= null then Into.Query := Query_Info_Ref.Create; end if; when FIELD_SQL_DRIVER => Into.Driver := Find_Driver (Util.Beans.Objects.To_String (Value)); when FIELD_SQL => if not Into.Query.Is_Null and Into.Driver >= 0 and Into.Query_Def /= null then Set_Query_Pattern (Into.Query.Value.Main_Query (Driver_Index (Into.Driver)), Value); end if; Into.Driver := 0; when FIELD_SQL_COUNT => if not Into.Query.Is_Null and Into.Driver >= 0 and Into.Query_Def /= null then Set_Query_Pattern (Into.Query.Value.Count_Query (Driver_Index (Into.Driver)), Value); end if; Into.Driver := 0; when FIELD_QUERY => if Into.Query_Def /= null then -- Now we can safely setup the query info associated with the query definition. Manager.Queries (Into.Query_Def.Query) := Into.Query; end if; Into.Query_Def := null; end case; end Set_Member; package Query_Mapper is new Util.Serialize.Mappers.Record_Mapper (Element_Type => Query_Loader, Element_Type_Access => Query_Loader_Access, Fields => Query_Info_Fields, Set_Member => Set_Member); Loader : aliased Query_Loader; Sql_Mapper : aliased Query_Mapper.Mapper; Reader : Util.Serialize.IO.XML.Parser; Mapper : Util.Serialize.Mappers.Processing; Path : constant String := To_String (File.Path); begin Log.Info ("Reading XML query {0}", Path); Loader.Driver := 0; -- Create the mapping to load the XML query file. Sql_Mapper.Add_Mapping ("class/@name", FIELD_CLASS_NAME); Sql_Mapper.Add_Mapping ("class/property/@type", FIELD_PROPERTY_TYPE); Sql_Mapper.Add_Mapping ("class/property/@name", FIELD_PROPERTY_NAME); Sql_Mapper.Add_Mapping ("query/@name", FIELD_QUERY_NAME); Sql_Mapper.Add_Mapping ("query/sql", FIELD_SQL); Sql_Mapper.Add_Mapping ("query/sql/@driver", FIELD_SQL_DRIVER); Sql_Mapper.Add_Mapping ("query/sql-count", FIELD_SQL_COUNT); Sql_Mapper.Add_Mapping ("query/sql-count/@driver", FIELD_SQL_DRIVER); Sql_Mapper.Add_Mapping ("query", FIELD_QUERY); Mapper.Add_Mapping ("query-mapping", Sql_Mapper'Unchecked_Access); -- Set the context for Set_Member. Query_Mapper.Set_Context (Mapper, Loader'Access); -- Read the XML query file. if Ada.Directories.Exists (Path) then Reader.Parse (Path, Mapper); File.Next_Check := Ada.Calendar.Clock + FILE_CHECK_DELTA_TIME; return; end if; if Manager.Loader = null then Log.Error ("XML query file '{0}' does not exist", Path); File.Next_Check := Ada.Calendar.Clock + FILE_CHECK_DELTA_TIME; return; end if; Log.Info ("Loading query {0} from static loader", File.File.Name.all); declare Content : constant access constant String := Manager.Loader (File.File.Name.all); begin if Content /= null then Reader.Parse_String (Content.all, Mapper); File.Next_Check := Infinity_Time; else Log.Error ("XML query file '{0}' does not exist", Path); File.Next_Check := Ada.Calendar.Clock + FILE_CHECK_DELTA_TIME; end if; end; end Read_Query; -- ------------------------------ -- Read the query definition. -- ------------------------------ procedure Read_Query (Manager : in Query_Manager; Into : in Query_Definition_Access) is begin if Manager.Queries (Into.Query).Is_Null or else Is_Modified (Manager.Files (Into.File.File)) then Read_Query (Manager, Manager.Files (Into.File.File)); end if; end Read_Query; -- ------------------------------ -- Initialize the queries to look in the list of directories specified by <b>Paths</b>. -- Each search directory is separated by ';' (yes, even on Unix). -- When <b>Load</b> is true, read the XML query file and initialize the query -- definitions from that file. -- ------------------------------ procedure Initialize (Manager : in out Query_Manager; Config : in ADO.Connections.Configuration'Class) is function Get_Config (Name : in String) return String; function Get_Config (Name : in String) return String is Value : constant String := Config.Get_Property (Name); begin if Value'Length > 0 then return Value; else return ADO.Configs.Get_Config (Name); end if; end Get_Config; Paths : constant String := Get_Config (Configs.QUERY_PATHS_CONFIG); Load : constant Boolean := Get_Config (Configs.QUERY_LOAD_CONFIG) = "true"; File : Query_File_Access := Query_Files; begin Log.Info ("Initializing query search paths to {0}", Paths); if Manager.Queries = null then Manager.Queries := new Query_Table (1 .. Last_Query); end if; if Manager.Files = null then Manager.Files := new File_Table (1 .. Last_File); end if; Manager.Driver := Config.Get_Driver; while File /= null loop declare Path : constant String := Util.Files.Find_File_Path (Name => File.Name.all, Paths => Paths); begin Manager.Files (File.File).File := File; Manager.Files (File.File).Last_Modified := Init_Time; Manager.Files (File.File).Next_Check := Init_Time; Manager.Files (File.File).Path := To_Unbounded_String (Path); if Load then Read_Query (Manager, Manager.Files (File.File)); end if; end; File := File.Next; end loop; end Initialize; -- ------------------------------ -- Find the query identified by the given name. -- ------------------------------ function Find_Query (Name : in String) return Query_Definition_Access is File : Query_File_Access := Query_Files; begin while File /= null loop declare Query : Query_Definition_Access := File.Queries; begin while Query /= null loop if Query.Name.all = Name then return Query; end if; Query := Query.Next; end loop; end; File := File.Next; end loop; Log.Warn ("Query {0} not found", Name); return null; end Find_Query; package body File is begin File.Name := Name'Access; File.Sha1_Map := Hash'Access; end File; package body Query is begin Query.Name := Query_Name'Access; Query.File := File; Register (File => File, Query => Query'Access); end Query; end ADO.Queries.Loaders;
Fix #10: if the XML query is loaded from a static loader, don't check the modification time and set the Next_Check date to the infinity
Fix #10: if the XML query is loaded from a static loader, don't check the modification time and set the Next_Check date to the infinity
Ada
apache-2.0
stcarrez/ada-ado
283ec84440bc5531fb5c04546a46d01090746079
regtests/util-encoders-tests.ads
regtests/util-encoders-tests.ads
----------------------------------------------------------------------- -- util-encodes-tests - Test for encoding -- Copyright (C) 2009, 2010, 2011, 2012, 2016 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Tests; package Util.Encoders.Tests is procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite); type Test is new Util.Tests.Test with null record; procedure Test_Hex (T : in out Test); procedure Test_Base64_Encode (T : in out Test); procedure Test_Base64_Decode (T : in out Test); procedure Test_Base64_URL_Encode (T : in out Test); procedure Test_Base64_URL_Decode (T : in out Test); procedure Test_Encoder (T : in out Test; C : in out Util.Encoders.Encoder); procedure Test_Base64_Benchmark (T : in out Test); procedure Test_SHA1_Encode (T : in out Test); -- Benchmark test for SHA1 procedure Test_SHA1_Benchmark (T : in out Test); -- Test HMAC-SHA1 procedure Test_HMAC_SHA1_RFC2202_T1 (T : in out Test); procedure Test_HMAC_SHA1_RFC2202_T2 (T : in out Test); procedure Test_HMAC_SHA1_RFC2202_T3 (T : in out Test); procedure Test_HMAC_SHA1_RFC2202_T4 (T : in out Test); procedure Test_HMAC_SHA1_RFC2202_T5 (T : in out Test); procedure Test_HMAC_SHA1_RFC2202_T6 (T : in out Test); procedure Test_HMAC_SHA1_RFC2202_T7 (T : in out Test); -- Test encoding leb128. procedure Test_LEB128 (T : in out Test); -- Test encoding leb128 + base64url. procedure Test_Base64_LEB128 (T : in out Test); end Util.Encoders.Tests;
----------------------------------------------------------------------- -- util-encodes-tests - Test for encoding -- Copyright (C) 2009, 2010, 2011, 2012, 2016, 2017 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Tests; package Util.Encoders.Tests is procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite); type Test is new Util.Tests.Test with null record; procedure Test_Hex (T : in out Test); procedure Test_Base64_Encode (T : in out Test); procedure Test_Base64_Decode (T : in out Test); procedure Test_Base64_URL_Encode (T : in out Test); procedure Test_Base64_URL_Decode (T : in out Test); procedure Test_Encoder (T : in out Test; C : in out Util.Encoders.Encoder); procedure Test_Base64_Benchmark (T : in out Test); procedure Test_SHA1_Encode (T : in out Test); procedure Test_SHA256_Encode (T : in out Test); -- Benchmark test for SHA1 procedure Test_SHA1_Benchmark (T : in out Test); -- Test HMAC-SHA1 procedure Test_HMAC_SHA1_RFC2202_T1 (T : in out Test); procedure Test_HMAC_SHA1_RFC2202_T2 (T : in out Test); procedure Test_HMAC_SHA1_RFC2202_T3 (T : in out Test); procedure Test_HMAC_SHA1_RFC2202_T4 (T : in out Test); procedure Test_HMAC_SHA1_RFC2202_T5 (T : in out Test); procedure Test_HMAC_SHA1_RFC2202_T6 (T : in out Test); procedure Test_HMAC_SHA1_RFC2202_T7 (T : in out Test); -- Test encoding leb128. procedure Test_LEB128 (T : in out Test); -- Test encoding leb128 + base64url. procedure Test_Base64_LEB128 (T : in out Test); end Util.Encoders.Tests;
Declare the Test_SHA256_Encode procedure
Declare the Test_SHA256_Encode procedure
Ada
apache-2.0
stcarrez/ada-util,stcarrez/ada-util
05bb123e20e9b35146527489d8f5e6b3c112b573
src/gen-commands-docs.adb
src/gen-commands-docs.adb
----------------------------------------------------------------------- -- gen-commands-docs -- Extract and generate documentation for the project -- Copyright (C) 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 GNAT.Command_Line; with Ada.Text_IO; with Gen.Artifacts.Docs; with Gen.Model.Packages; package body Gen.Commands.Docs is use GNAT.Command_Line; -- ------------------------------ -- Execute the command with the arguments. -- ------------------------------ procedure Execute (Cmd : in Command; Generator : in out Gen.Generator.Handler) is pragma Unreferenced (Cmd); Doc : Gen.Artifacts.Docs.Artifact; M : Gen.Model.Packages.Model_Definition; Arg1 : constant String := Get_Argument; Arg2 : constant String := Get_Argument; Fmt : Gen.Artifacts.Docs.Doc_Format := Gen.Artifacts.Docs.DOC_WIKI_GOOGLE; begin Generator.Read_Project ("dynamo.xml", False); if Arg1'Length = 0 then Generator.Error ("Missing target directory"); return; elsif Arg1 (Arg1'First) /= '-' then if Arg2'Length /= 0 then Generator.Error ("Invalid markup option " & Arg1); return; end if; -- Setup the target directory where the distribution is created. Generator.Set_Result_Directory (Arg1); else if Arg1 = "-markdown" then Fmt := Gen.Artifacts.Docs.DOC_MARKDOWN; elsif Arg1 = "-google" then Fmt := Gen.Artifacts.Docs.DOC_WIKI_GOOGLE; else Generator.Error ("Invalid markup option " & Arg1); return; end if; if Arg2'Length = 0 then Generator.Error ("Missing target directory"); return; end if; Generator.Set_Result_Directory (Arg2); end if; Doc.Set_Format (Fmt); Doc.Prepare (M, Generator); end Execute; -- ------------------------------ -- Write the help associated with the command. -- ------------------------------ procedure Help (Cmd : in Command; Generator : in out Gen.Generator.Handler) is pragma Unreferenced (Cmd, Generator); use Ada.Text_IO; begin Put_Line ("build-doc: Extract and generate the project documentation"); Put_Line ("Usage: build-doc [-markdown|-google] target-dir"); New_Line; Put_Line (" Extract the documentation from the project source files and generate the"); Put_Line (" project documentation. The following files are scanned:"); Put_Line (" - Ada specifications (src/*.ads)"); Put_Line (" - XML configuration files (config/*.xml)"); Put_Line (" - XML database model files (db/*.xml)"); end Help; end Gen.Commands.Docs;
----------------------------------------------------------------------- -- gen-commands-docs -- Extract and generate documentation for the project -- Copyright (C) 2012, 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 GNAT.Command_Line; with Ada.Text_IO; with Gen.Artifacts.Docs; with Gen.Model.Packages; package body Gen.Commands.Docs is use GNAT.Command_Line; -- ------------------------------ -- Execute the command with the arguments. -- ------------------------------ overriding procedure Execute (Cmd : in Command; Name : in String; Args : in Argument_List'Class; Generator : in out Gen.Generator.Handler) is pragma Unreferenced (Cmd); Doc : Gen.Artifacts.Docs.Artifact; M : Gen.Model.Packages.Model_Definition; Arg1 : constant String := Get_Argument; Arg2 : constant String := Get_Argument; Fmt : Gen.Artifacts.Docs.Doc_Format := Gen.Artifacts.Docs.DOC_WIKI_GOOGLE; begin Generator.Read_Project ("dynamo.xml", False); if Arg1'Length = 0 then Generator.Error ("Missing target directory"); return; elsif Arg1 (Arg1'First) /= '-' then if Arg2'Length /= 0 then Generator.Error ("Invalid markup option " & Arg1); return; end if; -- Setup the target directory where the distribution is created. Generator.Set_Result_Directory (Arg1); else if Arg1 = "-markdown" then Fmt := Gen.Artifacts.Docs.DOC_MARKDOWN; elsif Arg1 = "-google" then Fmt := Gen.Artifacts.Docs.DOC_WIKI_GOOGLE; else Generator.Error ("Invalid markup option " & Arg1); return; end if; if Arg2'Length = 0 then Generator.Error ("Missing target directory"); return; end if; Generator.Set_Result_Directory (Arg2); end if; Doc.Set_Format (Fmt); Doc.Prepare (M, Generator); end Execute; -- ------------------------------ -- Write the help associated with the command. -- ------------------------------ overriding procedure Help (Cmd : in Command; Generator : in out Gen.Generator.Handler) is pragma Unreferenced (Cmd, Generator); use Ada.Text_IO; begin Put_Line ("build-doc: Extract and generate the project documentation"); Put_Line ("Usage: build-doc [-markdown|-google] target-dir"); New_Line; Put_Line (" Extract the documentation from the project source files and generate the"); Put_Line (" project documentation. The following files are scanned:"); Put_Line (" - Ada specifications (src/*.ads)"); Put_Line (" - XML configuration files (config/*.xml)"); Put_Line (" - XML database model files (db/*.xml)"); end Help; end Gen.Commands.Docs;
Update to use the new command implementation
Update to use the new command implementation
Ada
apache-2.0
stcarrez/dynamo,stcarrez/dynamo,stcarrez/dynamo
ac3a8a10613d3099d1243cede07e232ce37d9629
matp/src/events/mat-events-tools.adb
matp/src/events/mat-events-tools.adb
----------------------------------------------------------------------- -- mat-events-tools - 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. ----------------------------------------------------------------------- package body MAT.Events.Tools is -- ------------------------------ -- 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 Target_Event_Type is Iter : Target_Event_Cursor := List.First; Event : Target_Event_Type; begin while Target_Event_Vectors.Has_Element (Iter) loop Event := Target_Event_Vectors.Element (Iter); if Event.Index = Kind then return Event; end if; Target_Event_Vectors.Next (Iter); end loop; raise Not_Found; end Find; function "<" (Left, Right : in Frame_Key_Type) return Boolean is begin if Left.Addr < Right.Addr then return True; elsif Left.Addr > Right.Addr then return False; else return Left.Level < Right.Level; end if; end "<"; -- ------------------------------ -- 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) is function "<" (Left, Right : in Event_Info_Type) return Boolean is begin return Left.Count < Right.Count; end "<"; package Sort_Event_Info is new Event_Info_Vectors.Generic_Sorting; Iter : Frame_Event_Info_Cursor := Map.First; Item : Event_Info_Type; begin while Frame_Event_Info_Maps.Has_Element (Iter) loop Item := Frame_Event_Info_Maps.Element (Iter); List.Append (Item); Frame_Event_Info_Maps.Next (Iter); end loop; Sort_Event_Info.Sort (List); end Build_Event_Info; -- ------------------------------ -- Extract from the frame info map, the list of frame event info sorted -- on the frame level and slot size. -- ------------------------------ procedure Build_Frame_Info (Map : in Frame_Event_Info_Map; List : in out Frame_Info_Vector) is function "<" (Left, Right : in Frame_Info_Type) return Boolean; function "<" (Left, Right : in Frame_Info_Type) return Boolean is begin if Left.Key.Level < Right.Key.Level then return True; else return False; end if; end "<"; package Sort_Frame_Info is new Frame_Info_Vectors.Generic_Sorting; Iter : Frame_Event_Info_Cursor := Map.First; Item : Frame_Info_Type; begin while Frame_Event_Info_Maps.Has_Element (Iter) loop Item.Key := Frame_Event_Info_Maps.Key (Iter); Item.Info := Frame_Event_Info_Maps.Element (Iter); List.Append (Item); Frame_Event_Info_Maps.Next (Iter); end loop; Sort_Frame_Info.Sort (List); end Build_Frame_Info; end MAT.Events.Tools;
----------------------------------------------------------------------- -- mat-events-tools - 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. ----------------------------------------------------------------------- package body MAT.Events.Tools is -- ------------------------------ -- 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 Target_Event_Type is Iter : Target_Event_Cursor := List.First; Event : Target_Event_Type; begin while Target_Event_Vectors.Has_Element (Iter) loop Event := Target_Event_Vectors.Element (Iter); if Event.Index = Kind then return Event; end if; Target_Event_Vectors.Next (Iter); end loop; raise Not_Found; end Find; function "<" (Left, Right : in Frame_Key_Type) return Boolean is begin if Left.Addr < Right.Addr then return True; elsif Left.Addr > Right.Addr then return False; else return Left.Level < Right.Level; end if; end "<"; -- ------------------------------ -- Collect statistics information about events. -- ------------------------------ procedure Collect_Info (Into : in out Event_Info_Type; Event : in MAT.Events.Target_Event_Type) is begin Into.Last_Event := Event; if Event.Event = 2 then Into.Malloc_Count := Into.Malloc_Count + 1; Into.Alloc_Size := Into.Alloc_Size + Event.Size; elsif Event.Event = 3 then Into.Realloc_Count := Into.Realloc_Count + 1; Into.Alloc_Size := Into.Alloc_Size + Event.Size; Into.Free_Size := Into.Free_Size + Event.Old_Size; elsif Event.Event = 4 then Into.Free_Count := Into.Free_Count + 1; Into.Free_Size := Into.Free_Size + Event.Size; end if; end Collect_Info; -- ------------------------------ -- 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) is function "<" (Left, Right : in Event_Info_Type) return Boolean is begin return Left.Count < Right.Count; end "<"; package Sort_Event_Info is new Event_Info_Vectors.Generic_Sorting; Iter : Frame_Event_Info_Cursor := Map.First; Item : Event_Info_Type; begin while Frame_Event_Info_Maps.Has_Element (Iter) loop Item := Frame_Event_Info_Maps.Element (Iter); List.Append (Item); Frame_Event_Info_Maps.Next (Iter); end loop; Sort_Event_Info.Sort (List); end Build_Event_Info; -- ------------------------------ -- Extract from the frame info map, the list of frame event info sorted -- on the frame level and slot size. -- ------------------------------ procedure Build_Frame_Info (Map : in Frame_Event_Info_Map; List : in out Frame_Info_Vector) is function "<" (Left, Right : in Frame_Info_Type) return Boolean; function "<" (Left, Right : in Frame_Info_Type) return Boolean is begin if Left.Key.Level < Right.Key.Level then return True; else return False; end if; end "<"; package Sort_Frame_Info is new Frame_Info_Vectors.Generic_Sorting; Iter : Frame_Event_Info_Cursor := Map.First; Item : Frame_Info_Type; begin while Frame_Event_Info_Maps.Has_Element (Iter) loop Item.Key := Frame_Event_Info_Maps.Key (Iter); Item.Info := Frame_Event_Info_Maps.Element (Iter); List.Append (Item); Frame_Event_Info_Maps.Next (Iter); end loop; Sort_Frame_Info.Sort (List); end Build_Frame_Info; end MAT.Events.Tools;
Implement the Collect_Info procedure
Implement the Collect_Info procedure
Ada
apache-2.0
stcarrez/mat,stcarrez/mat,stcarrez/mat
6ce8e718955ae0a689e3c0e773fbbe4199601f5f
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 -- ------------------------------ -- 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 begin 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 begin Ada.Text_IO.Put (Title); end Print_Title; -- ------------------------------ -- Start a new row in a report. -- ------------------------------ overriding procedure Start_Row (Console : in out Console_Type) is begin null; end Start_Row; -- ------------------------------ -- Finish a new row in a report. -- ------------------------------ overriding procedure End_Row (Console : in out Console_Type) is 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 -- ------------------------------ -- 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 begin 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 begin 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 null; end Start_Title; -- ------------------------------ -- Start a new row in a report. -- ------------------------------ overriding procedure Start_Row (Console : in out Console_Type) is begin null; end Start_Row; -- ------------------------------ -- Finish a new row in a report. -- ------------------------------ overriding procedure End_Row (Console : in out Console_Type) is begin Ada.Text_IO.New_Line; end End_Row; end MAT.Consoles.Text;
Implement the Start_Title operation
Implement the Start_Title operation
Ada
apache-2.0
stcarrez/mat,stcarrez/mat,stcarrez/mat
fdad16656825b122a3960b7b88e3db9718b7497c
src/generic/keccak-parallel_keccak_1600.ads
src/generic/keccak-parallel_keccak_1600.ads
with Keccak.Generic_Parallel_Permutation_Parallel_Fallback; with Keccak.Generic_Parallel_Permutation_Serial_Fallback; with Keccak.Keccak_1600; with Keccak.Keccak_1600.Rounds_24; with Keccak.Keccak_1600.Rounds_12; with Keccak.Types; with Interfaces; pragma Elaborate_All (Keccak.Generic_Parallel_Permutation_Parallel_Fallback); pragma Elaborate_All (Keccak.Generic_Parallel_Permutation_Serial_Fallback); -- @brief@ -- Defines procedures for running Keccak-f permutations in parallel for -- 2x, 4x, and 8x parallelism, as well as serial permutations. -- -- @description@ -- -- This package must define the following types and procedures: -- * Permute_S1_R12 - Serial Keccak-p[1600] permutation with 12 rounds. -- * Permute_S1_R24 - Serial Keccak-p[1600] permutation with 24 rounds. -- -- For 2x parallelism: -- * Parallel_State_P2 -- * Init_P2 -- * Permute_All_P2_R12 -- * Permute_All_P2_R24 -- * XOR_Bits_Into_State_Separate_P2 -- * Extract_Bytes_P2 -- -- For 4x parallelism: -- * Parallel_State_P4 -- * Init_P4 -- * Permute_All_P4_R12 -- * Permute_All_P4_R24 -- * XOR_Bits_Into_State_Separate_P4 -- * Extract_Bytes_P4 -- -- For 8x parallelism: -- * Parallel_State_P8 -- * Init_P8 -- * Permute_All_P8_R12 -- * Permute_All_P8_R24 -- * XOR_Bits_Into_State_Separate_P8 -- * Extract_Bytes_P8 -- -- Any other declarations in this package are architecture-specific and should -- not be relied upon. package Keccak.Parallel_Keccak_1600 with SPARK_Mode => On is ---------------------------------------------------------------------------- -- Keccak-f[1600]x2 -- No SIMD available on this architecture. Fall back to serial implementation. package KeccakF_1600_P2 is new Keccak.Generic_Parallel_Permutation_Serial_Fallback (Permutation_State => Keccak_1600.KeccakF_1600.State, Init => Keccak_1600.KeccakF_1600.Init, XOR_Bits_Into_State => Keccak_1600.KeccakF_1600_Lanes.XOR_Bits_Into_State, Extract_Bytes => Keccak_1600.KeccakF_1600_Lanes.Extract_Bytes, State_Size => 1600, Parallelism => 2); subtype Parallel_State_P2 is KeccakF_1600_P2.Parallel_State; procedure Init_P2 (S : out KeccakF_1600_P2.Parallel_State) renames KeccakF_1600_P2.Init; procedure XOR_Bits_Into_State_Separate_P2 (S : in out Parallel_State_P2; Data : in Types.Byte_Array; Data_Offset : in Natural; Bit_Len : in Natural) renames KeccakF_1600_P2.XOR_Bits_Into_State_Separate; procedure XOR_Bits_Into_State_All_P2 (S : in out Parallel_State_P2; Data : in Types.Byte_Array; Bit_Len : in Natural) renames KeccakF_1600_P2.XOR_Bits_Into_State_All; procedure Extract_Bytes_P2 (S : in Parallel_State_P2; Data : in out Types.Byte_Array; Data_Offset : in Natural; Byte_Len : in Natural) renames KeccakF_1600_P2.Extract_Bytes; ---------------------------------------------------------------------------- -- Keccak-f[1600]x4 -- No SIMD available on this architecture. Fall back to serial implementation. package KeccakF_1600_P4 is new Keccak.Generic_Parallel_Permutation_Serial_Fallback (Permutation_State => Keccak_1600.KeccakF_1600.State, Init => Keccak_1600.KeccakF_1600.Init, XOR_Bits_Into_State => Keccak_1600.KeccakF_1600_Lanes.XOR_Bits_Into_State, Extract_Bytes => Keccak_1600.KeccakF_1600_Lanes.Extract_Bytes, State_Size => 1600, Parallelism => 4); subtype Parallel_State_P4 is KeccakF_1600_P4.Parallel_State; procedure Init_P4 (S : out KeccakF_1600_P4.Parallel_State) renames KeccakF_1600_P4.Init; procedure XOR_Bits_Into_State_Separate_P4 (S : in out Parallel_State_P4; Data : in Types.Byte_Array; Data_Offset : in Natural; Bit_Len : in Natural) renames KeccakF_1600_P4.XOR_Bits_Into_State_Separate; procedure XOR_Bits_Into_State_All_P4 (S : in out Parallel_State_P4; Data : in Types.Byte_Array; Bit_Len : in Natural) renames KeccakF_1600_P4.XOR_Bits_Into_State_All; procedure Extract_Bytes_P4 (S : in Parallel_State_P4; Data : in out Types.Byte_Array; Data_Offset : in Natural; Byte_Len : in Natural) renames KeccakF_1600_P4.Extract_Bytes; ---------------------------------------------------------------------------- -- Keccak-f[1600]x8 -- No SIMD available on this architecture. Fall back to serial implementation. package KeccakF_1600_P8 is new Keccak.Generic_Parallel_Permutation_Serial_Fallback (Permutation_State => Keccak_1600.KeccakF_1600.State, Init => Keccak_1600.KeccakF_1600.Init, XOR_Bits_Into_State => Keccak_1600.KeccakF_1600_Lanes.XOR_Bits_Into_State, Extract_Bytes => Keccak_1600.KeccakF_1600_Lanes.Extract_Bytes, State_Size => 1600, Parallelism => 8); subtype Parallel_State_P8 is KeccakF_1600_P8.Parallel_State; procedure Init_P8 (S : out KeccakF_1600_P8.Parallel_State) renames KeccakF_1600_P8.Init; procedure XOR_Bits_Into_State_Separate_P8 (S : in out Parallel_State_P8; Data : in Types.Byte_Array; Data_Offset : in Natural; Bit_Len : in Natural) renames KeccakF_1600_P8.XOR_Bits_Into_State_Separate; procedure XOR_Bits_Into_State_All_P8 (S : in out Parallel_State_P8; Data : in Types.Byte_Array; Bit_Len : in Natural) renames KeccakF_1600_P8.XOR_Bits_Into_State_All; procedure Extract_Bytes_P8 (S : in Parallel_State_P8; Data : in out Types.Byte_Array; Data_Offset : in Natural; Byte_Len : in Natural) renames KeccakF_1600_P8.Extract_Bytes; end Keccak.Parallel_Keccak_1600;
with Keccak.Generic_Parallel_Permutation_Parallel_Fallback; with Keccak.Generic_Parallel_Permutation_Serial_Fallback; with Keccak.Keccak_1600; with Keccak.Keccak_1600.Rounds_24; with Keccak.Keccak_1600.Rounds_12; with Keccak.Types; with Interfaces; pragma Elaborate_All (Keccak.Generic_Parallel_Permutation_Parallel_Fallback); pragma Elaborate_All (Keccak.Generic_Parallel_Permutation_Serial_Fallback); -- @brief@ -- Defines procedures for running Keccak-f permutations in parallel for -- 2x, 4x, and 8x parallelism, as well as serial permutations. -- -- @description@ -- -- This package must define the following types and procedures: -- * Permute_S1_R12 - Serial Keccak-p[1600] permutation with 12 rounds. -- * Permute_S1_R24 - Serial Keccak-p[1600] permutation with 24 rounds. -- -- For 2x parallelism: -- * Parallel_State_P2 -- * Init_P2 -- * Permute_All_P2_R12 -- * Permute_All_P2_R24 -- * XOR_Bits_Into_State_Separate_P2 -- * Extract_Bytes_P2 -- -- For 4x parallelism: -- * Parallel_State_P4 -- * Init_P4 -- * Permute_All_P4_R12 -- * Permute_All_P4_R24 -- * XOR_Bits_Into_State_Separate_P4 -- * Extract_Bytes_P4 -- -- For 8x parallelism: -- * Parallel_State_P8 -- * Init_P8 -- * Permute_All_P8_R12 -- * Permute_All_P8_R24 -- * XOR_Bits_Into_State_Separate_P8 -- * Extract_Bytes_P8 -- -- Any other declarations in this package are architecture-specific and should -- not be relied upon. package Keccak.Parallel_Keccak_1600 with SPARK_Mode => On is ---------------------------------------------------------------------------- -- Keccak-f[1600]x2 -- No SIMD available on this architecture. Fall back to serial implementation. package KeccakF_1600_P2 is new Keccak.Generic_Parallel_Permutation_Serial_Fallback (Permutation_State => Keccak_1600.KeccakF_1600.Lane_Complemented_State, Init => Keccak_1600.KeccakF_1600.Init, XOR_Bits_Into_State => Keccak_1600.KeccakF_1600_Lanes.XOR_Bits_Into_State, Extract_Bytes => Keccak_1600.KeccakF_1600_Lanes.Extract_Bytes, State_Size => 1600, Parallelism => 2); subtype Parallel_State_P2 is KeccakF_1600_P2.Parallel_State; procedure Init_P2 (S : out KeccakF_1600_P2.Parallel_State) renames KeccakF_1600_P2.Init; procedure XOR_Bits_Into_State_Separate_P2 (S : in out Parallel_State_P2; Data : in Types.Byte_Array; Data_Offset : in Natural; Bit_Len : in Natural) renames KeccakF_1600_P2.XOR_Bits_Into_State_Separate; procedure XOR_Bits_Into_State_All_P2 (S : in out Parallel_State_P2; Data : in Types.Byte_Array; Bit_Len : in Natural) renames KeccakF_1600_P2.XOR_Bits_Into_State_All; procedure Extract_Bytes_P2 (S : in Parallel_State_P2; Data : in out Types.Byte_Array; Data_Offset : in Natural; Byte_Len : in Natural) renames KeccakF_1600_P2.Extract_Bytes; ---------------------------------------------------------------------------- -- Keccak-f[1600]x4 -- No SIMD available on this architecture. Fall back to serial implementation. package KeccakF_1600_P4 is new Keccak.Generic_Parallel_Permutation_Serial_Fallback (Permutation_State => Keccak_1600.KeccakF_1600.Lane_Complemented_State, Init => Keccak_1600.KeccakF_1600.Init, XOR_Bits_Into_State => Keccak_1600.KeccakF_1600_Lanes.XOR_Bits_Into_State, Extract_Bytes => Keccak_1600.KeccakF_1600_Lanes.Extract_Bytes, State_Size => 1600, Parallelism => 4); subtype Parallel_State_P4 is KeccakF_1600_P4.Parallel_State; procedure Init_P4 (S : out KeccakF_1600_P4.Parallel_State) renames KeccakF_1600_P4.Init; procedure XOR_Bits_Into_State_Separate_P4 (S : in out Parallel_State_P4; Data : in Types.Byte_Array; Data_Offset : in Natural; Bit_Len : in Natural) renames KeccakF_1600_P4.XOR_Bits_Into_State_Separate; procedure XOR_Bits_Into_State_All_P4 (S : in out Parallel_State_P4; Data : in Types.Byte_Array; Bit_Len : in Natural) renames KeccakF_1600_P4.XOR_Bits_Into_State_All; procedure Extract_Bytes_P4 (S : in Parallel_State_P4; Data : in out Types.Byte_Array; Data_Offset : in Natural; Byte_Len : in Natural) renames KeccakF_1600_P4.Extract_Bytes; ---------------------------------------------------------------------------- -- Keccak-f[1600]x8 -- No SIMD available on this architecture. Fall back to serial implementation. package KeccakF_1600_P8 is new Keccak.Generic_Parallel_Permutation_Serial_Fallback (Permutation_State => Keccak_1600.KeccakF_1600.Lane_Complemented_State, Init => Keccak_1600.KeccakF_1600.Init, XOR_Bits_Into_State => Keccak_1600.KeccakF_1600_Lanes.XOR_Bits_Into_State, Extract_Bytes => Keccak_1600.KeccakF_1600_Lanes.Extract_Bytes, State_Size => 1600, Parallelism => 8); subtype Parallel_State_P8 is KeccakF_1600_P8.Parallel_State; procedure Init_P8 (S : out KeccakF_1600_P8.Parallel_State) renames KeccakF_1600_P8.Init; procedure XOR_Bits_Into_State_Separate_P8 (S : in out Parallel_State_P8; Data : in Types.Byte_Array; Data_Offset : in Natural; Bit_Len : in Natural) renames KeccakF_1600_P8.XOR_Bits_Into_State_Separate; procedure XOR_Bits_Into_State_All_P8 (S : in out Parallel_State_P8; Data : in Types.Byte_Array; Bit_Len : in Natural) renames KeccakF_1600_P8.XOR_Bits_Into_State_All; procedure Extract_Bytes_P8 (S : in Parallel_State_P8; Data : in out Types.Byte_Array; Data_Offset : in Natural; Byte_Len : in Natural) renames KeccakF_1600_P8.Extract_Bytes; end Keccak.Parallel_Keccak_1600;
Fix a build error for ARCH=generic
Fix a build error for ARCH=generic
Ada
bsd-3-clause
damaki/libkeccak