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
8505ebfbb2bd7b8127198a17ce3c5e9afc19f161
regtests/util-http-cookies-tests.adb
regtests/util-http-cookies-tests.adb
----------------------------------------------------------------------- -- util-http-cookies-tests - Unit tests for Cookies -- Copyright (C) 2011, 2012 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Test_Caller; with Util.Log.Loggers; with Util.Measures; with Ada.Strings.Fixed; with Ada.Unchecked_Deallocation; package body Util.Http.Cookies.Tests is use Ada.Strings.Fixed; use Util.Tests; use Util.Log; -- The logger Log : constant Loggers.Logger := Loggers.Create ("ASF.Cookies.Tests"); procedure Free is new Ada.Unchecked_Deallocation (Cookie_Array, Cookie_Array_Access); package Caller is new Util.Test_Caller (Test, "Cookies"); procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is begin Caller.Add_Test (Suite, "Test ASF.Cookies.Create_Cookie", Test_Create_Cookie'Access); Caller.Add_Test (Suite, "Test ASF.Cookies.To_Http_Header", Test_To_Http_Header'Access); Caller.Add_Test (Suite, "Test ASF.Cookies.Get_Cookies", Test_Parse_Http_Header'Access); end Add_Tests; -- ------------------------------ -- Test creation of cookie -- ------------------------------ procedure Test_Create_Cookie (T : in out Test) is C : constant Cookie := Create ("cookie", "value"); begin T.Assert_Equals ("cookie", Get_Name (C), "Invalid name"); T.Assert_Equals ("value", Get_Value (C), "Invalid value"); T.Assert (not Is_Secure (C), "Invalid is_secure"); end Test_Create_Cookie; -- ------------------------------ -- Test conversion of cookie for HTTP header -- ------------------------------ procedure Test_To_Http_Header (T : in out Test) is procedure Test_Cookie (C : in Cookie); procedure Test_Cookie (Name : in String; Value : in String); procedure Test_Cookie (C : in Cookie) is S : constant String := To_Http_Header (C); begin Log.Info ("Cookie {0}: {1}", Get_Name (C), S); T.Assert (S'Length > 0, "Invalid cookie length for: " & S); T.Assert (Index (S, "=") > 0, "Invalid cookie format; " & S); end Test_Cookie; procedure Test_Cookie (Name : in String; Value : in String) is C : Cookie := Create (Name, Value); begin Test_Cookie (C); for I in 1 .. 24 loop Set_Max_Age (C, I * 3600 + I); Test_Cookie (C); end loop; Set_Secure (C, True); Test_Cookie (C); Set_Http_Only (C, True); Test_Cookie (C); Set_Domain (C, "world.com"); Test_Cookie (C); Set_Path (C, "/some-path"); Test_Cookie (C); end Test_Cookie; begin Test_Cookie ("a", "b"); Test_Cookie ("session_id", "79e2317bcabe731e2f681f5725bbc621-&v=1"); Test_Cookie ("p_41_zy", ""); Test_Cookie ("p_34", """quoted\t"""); Test_Cookie ("d", "s"); declare C : Cookie := Create ("cookie-name", "79e2317bcabe731e2f681f5725bbc621"); Start : Util.Measures.Stamp; begin Set_Path (C, "/home"); Set_Domain (C, ".mydomain.example.com"); Set_Max_Age (C, 1000); Set_Http_Only (C, True); Set_Secure (C, True); Set_Comment (C, "some comment"); for I in 1 .. 1000 loop declare S : constant String := To_Http_Header (C); begin if S'Length < 10 then T.Assert (S'Length > 10, "Invalid cookie generation"); end if; end; end loop; Util.Measures.Report (S => Start, Title => "Generation of 1000 cookies"); end; end Test_To_Http_Header; -- ------------------------------ -- Test parsing of client cookie to build a list of Cookie objects -- ------------------------------ procedure Test_Parse_Http_Header (T : in out Test) is procedure Test_Parse (Header : in String; Count : in Natural; Name : in String; Value : in String); -- ------------------------------ -- Parse the header and check for the expected cookie count and verify -- the value of a specific cookie -- ------------------------------ procedure Test_Parse (Header : in String; Count : in Natural; Name : in String; Value : in String) is Start : Util.Measures.Stamp; C : Cookie_Array_Access := Get_Cookies (Header); Found : Boolean := False; begin Util.Measures.Report (S => Start, Title => "Parsing of cookie " & Name); T.Assert (C /= null, "Null value returned by Get_Cookies"); Assert_Equals (T, Count, C'Length, "Invalid count in result array"); for I in C'Range loop Log.Debug ("Cookie: {0}={1}", Get_Name (C (I)), Get_Value (C (I))); if Name = Get_Name (C (I)) then Assert_Equals (T, Value, Get_Value (C (I)), "Invalid cookie: " & Name); Found := True; end if; end loop; T.Assert (Found, "Cookie " & Name & " not found"); Free (C); end Test_Parse; begin Test_Parse ("A=B", 1, "A", "B"); Test_Parse ("A=B=", 1, "A", "B="); Test_Parse ("CONTEXTE=mar=101&nab=84fbbe2a81887732fe9c635d9ac319b5" & "&pfl=afide0&typsrv=we&sc=1&soumar=1011&srcurlconfigchapeau" & "=sous_ouv_formulaire_chapeau_dei_config&nag=550&reg=14505; " & "xtvrn=$354249$354336$; CEPORM=321169600.8782.0000; SES=auth=0&" & "cartridge_url=&return_url=; CEPORC=344500416.8782.0000", 5, "SES", "auth=0&cartridge_url=&return_url="); Test_Parse ("s_nr=1298652863627; s_sq=%5B%5BB%5D%5D; s_cc=true; oraclelicense=" & "accept-dbindex-cookie; gpv_p24=no%20value; gpw_e24=no%20value", 6, "gpw_e24", "no%20value"); -- Parse a set of cookies from microsoft.com Test_Parse ("WT_FPC=id=00.06.036.020-2037773472.29989343:lv=1300442685103:ss=1300442685103; " & "MC1=GUID=9d86c397c1a5ea4cab48d9fe19b76b4e&HASH=97c3&LV=20092&V=3; " & "A=I&I=AxUFAAAAAABwBwAALSllub5HorZBtWWX8ZeXcQ!!&CS=114[3B002j2p[0302g3V309; " & "WT_NVR_RU=0=technet|msdn:1=:2=; mcI=Fri, 31 Dec 2010 10:44:31 GMT; " & "omniID=beb780dd_ab6d_4802_9f37_e33dde280adb; CodeSnippetContainerLang=" & "Visual Basic; MSID=Microsoft.CreationDate=11/09/2010 10:08:25&Microsoft." & "LastVisitDate=03/01/2011 17:08:34&Microsoft.VisitStartDate=03/01/2011 " & "17:08:34&Microsoft.CookieId=882efa27-ee6c-40c5-96ba-2297f985d9e3&Microsoft" & ".TokenId=0c0a5e07-37a6-4ca3-afc0-0edf3de329f6&Microsoft.NumberOfVisits=" & "60&Microsoft.IdentityToken=RojEm8r/0KbCYeKasdfwekl3FtctotD5ocj7WVR72795" & "dBj23rXVz5/xeldkkKHr/NtXFN3xAvczHlHQHKw14/9f/VAraQFIzEYpypGE24z1AuPCzVwU" & "l4HZPnOFH+IA0u2oarcR1n3IMC4Gk8D1UOPBwGlYMB2Xl2W+Up8kJikc4qUxmFG+X5SRrZ3m7" & "LntAv92B4v7c9FPewcQHDSAJAmTOuy7+sl6zEwW2fGWjqGe3G7bh+qqUWPs4LrvSyyi7T3UCW" & "anSWn6jqJInP/MSeAxAvjbTrBwlJlE3AoUfXUJgL81boPYsIXZ30lPpqjMkyc0Jd70dffNNTo5" & "qwkvfFhyOvnfYoQ7dZ0REw+TRA01xHyyUSPINOVgM5Vcu4SdvcUoIlMR3Y097nK+lvx8SqV4UU" & "+QENW1wbBDa7/u6AQqUuk0616tWrBQMR9pYKwYsORUqLkQY5URzhVVA7Py28dLX002Nehqjbh68" & "4xQv/gQYbPZMZUq/wgmPsqA5mJU/lki6A0S/H/ULGbrJE0PBQr8T+Hd+Op4HxEHvjvkTs=&Micr" & "osoft.MicrosoftId=0004-1282-6244-7365; msresearch=%7B%22version%22%3A%224.6" & "%22%2C%22state%22%3A%7B%22name%22%3A%22IDLE%22%2C%22url%22%3Aundefined%2C%2" & "2timestamp%22%3A1296211850175%7D%2C%22lastinvited%22%3A1296211850175%2C%22u" & "serid%22%3A%2212962118501758905232121057759%22%2C%22vendorid%22%3A1%2C%22su" & "rveys%22%3A%5Bundefined%5D%7D; s_sq=%5B%5BB%5D%5D; s_cc=true; " & "GsfxStatsLog=true; GsfxSessionCookie=231210164895294015; ADS=SN=175A21EF;" & ".ASPXANONYMOUS=HJbsF8QczAEkAAAAMGU4YjY4YTctNDJhNy00NmQ3LWJmOWEtNjVjMzFmODY" & "1ZTA5dhasChFIbRm1YpxPXPteSbwdTE01", 15, "s_sq", "%5B%5BB%5D%5D"); end Test_Parse_Http_Header; end Util.Http.Cookies.Tests;
----------------------------------------------------------------------- -- util-http-cookies-tests - Unit tests for Cookies -- Copyright (C) 2011, 2012, 2015 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Test_Caller; with Util.Log.Loggers; with Util.Measures; with Ada.Strings.Fixed; with Ada.Unchecked_Deallocation; package body Util.Http.Cookies.Tests is use Ada.Strings.Fixed; use Util.Tests; use Util.Log; -- The logger Log : constant Loggers.Logger := Loggers.Create ("ASF.Cookies.Tests"); procedure Free is new Ada.Unchecked_Deallocation (Cookie_Array, Cookie_Array_Access); package Caller is new Util.Test_Caller (Test, "Cookies"); procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is begin Caller.Add_Test (Suite, "Test ASF.Cookies.Create_Cookie", Test_Create_Cookie'Access); Caller.Add_Test (Suite, "Test ASF.Cookies.To_Http_Header", Test_To_Http_Header'Access); Caller.Add_Test (Suite, "Test ASF.Cookies.Get_Cookies", Test_Parse_Http_Header'Access); end Add_Tests; -- ------------------------------ -- Test creation of cookie -- ------------------------------ procedure Test_Create_Cookie (T : in out Test) is C : constant Cookie := Create ("cookie", "value"); begin T.Assert_Equals ("cookie", Get_Name (C), "Invalid name"); T.Assert_Equals ("value", Get_Value (C), "Invalid value"); T.Assert (not Is_Secure (C), "Invalid is_secure"); end Test_Create_Cookie; -- ------------------------------ -- Test conversion of cookie for HTTP header -- ------------------------------ procedure Test_To_Http_Header (T : in out Test) is procedure Test_Cookie (C : in Cookie); procedure Test_Cookie (Name : in String; Value : in String); procedure Test_Cookie (C : in Cookie) is S : constant String := To_Http_Header (C); begin Log.Info ("Cookie {0}: {1}", Get_Name (C), S); T.Assert (S'Length > 0, "Invalid cookie length for: " & S); T.Assert (Index (S, "=") > 0, "Invalid cookie format; " & S); end Test_Cookie; procedure Test_Cookie (Name : in String; Value : in String) is C : Cookie := Create (Name, Value); begin Test_Cookie (C); for I in 1 .. 24 loop Set_Max_Age (C, I * 3600 + I); Test_Cookie (C); end loop; Set_Secure (C, True); Test_Cookie (C); Set_Http_Only (C, True); Test_Cookie (C); Set_Domain (C, "world.com"); Test_Cookie (C); Set_Path (C, "/some-path"); Test_Cookie (C); end Test_Cookie; begin Test_Cookie ("a", "b"); Test_Cookie ("session_id", "79e2317bcabe731e2f681f5725bbc621-&v=1"); Test_Cookie ("p_41_zy", ""); Test_Cookie ("p_34", """quoted\t"""); Test_Cookie ("d", "s"); declare C : Cookie := Create ("cookie-name", "79e2317bcabe731e2f681f5725bbc621"); Start : Util.Measures.Stamp; begin Set_Path (C, "/home"); Set_Domain (C, ".mydomain.example.com"); Set_Max_Age (C, 1000); Set_Http_Only (C, True); Set_Secure (C, True); Set_Comment (C, "some comment"); for I in 1 .. 1000 loop declare S : constant String := To_Http_Header (C); begin if S'Length < 10 then T.Assert (S'Length > 10, "Invalid cookie generation"); end if; end; end loop; Util.Measures.Report (S => Start, Title => "Generation of 1000 cookies"); end; end Test_To_Http_Header; -- ------------------------------ -- Test parsing of client cookie to build a list of Cookie objects -- ------------------------------ procedure Test_Parse_Http_Header (T : in out Test) is procedure Test_Parse (Header : in String; Count : in Natural; Name : in String; Value : in String); -- ------------------------------ -- Parse the header and check for the expected cookie count and verify -- the value of a specific cookie -- ------------------------------ procedure Test_Parse (Header : in String; Count : in Natural; Name : in String; Value : in String) is Start : Util.Measures.Stamp; C : Cookie_Array_Access := Get_Cookies (Header); Found : Boolean := False; begin Util.Measures.Report (S => Start, Title => "Parsing of cookie " & Name); T.Assert (C /= null, "Null value returned by Get_Cookies"); Assert_Equals (T, Count, C'Length, "Invalid count in result array"); for I in C'Range loop Log.Debug ("Cookie: {0}={1}", Get_Name (C (I)), Get_Value (C (I))); if Name = Get_Name (C (I)) then Assert_Equals (T, Value, Get_Value (C (I)), "Invalid cookie: " & Name); Found := True; end if; end loop; T.Assert (Found, "Cookie " & Name & " not found"); Free (C); end Test_Parse; begin Test_Parse ("A=B", 1, "A", "B"); Test_Parse ("A=B=", 1, "A", "B="); Test_Parse ("CONTEXTE=mar=101&nab=84fbbe2a81887732fe9c635d9ac319b5" & "&pfl=afide0&typsrv=we&sc=1&soumar=1011&srcurlconfigchapeau" & "=sous_ouv_formulaire_chapeau_dei_config&nag=550&reg=14505; " & "xtvrn=$354249$354336$; CEPORM=321169600.8782.0000; SES=auth=0&" & "cartridge_url=&return_url=; CEPORC=344500416.8782.0000", 5, "SES", "auth=0&cartridge_url=&return_url="); Test_Parse ("s_nr=1298652863627; s_sq=%5B%5BB%5D%5D; s_cc=true; oraclelicense=" & "accept-dbindex-cookie; gpv_p24=no%20value; gpw_e24=no%20value", 6, "gpw_e24", "no%20value"); -- Parse a set of cookies from microsoft.com Test_Parse ("WT_FPC=id=00.06.036.020-2037773472.29989343:lv=1300442685103:ss=1300442685103; " & "MC1=GUID=9d86c397c1a5ea4cab48d9fe19b76b4e&HASH=97c3&LV=20092&V=3; " & "A=I&I=AxUFAAAAAABwBwAALSllub5HorZBtWWX8ZeXcQ!!&CS=114[3B002j2p[0302g3V309; " & "WT_NVR_RU=0=technet|msdn:1=:2=; mcI=Fri, 31 Dec 2010 10:44:31 GMT; " & "omniID=beb780dd_ab6d_4802_9f37_e33dde280adb; CodeSnippetContainerLang=" & "Visual Basic; MSID=Microsoft.CreationDate=11/09/2010 10:08:25&Microsoft." & "LastVisitDate=03/01/2011 17:08:34&Microsoft.VisitStartDate=03/01/2011 " & "17:08:34&Microsoft.CookieId=882efa27-ee6c-40c5-96ba-2297f985d9e3&Microsoft" & ".TokenId=0c0a5e07-37a6-4ca3-afc0-0edf3de329f6&Microsoft.NumberOfVisits=" & "60&Microsoft.IdentityToken=RojEm8r/0KbCYeKasdfwekl3FtctotD5ocj7WVR72795" & "dBj23rXVz5/xeldkkKHr/NtXFN3xAvczHlHQHKw14/9f/VAraQFIzEYpypGE24z1AuPCzVwU" & "l4HZPnOFH+IA0u2oarcR1n3IMC4Gk8D1UOPBwGlYMB2Xl2W+Up8kJikc4qUxmFG+X5SRrZ3m7" & "LntAv92B4v7c9FPewcQHDSAJAmTOuy7+sl6zEwW2fGWjqGe3G7bh+qqUWPs4LrvSyyi7T3UCW" & "anSWn6jqJInP/MSeAxAvjbTrBwlJlE3AoUfXUJgL81boPYsIXZ30lPpqjMkyc0Jd70dffNNTo5" & "qwkvfFhyOvnfYoQ7dZ0REw+TRA01xHyyUSPINOVgM5Vcu4SdvcUoIlMR3Y097nK+lvx8SqV4UU" & "+QENW1wbBDa7/u6AQqUuk0616tWrBQMR9pYKwYsORUqLkQY5URzhVVA7Py28dLX002Nehqjbh68" & "4xQv/gQYbPZMZUq/wgmPsqA5mJU/lki6A0S/H/ULGbrJE0PBQr8T+Hd+Op4HxEHvjvkTs=&Micr" & "osoft.MicrosoftId=0004-1282-6244-7365; msresearch=%7B%22version%22%3A%224.6" & "%22%2C%22state%22%3A%7B%22name%22%3A%22IDLE%22%2C%22url%22%3Aundefined%2C%2" & "2timestamp%22%3A1296211850175%7D%2C%22lastinvited%22%3A1296211850175%2C%22u" & "serid%22%3A%2212962118501758905232121057759%22%2C%22vendorid%22%3A1%2C%22su" & "rveys%22%3A%5Bundefined%5D%7D; s_sq=%5B%5BB%5D%5D; s_cc=true; " & "GsfxStatsLog=true; GsfxSessionCookie=231210164895294015; ADS=SN=175A21EF;" & ".ASPXANONYMOUS=HJbsF8QczAEkAAAAMGU4YjY4YTctNDJhNy00NmQ3LWJmOWEtNjVjMzFmODY" & "1ZTA5dhasChFIbRm1YpxPXPteSbwdTE01", 15, "s_sq", "%5B%5BB%5D%5D"); Test_Parse ("A=B;", 1, "A", "B"); Test_Parse ("A=B; ", 1, "A", "B"); Test_Parse ("A=B; C&3", 1, "A", "B"); Test_Parse ("A=C; C<3=4", 1, "A", "C"); end Test_Parse_Http_Header; end Util.Http.Cookies.Tests;
Add more test for cookies
Add more test for cookies
Ada
apache-2.0
stcarrez/ada-util,stcarrez/ada-util
d6f61dbb76bf4c551da286a8c96f13802d055a75
regtests/wiki-tests.adb
regtests/wiki-tests.adb
----------------------------------------------------------------------- -- Render Tests - Unit tests for AWA Wiki rendering -- Copyright (C) 2013, 2016, 2020 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Text_IO; with Ada.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.Filters.Autolink; with Wiki.Filters.Variables; with Wiki.Plugins.Templates; with Wiki.Plugins.Conditions; with Wiki.Plugins.Variables; 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; Var_Filter : aliased Wiki.Filters.Variables.Variable_Filter; Auto_Filter : aliased Wiki.Filters.Autolink.Autolink_Filter; Template : aliased Wiki.Plugins.Templates.File_Template_Plugin; Condition : aliased Wiki.Plugins.Conditions.Condition_Plugin; Variables : aliased Wiki.Plugins.Variables.Variable_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; elsif Name = "set" then return Variables'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 (Auto_Filter'Unchecked_Access); Engine.Add_Filter (Html_Filter'Unchecked_Access); Engine.Add_Filter (Var_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; elsif Ext = "markdown" then Format := Wiki.SYNTAX_MARKDOWN; 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, 2020 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Text_IO; with Ada.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.Filters.Autolink; with Wiki.Filters.Variables; with Wiki.Plugins.Templates; with Wiki.Plugins.Conditions; with Wiki.Plugins.Variables; 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; Var_Filter : aliased Wiki.Filters.Variables.Variable_Filter; Auto_Filter : aliased Wiki.Filters.Autolink.Autolink_Filter; Template : aliased Wiki.Plugins.Templates.File_Template_Plugin; Condition : aliased Wiki.Plugins.Conditions.Condition_Plugin; Variables : aliased Wiki.Plugins.Variables.Variable_Plugin; List_Vars : aliased Wiki.Plugins.Variables.List_Variable_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; elsif Name = "set" then return Variables'Unchecked_Access; elsif Name = "list" then return List_Vars'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 (Auto_Filter'Unchecked_Access); Engine.Add_Filter (Html_Filter'Unchecked_Access); Engine.Add_Filter (Var_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; elsif Ext = "markdown" then Format := Wiki.SYNTAX_MARKDOWN; 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;
Declare the List_Variable_Plugin and allow to retrieve it with the plugin factory
Declare the List_Variable_Plugin and allow to retrieve it with the plugin factory
Ada
apache-2.0
stcarrez/ada-wiki,stcarrez/ada-wiki
9e5df7fab5a6c84ff9a354e11ed87177374f36bd
regtests/wiki-tests.adb
regtests/wiki-tests.adb
----------------------------------------------------------------------- -- Render Tests - Unit tests for AWA Wiki rendering -- Copyright (C) 2013, 2016 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Text_IO; with Ada.Directories; with Ada.Characters.Conversions; with Util.Files; with Util.Measures; with Wiki.Render.Wiki; with Wiki.Filters.Html; with Wiki.Streams.Html.Builders; with Wiki.Streams.Builders; with Wiki.Utils; with Wiki.Nodes; 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 function To_Wide (Item : in String) return Wide_Wide_String renames Ada.Characters.Conversions.To_Wide_Wide_String; Result_File : constant String := To_String (T.Result); Content : Unbounded_String; begin Util.Files.Read_File (Path => To_String (T.File), Into => Content, Max_Size => 10000); declare Time : Util.Measures.Stamp; begin if T.Source = Wiki.SYNTAX_HTML then declare Html_Filter : aliased Wiki.Filters.Html.Html_Filter_Type; Writer : aliased Wiki.Streams.Builders.Output_Builder_Stream; Renderer : aliased Wiki.Render.Wiki.Wiki_Renderer; Doc : Wiki.Nodes.Document; Engine : Wiki.Parsers.Parser; begin Renderer.Set_Output_Stream (Writer'Unchecked_Access, T.Format); Engine.Add_Filter (Html_Filter'Unchecked_Access); Engine.Set_Syntax (Wiki.SYNTAX_HTML); Engine.Parse (To_Wide (To_String (Content)), Doc); Renderer.Render (Doc); Content := To_Unbounded_String (Writer.To_String); end; elsif T.Is_Html then Content := To_Unbounded_String (Utils.To_Html (To_Wide (To_String (Content)), T.Format)); else Content := To_Unbounded_String (Utils.To_Text (To_Wide (To_String (Content)), T.Format)); end if; Util.Measures.Report (Time, "Render " & To_String (T.Name)); end; Util.Files.Write_File (Result_File, Content); Util.Tests.Assert_Equal_Files (T => T, Expect => To_String (T.Expect), Test => Result_File, Message => "Render"); end Test_Render; -- ------------------------------ -- Test case name -- ------------------------------ overriding function Name (T : in Test) return Util.Tests.Message_String is begin if T.Source = Wiki.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 Ada.Characters.Conversions; with Util.Files; with Util.Measures; with Wiki.Render.Wiki; with Wiki.Filters.Html; with Wiki.Streams.Html.Builders; with Wiki.Streams.Builders; with Wiki.Utils; with Wiki.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 function To_Wide (Item : in String) return Wide_Wide_String renames Ada.Characters.Conversions.To_Wide_Wide_String; Result_File : constant String := To_String (T.Result); Content : Unbounded_String; begin Util.Files.Read_File (Path => To_String (T.File), Into => Content, Max_Size => 10000); declare Time : Util.Measures.Stamp; begin if T.Source = Wiki.SYNTAX_HTML then declare Html_Filter : aliased Wiki.Filters.Html.Html_Filter_Type; Writer : aliased Wiki.Streams.Builders.Output_Builder_Stream; Renderer : aliased Wiki.Render.Wiki.Wiki_Renderer; Doc : Wiki.Documents.Document; Engine : Wiki.Parsers.Parser; begin Renderer.Set_Output_Stream (Writer'Unchecked_Access, T.Format); Engine.Add_Filter (Html_Filter'Unchecked_Access); Engine.Set_Syntax (Wiki.SYNTAX_HTML); Engine.Parse (To_Wide (To_String (Content)), Doc); Renderer.Render (Doc); Content := To_Unbounded_String (Writer.To_String); end; elsif T.Is_Html then Content := To_Unbounded_String (Utils.To_Html (To_Wide (To_String (Content)), T.Format)); else Content := To_Unbounded_String (Utils.To_Text (To_Wide (To_String (Content)), T.Format)); end if; Util.Measures.Report (Time, "Render " & To_String (T.Name)); end; Util.Files.Write_File (Result_File, Content); Util.Tests.Assert_Equal_Files (T => T, Expect => To_String (T.Expect), Test => Result_File, Message => "Render"); end Test_Render; -- ------------------------------ -- Test case name -- ------------------------------ overriding function Name (T : in Test) return Util.Tests.Message_String is begin if T.Source = Wiki.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;
Use Wiki.Documents.Document type
Use Wiki.Documents.Document type
Ada
apache-2.0
stcarrez/ada-wiki,stcarrez/ada-wiki
a2822744567ddbaf50d8ba15a2f188eb71283cbb
mat/src/memory/mat-memory-targets.ads
mat/src/memory/mat-memory-targets.ads
----------------------------------------------------------------------- -- Memory clients - Client info related to its memory -- Copyright (C) 2014 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with MAT.Frames; with MAT.Readers; with MAT.Memory.Tools; with MAT.Expressions; package MAT.Memory.Targets is -- Define some global statistics about the memory slots. type Memory_Stat is record Thread_Count : Natural := 0; Total_Alloc : MAT.Types.Target_Size := 0; Total_Free : MAT.Types.Target_Size := 0; Malloc_Count : Natural := 0; Free_Count : Natural := 0; Realloc_Count : Natural := 0; end record; type Target_Memory is tagged limited private; type Client_Memory_Ref is access all Target_Memory; -- Initialize the target memory object to manage the memory slots, the stack frames -- and setup the reader to analyze the memory events. procedure Initialize (Memory : in out Target_Memory; Reader : in out MAT.Readers.Manager_Base'Class); -- Take into account a malloc probe. The memory slot [Addr .. Slot.Size] is inserted -- in the used slots map. The freed slots that intersect the malloc'ed region are -- removed from the freed map. procedure Probe_Malloc (Memory : in out Target_Memory; Addr : in MAT.Types.Target_Addr; Slot : in Allocation); -- Take into account a free probe. Add the memory slot in the freed map and remove -- the slot from the used slots map. procedure Probe_Free (Memory : in out Target_Memory; Addr : in MAT.Types.Target_Addr; Slot : in Allocation); -- Take into account a realloc probe. The old memory slot represented by Old_Addr is -- removed from the used slots maps and the new memory slot [Addr .. Slot.Size] is -- inserted in the used slots map. procedure Probe_Realloc (Memory : in out Target_Memory; Addr : in MAT.Types.Target_Addr; Old_Addr : in MAT.Types.Target_Addr; Slot : in Allocation); -- Insert in the frame tree the new stack frame represented by <tt>Pc</tt>. -- If the frame is already known, the frame reference counter is incremented. -- The frame represented by <tt>Pc</tt> is returned in <tt>Result</tt>. procedure Create_Frame (Memory : in out Target_Memory; Pc : in MAT.Frames.Frame_Table; Result : out MAT.Frames.Frame_Type); -- Collect the information about memory slot sizes allocated by the application. procedure Size_Information (Memory : in out Target_Memory; Sizes : in out MAT.Memory.Tools.Size_Info_Map); -- Collect the information about threads and the memory allocations they've made. procedure Thread_Information (Memory : in out Target_Memory; Threads : in out Memory_Info_Map); -- Collect the information about frames and the memory allocations they've made. procedure Frame_Information (Memory : in out Target_Memory; Level : in Natural; Frames : in out Frame_Info_Map); -- Get the global memory and allocation statistics. procedure Stat_Information (Memory : in out Target_Memory; Result : out Memory_Stat); -- Find from the <tt>Memory</tt> map the memory slots whose address intersects -- the region [From .. To] and which is selected by the given filter expression. -- Add the memory slot in the <tt>Into</tt> list if it does not already contains -- the memory slot. procedure Find (Memory : in out Target_Memory; From : in MAT.Types.Target_Addr; To : in MAT.Types.Target_Addr; Filter : in MAT.Expressions.Expression_Type; Into : in out MAT.Memory.Allocation_Map); private protected type Memory_Allocator is -- Take into account a malloc probe. The memory slot [Addr .. Slot.Size] is inserted -- in the used slots map. The freed slots that intersect the malloc'ed region are -- removed from the freed map. procedure Probe_Malloc (Addr : in MAT.Types.Target_Addr; Slot : in Allocation); -- Take into account a free probe. Add the memory slot in the freed map and remove -- the slot from the used slots map. procedure Probe_Free (Addr : in MAT.Types.Target_Addr; Slot : in Allocation); -- Take into account a realloc probe. The old memory slot represented by Old_Addr is -- removed from the used slots maps and the new memory slot [Addr .. Slot.Size] is -- inserted in the used slots map. procedure Probe_Realloc (Addr : in MAT.Types.Target_Addr; Old_Addr : in MAT.Types.Target_Addr; Slot : in Allocation); -- Insert in the frame tree the new stack frame represented by <tt>Pc</tt>. -- If the frame is already known, the frame reference counter is incremented. -- The frame represented by <tt>Pc</tt> is returned in <tt>Result</tt>. procedure Create_Frame (Pc : in MAT.Frames.Frame_Table; Result : out MAT.Frames.Frame_Type); -- Collect the information about memory slot sizes allocated by the application. procedure Size_Information (Sizes : in out MAT.Memory.Tools.Size_Info_Map); -- Collect the information about threads and the memory allocations they've made. procedure Thread_Information (Threads : in out Memory_Info_Map); -- Collect the information about frames and the memory allocations they've made. procedure Frame_Information (Level : in Natural; Frames : in out Frame_Info_Map); -- Find from the <tt>Memory</tt> map the memory slots whose address intersects -- the region [From .. To] and which is selected by the given filter expression. -- Add the memory slot in the <tt>Into</tt> list if it does not already contains -- the memory slot. procedure Find (From : in MAT.Types.Target_Addr; To : in MAT.Types.Target_Addr; Filter : in MAT.Expressions.Expression_Type; Into : in out MAT.Memory.Allocation_Map); -- Get the global memory and allocation statistics. procedure Stat_Information (Result : out Memory_Stat); private Used_Slots : Allocation_Map; Freed_Slots : Allocation_Map; Stats : Memory_Stat; Frames : MAT.Frames.Frame_Type := MAT.Frames.Create_Root; end Memory_Allocator; type Target_Memory is tagged limited record Reader : MAT.Readers.Reader_Access; Memory : Memory_Allocator; end record; end MAT.Memory.Targets;
----------------------------------------------------------------------- -- Memory clients - Client info related to its memory -- Copyright (C) 2014 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with MAT.Frames; with MAT.Readers; with MAT.Memory.Tools; with MAT.Expressions; package MAT.Memory.Targets is -- Define some global statistics about the memory slots. type Memory_Stat is record Thread_Count : Natural := 0; Total_Alloc : MAT.Types.Target_Size := 0; Total_Free : MAT.Types.Target_Size := 0; Malloc_Count : Natural := 0; Free_Count : Natural := 0; Realloc_Count : Natural := 0; end record; type Target_Memory is tagged limited private; type Client_Memory_Ref is access all Target_Memory; -- Initialize the target memory object to manage the memory slots, the stack frames -- and setup the reader to analyze the memory events. procedure Initialize (Memory : in out Target_Memory; Reader : in out MAT.Readers.Manager_Base'Class); -- Take into account a malloc probe. The memory slot [Addr .. Slot.Size] is inserted -- in the used slots map. The freed slots that intersect the malloc'ed region are -- removed from the freed map. procedure Probe_Malloc (Memory : in out Target_Memory; Addr : in MAT.Types.Target_Addr; Slot : in Allocation); -- Take into account a free probe. Add the memory slot in the freed map and remove -- the slot from the used slots map. procedure Probe_Free (Memory : in out Target_Memory; Addr : in MAT.Types.Target_Addr; Slot : in Allocation); -- Take into account a realloc probe. The old memory slot represented by Old_Addr is -- removed from the used slots maps and the new memory slot [Addr .. Slot.Size] is -- inserted in the used slots map. procedure Probe_Realloc (Memory : in out Target_Memory; Addr : in MAT.Types.Target_Addr; Old_Addr : in MAT.Types.Target_Addr; Slot : in Allocation); -- Insert in the frame tree the new stack frame represented by <tt>Pc</tt>. -- If the frame is already known, the frame reference counter is incremented. -- The frame represented by <tt>Pc</tt> is returned in <tt>Result</tt>. procedure Create_Frame (Memory : in out Target_Memory; Pc : in MAT.Frames.Frame_Table; Result : out MAT.Frames.Frame_Type); -- Collect the information about memory slot sizes allocated by the application. procedure Size_Information (Memory : in out Target_Memory; Sizes : in out MAT.Memory.Tools.Size_Info_Map); -- Collect the information about threads and the memory allocations they've made. procedure Thread_Information (Memory : in out Target_Memory; Threads : in out Memory_Info_Map); -- Collect the information about frames and the memory allocations they've made. procedure Frame_Information (Memory : in out Target_Memory; Level : in Natural; Frames : in out Frame_Info_Map); -- Get the global memory and allocation statistics. procedure Stat_Information (Memory : in out Target_Memory; Result : out Memory_Stat); -- Find from the <tt>Memory</tt> map the memory slots whose address intersects -- the region [From .. To] and which is selected by the given filter expression. -- Add the memory slot in the <tt>Into</tt> list if it does not already contains -- the memory slot. procedure Find (Memory : in out Target_Memory; From : in MAT.Types.Target_Addr; To : in MAT.Types.Target_Addr; Filter : in MAT.Expressions.Expression_Type; Into : in out MAT.Memory.Allocation_Map); private protected type Memory_Allocator is -- Add the memory region from the list of memory region managed by the program. procedure Add_Region (Region : in Region_Info); -- Take into account a malloc probe. The memory slot [Addr .. Slot.Size] is inserted -- in the used slots map. The freed slots that intersect the malloc'ed region are -- removed from the freed map. procedure Probe_Malloc (Addr : in MAT.Types.Target_Addr; Slot : in Allocation); -- Take into account a free probe. Add the memory slot in the freed map and remove -- the slot from the used slots map. procedure Probe_Free (Addr : in MAT.Types.Target_Addr; Slot : in Allocation); -- Take into account a realloc probe. The old memory slot represented by Old_Addr is -- removed from the used slots maps and the new memory slot [Addr .. Slot.Size] is -- inserted in the used slots map. procedure Probe_Realloc (Addr : in MAT.Types.Target_Addr; Old_Addr : in MAT.Types.Target_Addr; Slot : in Allocation); -- Insert in the frame tree the new stack frame represented by <tt>Pc</tt>. -- If the frame is already known, the frame reference counter is incremented. -- The frame represented by <tt>Pc</tt> is returned in <tt>Result</tt>. procedure Create_Frame (Pc : in MAT.Frames.Frame_Table; Result : out MAT.Frames.Frame_Type); -- Collect the information about memory slot sizes allocated by the application. procedure Size_Information (Sizes : in out MAT.Memory.Tools.Size_Info_Map); -- Collect the information about threads and the memory allocations they've made. procedure Thread_Information (Threads : in out Memory_Info_Map); -- Collect the information about frames and the memory allocations they've made. procedure Frame_Information (Level : in Natural; Frames : in out Frame_Info_Map); -- Find from the <tt>Memory</tt> map the memory slots whose address intersects -- the region [From .. To] and which is selected by the given filter expression. -- Add the memory slot in the <tt>Into</tt> list if it does not already contains -- the memory slot. procedure Find (From : in MAT.Types.Target_Addr; To : in MAT.Types.Target_Addr; Filter : in MAT.Expressions.Expression_Type; Into : in out MAT.Memory.Allocation_Map); -- Get the global memory and allocation statistics. procedure Stat_Information (Result : out Memory_Stat); private Used_Slots : Allocation_Map; Freed_Slots : Allocation_Map; Regions : Region_Info_Map; Stats : Memory_Stat; Frames : MAT.Frames.Frame_Type := MAT.Frames.Create_Root; end Memory_Allocator; type Target_Memory is tagged limited record Reader : MAT.Readers.Reader_Access; Memory : Memory_Allocator; end record; end MAT.Memory.Targets;
Define the protected operation Add_Region
Define the protected operation Add_Region
Ada
apache-2.0
stcarrez/mat,stcarrez/mat,stcarrez/mat
53b1d5c7a7720c78f0200f149ede1834c7010e6e
mat/src/mat-commands.ads
mat/src/mat-commands.ads
----------------------------------------------------------------------- -- mat-commands -- Command support and execution -- 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 GNAT.Sockets; with MAT.Targets; package MAT.Commands is Stop_Interp : exception; -- The options that can be configured through the command line. type Options_Type is record Interactive : Boolean := True; Graphical : Boolean := False; Address : GNAT.Sockets.Sock_Addr_Type := (Port => 4096, others => <>); end record; -- Procedure that defines a command handler. type Command_Handler is access procedure (Target : in out MAT.Targets.Target_Type'Class; Args : in String); -- Execute the command given in the line. procedure Execute (Target : in out MAT.Targets.Target_Type'Class; Line : in String); -- Enter in the interactive loop reading the commands from the standard input -- and executing the commands. procedure Interactive (Target : in out MAT.Targets.Target_Type'Class); -- Parse the command line arguments and configure the target instance. procedure Initialize_Options (Target : in out MAT.Targets.Target_Type'Class; Options : in out Options_Type); -- Convert the string to a socket address. The string can have two forms: -- port -- host:port function To_Sock_Addr_Type (Param : in String) return GNAT.Sockets.Sock_Addr_Type; end MAT.Commands;
----------------------------------------------------------------------- -- mat-commands -- Command support and execution -- 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 GNAT.Sockets; with MAT.Targets; package MAT.Commands is Stop_Interp : exception; -- The options that can be configured through the command line. type Options_Type is record Interactive : Boolean := True; Graphical : Boolean := False; Address : GNAT.Sockets.Sock_Addr_Type := (Port => 4096, others => <>); end record; -- Procedure that defines a command handler. type Command_Handler is access procedure (Target : in out MAT.Targets.Target_Type'Class; Args : in String); -- Execute the command given in the line. procedure Execute (Target : in out MAT.Targets.Target_Type'Class; Line : in String); -- Enter in the interactive loop reading the commands from the standard input -- and executing the commands. procedure Interactive (Target : in out MAT.Targets.Target_Type'Class); -- Parse the command line arguments and configure the target instance. procedure Initialize_Options (Target : in out MAT.Targets.Target_Type'Class; Options : in out Options_Type); -- Convert the string to a socket address. The string can have two forms: -- port -- host:port function To_Sock_Addr_Type (Param : in String) return GNAT.Sockets.Sock_Addr_Type; -- Print the application usage. procedure Usage; end MAT.Commands;
Declare the Usage procedure
Declare the Usage procedure
Ada
apache-2.0
stcarrez/mat,stcarrez/mat,stcarrez/mat
6ac275023cfeed42e24209cb51f32d561be73a0c
src/asf-components-utils-factory.adb
src/asf-components-utils-factory.adb
----------------------------------------------------------------------- -- core-factory -- Factory for Core UI Components -- Copyright (C) 2009, 2010, 2011, 2012, 2013, 2014, 2015, 2016, 2018 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Calendar; with Ada.Exceptions; with Ada.Strings.Maps; with ASF.Views.Nodes; with ASF.Locales; with ASF.Components.Utils.Files; with ASF.Components.Utils.Flush; with ASF.Components.Utils.Scripts; with ASF.Components.Utils.Escapes; with ASF.Components.Utils.Beans; with ASF.Components.Html.Messages; with ASF.Applications.Main; with Util.Log.Loggers; with Util.Properties.Bundles; with Util.Dates.Formats; with Util.Dates.ISO8601; with Util.Beans.Objects.Time; with Util.Locales; with Util.Encoders.SHA256; with Util.Strings.Transforms; use Util.Strings; package body ASF.Components.Utils.Factory is use ASF.Components.Base; -- The logger Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("ASF.Components.Utils.Factory"); function Create_File return UIComponent_Access; function Create_Flush return UIComponent_Access; function Create_Script return UIComponent_Access; function Create_Escape return UIComponent_Access; function Create_Set return UIComponent_Access; -- ------------------------- -- ------------------------------ -- Create a UIFile component -- ------------------------------ function Create_File return UIComponent_Access is begin return new ASF.Components.Utils.Files.UIFile; end Create_File; -- ------------------------------ -- Create a UIFlush component -- ------------------------------ function Create_Flush return UIComponent_Access is begin return new ASF.Components.Utils.Flush.UIFlush; end Create_Flush; -- ------------------------------ -- Create a UIScript component -- ------------------------------ function Create_Script return UIComponent_Access is begin return new ASF.Components.Utils.Scripts.UIScript; end Create_Script; -- ------------------------------ -- Create a UIEscape component -- ------------------------------ function Create_Escape return UIComponent_Access is begin return new ASF.Components.Utils.Escapes.UIEscape; end Create_Escape; -- ------------------------------ -- Create a UISetBean component -- ------------------------------ function Create_Set return UIComponent_Access is begin return new ASF.Components.Utils.Beans.UISetBean; end Create_Set; use ASF.Views.Nodes; URI : aliased constant String := "http://code.google.com/p/ada-asf/util"; ESCAPE_TAG : aliased constant String := "escape"; FILE_TAG : aliased constant String := "file"; FLUSH_TAG : aliased constant String := "flush"; SCRIPT_TAG : aliased constant String := "script"; SET_TAG : aliased constant String := "set"; Core_Bindings : aliased constant ASF.Factory.Binding_Array := (1 => (Name => ESCAPE_TAG'Access, Component => Create_Escape'Access, Tag => Create_Component_Node'Access), 2 => (Name => FILE_TAG'Access, Component => Create_File'Access, Tag => Create_Component_Node'Access), 3 => (Name => FLUSH_TAG'Access, Component => Create_Flush'Access, Tag => Create_Component_Node'Access), 4 => (Name => SCRIPT_TAG'Access, Component => Create_Script'Access, Tag => Create_Component_Node'Access), 5 => (Name => SET_TAG'Access, Component => Create_Set'Access, Tag => Create_Component_Node'Access) ); Core_Factory : aliased constant ASF.Factory.Factory_Bindings := (URI => URI'Access, Bindings => Core_Bindings'Access); -- ------------------------------ -- Get the HTML component factory. -- ------------------------------ function Definition return ASF.Factory.Factory_Bindings_Access is begin return Core_Factory'Access; end Definition; -- Truncate the string representation represented by <b>Value</b> to -- the length specified by <b>Size</b>. function Escape_Javascript (Value : EL.Objects.Object) return EL.Objects.Object; -- Escape the string using XML escape rules. function Escape_Xml (Value : EL.Objects.Object) return EL.Objects.Object; -- Translate the value into an ISO8606 date. function To_ISO8601 (Value : in EL.Objects.Object) return EL.Objects.Object; -- Encode the string for URL. function Url_Encode (Value : in EL.Objects.Object) return EL.Objects.Object; -- Encode the object into a SHA256. function SHA256 (Value : in EL.Objects.Object) return EL.Objects.Object; function SHA256_Base64 (Value : in EL.Objects.Object) return EL.Objects.Object; -- Format a date using the given date pattern. function Format_Date (Date : in EL.Objects.Object; Format : in EL.Objects.Object) return EL.Objects.Object; -- Translate a value using a resource bundle and applying a prefix for the translation. function Translate (Bundle : in EL.Objects.Object; Prefix : in EL.Objects.Object; Value : in EL.Objects.Object) return EL.Objects.Object; procedure Set_Functions (Mapper : in out EL.Functions.Function_Mapper'Class) is begin Mapper.Set_Function (Name => "escapeJavaScript", Namespace => URI, Func => Escape_Javascript'Access); Mapper.Set_Function (Name => "escapeXml", Namespace => URI, Func => Escape_Xml'Access); Mapper.Set_Function (Name => "formatDate", Namespace => URI, Func => Format_Date'Access); Mapper.Set_Function (Name => "iso8601", Namespace => URI, Func => To_ISO8601'Access); Mapper.Set_Function (Name => "hasMessage", Namespace => URI, Func => ASF.Components.Html.Messages.Has_Message'Access, Optimize => False); Mapper.Set_Function (Name => "urlEncode", Namespace => URI, Func => Url_Encode'Access, Optimize => False); Mapper.Set_Function (Name => "translate", Namespace => URI, Func => Translate'Access); Mapper.Set_Function (Name => "sha256base64", Namespace => URI, Func => SHA256_Base64'Access); Mapper.Set_Function (Name => "sha256", Namespace => URI, Func => SHA256'Access); end Set_Functions; function Escape_Javascript (Value : EL.Objects.Object) return EL.Objects.Object is Result : Ada.Strings.Unbounded.Unbounded_String; Content : constant String := EL.Objects.To_String (Value); begin Transforms.Escape_Javascript (Content => Content, Into => Result); return EL.Objects.To_Object (Result); end Escape_Javascript; function Escape_Xml (Value : EL.Objects.Object) return EL.Objects.Object is Result : Ada.Strings.Unbounded.Unbounded_String; Content : constant String := EL.Objects.To_String (Value); begin Transforms.Escape_Xml (Content => Content, Into => Result); return EL.Objects.To_Object (Result); end Escape_Xml; -- ------------------------------ -- Translate the value into an ISO8606 date. -- ------------------------------ function To_ISO8601 (Value : in EL.Objects.Object) return EL.Objects.Object is D : constant Ada.Calendar.Time := Util.Beans.Objects.Time.To_Time (Value); S : constant String := Util.Dates.ISO8601.Image (D); begin return Util.Beans.Objects.To_Object (S); end To_ISO8601; -- ------------------------------ -- Format a date using the given date pattern. -- ------------------------------ function Format_Date (Date : in EL.Objects.Object; Format : in EL.Objects.Object) return EL.Objects.Object is Context : constant ASF.Contexts.Faces.Faces_Context_Access := ASF.Contexts.Faces.Current; Locale : constant Util.Locales.Locale := Context.Get_Locale; Bundle : ASF.Locales.Bundle; begin begin ASF.Applications.Main.Load_Bundle (Context.Get_Application.all, Name => "asf", Locale => Util.Locales.To_String (Locale), Bundle => Bundle); exception when E : Util.Properties.Bundles.NO_BUNDLE => Log.Error ("Cannot localize dates: {0}", Ada.Exceptions.Exception_Message (E)); end; declare Time : constant Ada.Calendar.Time := Util.Beans.Objects.Time.To_Time (Date); Pattern : constant String := Util.Beans.Objects.To_String (Format); Result : constant String := Util.Dates.Formats.Format (Pattern, Time, Bundle); begin return EL.Objects.To_Object (Result); end; end Format_Date; -- ------------------------------ -- Translate a value using a resource bundle and applying a prefix for the translation. -- ------------------------------ function Translate (Bundle : in EL.Objects.Object; Prefix : in EL.Objects.Object; Value : in EL.Objects.Object) return EL.Objects.Object is Bean : access Util.Beans.Basic.Readonly_Bean'Class; begin Bean := Util.Beans.Objects.To_Bean (Bundle); if Bean = null then return Value; else return Bean.Get_Value (EL.Objects.To_String (Prefix) & EL.Objects.To_String (Value)); end if; end Translate; use Ada.Strings.Maps; Conversion : constant String (1 .. 16) := "0123456789ABCDEF"; Url_Encode_Set : constant Ada.Strings.Maps.Character_Set := Ada.Strings.Maps.To_Set (Span => (Low => Character'Val (0), High => ' ')) or Ada.Strings.Maps.To_Set (Span => (Low => Character'Val (128), High => Character'Val (255))) or Ada.Strings.Maps.To_Set (":/?#[]@!$&'""()*+,;="); -- ------------------------------ -- Encode the string for URL. -- ------------------------------ function Url_Encode (Value : in EL.Objects.Object) return EL.Objects.Object is S : constant String := Util.Beans.Objects.To_String (Value); T : String (1 .. S'Length * 3); Pos : Positive := 1; C : Character; begin for I in S'Range loop C := S (I); if Ada.Strings.Maps.Is_In (C, Url_Encode_Set) then T (Pos) := '%'; T (Pos + 1) := Conversion (1 + Character'Pos (C) / 16); T (Pos + 2) := Conversion (1 + Character'Pos (C) mod 16); Pos := Pos + 3; else T (Pos) := C; Pos := Pos + 1; end if; end loop; return Util.Beans.Objects.To_Object (T (1 .. Pos - 1)); end Url_Encode; -- ------------------------------ -- Encode the object into a SHA256. -- ------------------------------ function SHA256_Base64 (Value : in EL.Objects.Object) return EL.Objects.Object is Content : constant String := Util.Beans.Objects.To_String (Value); Context : Util.Encoders.SHA256.Context; Result : Util.Encoders.SHA256.Base64_Digest; begin Util.Encoders.SHA256.Update (Context, Content); Util.Encoders.SHA256.Finish_Base64 (Context, Result); return Util.Beans.Objects.To_Object (Result); end SHA256_Base64; -- ------------------------------ -- Encode the object into a SHA256. -- ------------------------------ function SHA256 (Value : in EL.Objects.Object) return EL.Objects.Object is Content : constant String := Util.Beans.Objects.To_String (Value); Context : Util.Encoders.SHA256.Context; Result : Util.Encoders.SHA256.Digest; begin Util.Encoders.SHA256.Update (Context, Content); Util.Encoders.SHA256.Finish (Context, Result); return Util.Beans.Objects.To_Object (Result); end SHA256; end ASF.Components.Utils.Factory;
----------------------------------------------------------------------- -- core-factory -- Factory for Core UI Components -- Copyright (C) 2009, 2010, 2011, 2012, 2013, 2014, 2015, 2016, 2018 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Calendar; with Ada.Exceptions; with Ada.Strings.Maps; with ASF.Views.Nodes; with ASF.Locales; with ASF.Components.Utils.Files; with ASF.Components.Utils.Flush; with ASF.Components.Utils.Scripts; with ASF.Components.Utils.Escapes; with ASF.Components.Utils.Beans; with ASF.Components.Html.Messages; with ASF.Applications.Main; with Util.Log.Loggers; with Util.Properties.Bundles; with Util.Dates.Formats; with Util.Dates.ISO8601; with Util.Beans.Objects.Time; with Util.Locales; with Util.Encoders.SHA256; with Util.Strings.Transforms; use Util.Strings; package body ASF.Components.Utils.Factory is use ASF.Components.Base; -- The logger Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("ASF.Components.Utils.Factory"); function Create_File return UIComponent_Access; function Create_Flush return UIComponent_Access; function Create_Script return UIComponent_Access; function Create_Escape return UIComponent_Access; function Create_Set return UIComponent_Access; -- ------------------------- -- ------------------------------ -- Create a UIFile component -- ------------------------------ function Create_File return UIComponent_Access is begin return new ASF.Components.Utils.Files.UIFile; end Create_File; -- ------------------------------ -- Create a UIFlush component -- ------------------------------ function Create_Flush return UIComponent_Access is begin return new ASF.Components.Utils.Flush.UIFlush; end Create_Flush; -- ------------------------------ -- Create a UIScript component -- ------------------------------ function Create_Script return UIComponent_Access is begin return new ASF.Components.Utils.Scripts.UIScript; end Create_Script; -- ------------------------------ -- Create a UIEscape component -- ------------------------------ function Create_Escape return UIComponent_Access is begin return new ASF.Components.Utils.Escapes.UIEscape; end Create_Escape; -- ------------------------------ -- Create a UISetBean component -- ------------------------------ function Create_Set return UIComponent_Access is begin return new ASF.Components.Utils.Beans.UISetBean; end Create_Set; use ASF.Views.Nodes; URI : aliased constant String := "http://code.google.com/p/ada-asf/util"; ESCAPE_TAG : aliased constant String := "escape"; FILE_TAG : aliased constant String := "file"; FLUSH_TAG : aliased constant String := "flush"; SCRIPT_TAG : aliased constant String := "script"; SET_TAG : aliased constant String := "set"; -- ------------------------------ -- Register the HTML component factory. -- ------------------------------ procedure Register (Factory : in out ASF.Factory.Component_Factory) is begin ASF.Factory.Register (Factory, URI => URI'Access, Name => ESCAPE_TAG'Access, Tag => Create_Component_Node'Access, Create => Create_Escape'Access); ASF.Factory.Register (Factory, URI => URI'Access, Name => FILE_TAG'Access, Tag => Create_Component_Node'Access, Create => Create_File'Access); ASF.Factory.Register (Factory, URI => URI'Access, Name => FLUSH_TAG'Access, Tag => Create_Component_Node'Access, Create => Create_Flush'Access); ASF.Factory.Register (Factory, URI => URI'Access, Name => SCRIPT_TAG'Access, Tag => Create_Component_Node'Access, Create => Create_Script'Access); ASF.Factory.Register (Factory, URI => URI'Access, Name => SET_TAG'Access, Tag => Create_Component_Node'Access, Create => Create_Set'Access); end Register; -- Truncate the string representation represented by <b>Value</b> to -- the length specified by <b>Size</b>. function Escape_Javascript (Value : EL.Objects.Object) return EL.Objects.Object; -- Escape the string using XML escape rules. function Escape_Xml (Value : EL.Objects.Object) return EL.Objects.Object; -- Translate the value into an ISO8606 date. function To_ISO8601 (Value : in EL.Objects.Object) return EL.Objects.Object; -- Encode the string for URL. function Url_Encode (Value : in EL.Objects.Object) return EL.Objects.Object; -- Encode the object into a SHA256. function SHA256 (Value : in EL.Objects.Object) return EL.Objects.Object; function SHA256_Base64 (Value : in EL.Objects.Object) return EL.Objects.Object; -- Format a date using the given date pattern. function Format_Date (Date : in EL.Objects.Object; Format : in EL.Objects.Object) return EL.Objects.Object; -- Translate a value using a resource bundle and applying a prefix for the translation. function Translate (Bundle : in EL.Objects.Object; Prefix : in EL.Objects.Object; Value : in EL.Objects.Object) return EL.Objects.Object; procedure Set_Functions (Mapper : in out EL.Functions.Function_Mapper'Class) is begin Mapper.Set_Function (Name => "escapeJavaScript", Namespace => URI, Func => Escape_Javascript'Access); Mapper.Set_Function (Name => "escapeXml", Namespace => URI, Func => Escape_Xml'Access); Mapper.Set_Function (Name => "formatDate", Namespace => URI, Func => Format_Date'Access); Mapper.Set_Function (Name => "iso8601", Namespace => URI, Func => To_ISO8601'Access); Mapper.Set_Function (Name => "hasMessage", Namespace => URI, Func => ASF.Components.Html.Messages.Has_Message'Access, Optimize => False); Mapper.Set_Function (Name => "urlEncode", Namespace => URI, Func => Url_Encode'Access, Optimize => False); Mapper.Set_Function (Name => "translate", Namespace => URI, Func => Translate'Access); Mapper.Set_Function (Name => "sha256base64", Namespace => URI, Func => SHA256_Base64'Access); Mapper.Set_Function (Name => "sha256", Namespace => URI, Func => SHA256'Access); end Set_Functions; function Escape_Javascript (Value : EL.Objects.Object) return EL.Objects.Object is Result : Ada.Strings.Unbounded.Unbounded_String; Content : constant String := EL.Objects.To_String (Value); begin Transforms.Escape_Javascript (Content => Content, Into => Result); return EL.Objects.To_Object (Result); end Escape_Javascript; function Escape_Xml (Value : EL.Objects.Object) return EL.Objects.Object is Result : Ada.Strings.Unbounded.Unbounded_String; Content : constant String := EL.Objects.To_String (Value); begin Transforms.Escape_Xml (Content => Content, Into => Result); return EL.Objects.To_Object (Result); end Escape_Xml; -- ------------------------------ -- Translate the value into an ISO8606 date. -- ------------------------------ function To_ISO8601 (Value : in EL.Objects.Object) return EL.Objects.Object is D : constant Ada.Calendar.Time := Util.Beans.Objects.Time.To_Time (Value); S : constant String := Util.Dates.ISO8601.Image (D); begin return Util.Beans.Objects.To_Object (S); end To_ISO8601; -- ------------------------------ -- Format a date using the given date pattern. -- ------------------------------ function Format_Date (Date : in EL.Objects.Object; Format : in EL.Objects.Object) return EL.Objects.Object is Context : constant ASF.Contexts.Faces.Faces_Context_Access := ASF.Contexts.Faces.Current; Locale : constant Util.Locales.Locale := Context.Get_Locale; Bundle : ASF.Locales.Bundle; begin begin ASF.Applications.Main.Load_Bundle (Context.Get_Application.all, Name => "asf", Locale => Util.Locales.To_String (Locale), Bundle => Bundle); exception when E : Util.Properties.Bundles.NO_BUNDLE => Log.Error ("Cannot localize dates: {0}", Ada.Exceptions.Exception_Message (E)); end; declare Time : constant Ada.Calendar.Time := Util.Beans.Objects.Time.To_Time (Date); Pattern : constant String := Util.Beans.Objects.To_String (Format); Result : constant String := Util.Dates.Formats.Format (Pattern, Time, Bundle); begin return EL.Objects.To_Object (Result); end; end Format_Date; -- ------------------------------ -- Translate a value using a resource bundle and applying a prefix for the translation. -- ------------------------------ function Translate (Bundle : in EL.Objects.Object; Prefix : in EL.Objects.Object; Value : in EL.Objects.Object) return EL.Objects.Object is Bean : access Util.Beans.Basic.Readonly_Bean'Class; begin Bean := Util.Beans.Objects.To_Bean (Bundle); if Bean = null then return Value; else return Bean.Get_Value (EL.Objects.To_String (Prefix) & EL.Objects.To_String (Value)); end if; end Translate; use Ada.Strings.Maps; Conversion : constant String (1 .. 16) := "0123456789ABCDEF"; Url_Encode_Set : constant Ada.Strings.Maps.Character_Set := Ada.Strings.Maps.To_Set (Span => (Low => Character'Val (0), High => ' ')) or Ada.Strings.Maps.To_Set (Span => (Low => Character'Val (128), High => Character'Val (255))) or Ada.Strings.Maps.To_Set (":/?#[]@!$&'""()*+,;="); -- ------------------------------ -- Encode the string for URL. -- ------------------------------ function Url_Encode (Value : in EL.Objects.Object) return EL.Objects.Object is S : constant String := Util.Beans.Objects.To_String (Value); T : String (1 .. S'Length * 3); Pos : Positive := 1; C : Character; begin for I in S'Range loop C := S (I); if Ada.Strings.Maps.Is_In (C, Url_Encode_Set) then T (Pos) := '%'; T (Pos + 1) := Conversion (1 + Character'Pos (C) / 16); T (Pos + 2) := Conversion (1 + Character'Pos (C) mod 16); Pos := Pos + 3; else T (Pos) := C; Pos := Pos + 1; end if; end loop; return Util.Beans.Objects.To_Object (T (1 .. Pos - 1)); end Url_Encode; -- ------------------------------ -- Encode the object into a SHA256. -- ------------------------------ function SHA256_Base64 (Value : in EL.Objects.Object) return EL.Objects.Object is Content : constant String := Util.Beans.Objects.To_String (Value); Context : Util.Encoders.SHA256.Context; Result : Util.Encoders.SHA256.Base64_Digest; begin Util.Encoders.SHA256.Update (Context, Content); Util.Encoders.SHA256.Finish_Base64 (Context, Result); return Util.Beans.Objects.To_Object (Result); end SHA256_Base64; -- ------------------------------ -- Encode the object into a SHA256. -- ------------------------------ function SHA256 (Value : in EL.Objects.Object) return EL.Objects.Object is Content : constant String := Util.Beans.Objects.To_String (Value); Context : Util.Encoders.SHA256.Context; Result : Util.Encoders.SHA256.Digest; begin Util.Encoders.SHA256.Update (Context, Content); Util.Encoders.SHA256.Finish (Context, Result); return Util.Beans.Objects.To_Object (Result); end SHA256; end ASF.Components.Utils.Factory;
Change the Definition function into a Register procedure
Change the Definition function into a Register procedure
Ada
apache-2.0
stcarrez/ada-asf,stcarrez/ada-asf,stcarrez/ada-asf
abec17df29cfedcb71365e414247d574b210666e
src/base/commands/util-commands-drivers.ads
src/base/commands/util-commands-drivers.ads
----------------------------------------------------------------------- -- util-commands-drivers -- Support to make command line tools -- Copyright (C) 2017, 2018, 2019 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Log; with Util.Commands.Parsers; private with Ada.Strings.Unbounded; private with Ada.Containers.Indefinite_Ordered_Maps; -- == Command line driver == -- The `Util.Commands.Drivers` generic package provides a support to build command line -- tools that have different commands identified by a name. It defines the `Driver_Type` -- tagged record that provides a registry of application commands. It gives entry points -- to register commands and execute them. -- -- The `Context_Type` package parameter defines the type for the `Context` parameter -- that is passed to the command when it is executed. It can be used to provide -- application specific context to the command. -- -- The `Config_Parser` describes the parser package that will handle the analysis of -- command line options. To use the GNAT options parser, it is possible to use the -- `Util.Commands.Parsers.GNAT_Parser` package. generic -- The command execution context. type Context_Type (<>) is limited private; with package Config_Parser is new Util.Commands.Parsers.Config_Parser (<>); Driver_Name : String := "Drivers"; package Util.Commands.Drivers is subtype Config_Type is Config_Parser.Config_Type; -- A simple command handler executed when the command with the given name is executed. type Command_Handler is not null access procedure (Name : in String; Args : in Argument_List'Class; Context : in out Context_Type); -- A more complex command handler that has a command instance as context. type Command_Type is abstract tagged limited private; type Command_Access is access all Command_Type'Class; -- Execute the command with the arguments. The command name is passed with the command -- arguments. procedure Execute (Command : in out Command_Type; Name : in String; Args : in Argument_List'Class; Context : in out Context_Type) is abstract; -- Setup the command before parsing the arguments and executing it. procedure Setup (Command : in out Command_Type; Config : in out Config_Type; Context : in out Context_Type) is null; -- Write the help associated with the command. procedure Help (Command : in out Command_Type; Name : in String; Context : in out Context_Type) is abstract; -- Write the command usage. procedure Usage (Command : in out Command_Type; Name : in String; Context : in out Context_Type); -- 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); type Help_Command_Type is new Command_Type with private; -- Execute the help command with the arguments. -- Print the help for every registered command. overriding procedure Execute (Command : in out Help_Command_Type; Name : in String; Args : in Argument_List'Class; Context : in out Context_Type); -- Write the help associated with the command. overriding procedure Help (Command : in out Help_Command_Type; Name : in String; Context : in out Context_Type); type Driver_Type is tagged limited private; -- Report the command usage. procedure Usage (Driver : in Driver_Type; Args : in Argument_List'Class; Context : in out Context_Type; Name : in String := ""); -- Set the driver description printed in the usage. procedure Set_Description (Driver : in out Driver_Type; Description : in String); -- Set the driver usage printed in the usage. procedure Set_Usage (Driver : in out Driver_Type; Usage : in String); -- Register the command under the given name. procedure Add_Command (Driver : in out Driver_Type; Name : in String; Command : in Command_Access); procedure Add_Command (Driver : in out Driver_Type; Name : in String; Description : in String; Command : in Command_Access); -- Register the command under the given name. procedure Add_Command (Driver : in out Driver_Type; Name : in String; Description : in String; Handler : in Command_Handler); -- 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; -- 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); -- 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); private package Command_Maps is new Ada.Containers.Indefinite_Ordered_Maps (Key_Type => String, Element_Type => Command_Access, "<" => "<"); type Command_Type is abstract tagged limited record Driver : access Driver_Type'Class; Description : Ada.Strings.Unbounded.Unbounded_String; end record; type Help_Command_Type is new Command_Type with null record; type Handler_Command_Type is new Command_Type with record Handler : Command_Handler; end record; -- Execute the command with the arguments. overriding procedure Execute (Command : in out Handler_Command_Type; Name : in String; Args : in Argument_List'Class; Context : in out Context_Type); -- Write the help associated with the command. overriding procedure Help (Command : in out Handler_Command_Type; Name : in String; Context : in out Context_Type); type Driver_Type is tagged limited record List : Command_Maps.Map; Desc : Ada.Strings.Unbounded.Unbounded_String; Usage : Ada.Strings.Unbounded.Unbounded_String; end record; end Util.Commands.Drivers;
----------------------------------------------------------------------- -- util-commands-drivers -- Support to make command line tools -- Copyright (C) 2017, 2018, 2019 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Log; with Util.Commands.Parsers; private with Ada.Strings.Unbounded; private with Ada.Containers.Indefinite_Ordered_Maps; -- == Command line driver == -- The `Util.Commands.Drivers` generic package provides a support to build command line -- tools that have different commands identified by a name. It defines the `Driver_Type` -- tagged record that provides a registry of application commands. It gives entry points -- to register commands and execute them. -- -- The `Context_Type` package parameter defines the type for the `Context` parameter -- that is passed to the command when it is executed. It can be used to provide -- application specific context to the command. -- -- The `Config_Parser` describes the parser package that will handle the analysis of -- command line options. To use the GNAT options parser, it is possible to use the -- `Util.Commands.Parsers.GNAT_Parser` package. generic -- The command execution context. type Context_Type (<>) is limited private; with package Config_Parser is new Util.Commands.Parsers.Config_Parser (<>); Driver_Name : String := "Drivers"; package Util.Commands.Drivers is subtype Config_Type is Config_Parser.Config_Type; -- A simple command handler executed when the command with the given name is executed. type Command_Handler is not null access procedure (Name : in String; Args : in Argument_List'Class; Context : in out Context_Type); -- A more complex command handler that has a command instance as context. type Command_Type is abstract tagged limited private; type Command_Access is access all Command_Type'Class; -- Get the description associated with the command. function Get_Description (Command : in Command_Type) return String; -- Get the name used to register the command. function Get_Name (Command : in Command_Type) return String; -- Execute the command with the arguments. The command name is passed with the command -- arguments. procedure Execute (Command : in out Command_Type; Name : in String; Args : in Argument_List'Class; Context : in out Context_Type) is abstract; -- Setup the command before parsing the arguments and executing it. procedure Setup (Command : in out Command_Type; Config : in out Config_Type; Context : in out Context_Type) is null; -- Write the help associated with the command. procedure Help (Command : in out Command_Type; Name : in String; Context : in out Context_Type) is abstract; -- Write the command usage. procedure Usage (Command : in out Command_Type; Name : in String; Context : in out Context_Type); -- 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); type Help_Command_Type is new Command_Type with private; -- Execute the help command with the arguments. -- Print the help for every registered command. overriding procedure Execute (Command : in out Help_Command_Type; Name : in String; Args : in Argument_List'Class; Context : in out Context_Type); -- Write the help associated with the command. overriding procedure Help (Command : in out Help_Command_Type; Name : in String; Context : in out Context_Type); type Driver_Type is tagged limited private; -- Report the command usage. procedure Usage (Driver : in Driver_Type; Args : in Argument_List'Class; Context : in out Context_Type; Name : in String := ""); -- Set the driver description printed in the usage. procedure Set_Description (Driver : in out Driver_Type; Description : in String); -- Set the driver usage printed in the usage. procedure Set_Usage (Driver : in out Driver_Type; Usage : in String); -- Register the command under the given name. procedure Add_Command (Driver : in out Driver_Type; Name : in String; Command : in Command_Access); procedure Add_Command (Driver : in out Driver_Type; Name : in String; Description : in String; Command : in Command_Access); -- Register the command under the given name. procedure Add_Command (Driver : in out Driver_Type; Name : in String; Description : in String; Handler : in Command_Handler); -- 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; -- 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); -- 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); private package Command_Maps is new Ada.Containers.Indefinite_Ordered_Maps (Key_Type => String, Element_Type => Command_Access, "<" => "<"); type Command_Type is abstract tagged limited record Driver : access Driver_Type'Class; Name : Ada.Strings.Unbounded.Unbounded_String; Description : Ada.Strings.Unbounded.Unbounded_String; end record; type Help_Command_Type is new Command_Type with null record; type Handler_Command_Type is new Command_Type with record Handler : Command_Handler; end record; -- Execute the command with the arguments. overriding procedure Execute (Command : in out Handler_Command_Type; Name : in String; Args : in Argument_List'Class; Context : in out Context_Type); -- Write the help associated with the command. overriding procedure Help (Command : in out Handler_Command_Type; Name : in String; Context : in out Context_Type); type Driver_Type is tagged limited record List : Command_Maps.Map; Desc : Ada.Strings.Unbounded.Unbounded_String; Usage : Ada.Strings.Unbounded.Unbounded_String; end record; end Util.Commands.Drivers;
Add Get_Description and Get_Name on the Command_Type
Add Get_Description and Get_Name on the Command_Type
Ada
apache-2.0
stcarrez/ada-util,stcarrez/ada-util
bcb58808737f5a17a670be659f7392eaa018deed
src/util-streams.ads
src/util-streams.ads
----------------------------------------------------------------------- -- util-streams -- Stream utilities -- Copyright (C) 2010, 2016, 2018 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Streams; -- = Streams = -- The `Util.Streams` package provides several types and operations to allow the -- composition of input and output streams. Input streams can be chained together so that -- they traverse the different stream objects when the data is read from them. Similarly, -- output streams can be chained and the data that is written will traverse the different -- streams from the first one up to the last one in the chain. During such traversal, the -- stream object is able to bufferize the data or make transformations on the data. -- -- @include util-streams-buffered.ads -- @include util-streams-texts.ads -- @include util-streams-files.ads -- @include util-streams-pipes.ads -- @include util-streams-sockets.ads -- @include util-streams-raw.ads -- @include util-streams-buffered-encoders.ads package Util.Streams is pragma Preelaborate; -- ----------------------- -- Output stream -- ----------------------- -- The <b>Output_Stream</b> is an interface that accepts output bytes -- and sends them to a sink. type Output_Stream is limited interface; type Output_Stream_Access is access all Output_Stream'Class; -- Write the buffer array to the output stream. procedure Write (Stream : in out Output_Stream; Buffer : in Ada.Streams.Stream_Element_Array) is abstract; -- Flush the buffer (if any) to the sink. procedure Flush (Stream : in out Output_Stream) is null; -- Close the sink. procedure Close (Stream : in out Output_Stream) is null; -- ----------------------- -- Input stream -- ----------------------- -- The <b>Input_Stream</b> is the interface that reads input bytes -- from a source and returns them. type Input_Stream is limited interface; type Input_Stream_Access is access all Input_Stream'Class; -- 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_Stream; Into : out Ada.Streams.Stream_Element_Array; Last : out Ada.Streams.Stream_Element_Offset) is abstract; -- Copy the input stream to the output stream until the end of the input stream -- is reached. procedure Copy (From : in out Input_Stream'Class; Into : in out Output_Stream'Class); -- Copy the stream array to the string. -- The string must be large enough to hold the stream array -- or a Constraint_Error exception is raised. procedure Copy (From : in Ada.Streams.Stream_Element_Array; Into : in out String); -- Copy the string to the stream array. -- The stream array must be large enough to hold the string -- or a Constraint_Error exception is raised. procedure Copy (From : in String; Into : in out Ada.Streams.Stream_Element_Array); -- Notes: -- ------ -- The <b>Ada.Streams.Root_Stream_Type</b> implements the <b>Output_Stream</b> -- and <b>Input_Stream</b>. It is however not easy to use for composing various -- stream behaviors. end Util.Streams;
----------------------------------------------------------------------- -- util-streams -- Stream utilities -- Copyright (C) 2010, 2016, 2018 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Streams; -- = Streams = -- The `Util.Streams` package provides several types and operations to allow the -- composition of input and output streams. Input streams can be chained together so that -- they traverse the different stream objects when the data is read from them. Similarly, -- output streams can be chained and the data that is written will traverse the different -- streams from the first one up to the last one in the chain. During such traversal, the -- stream object is able to bufferize the data or make transformations on the data. -- -- The `Input_Stream` interface represents the stream to read data. It only provides a -- `Read` procedure. The `Output_Stream` interface represents the stream to write data. -- It provides a `Write`, `Flush` and `Close` operation. -- -- @include util-streams-buffered.ads -- @include util-streams-texts.ads -- @include util-streams-files.ads -- @include util-streams-pipes.ads -- @include util-streams-sockets.ads -- @include util-streams-raw.ads -- @include util-streams-buffered-encoders.ads package Util.Streams is pragma Preelaborate; -- ----------------------- -- Output stream -- ----------------------- -- The <b>Output_Stream</b> is an interface that accepts output bytes -- and sends them to a sink. type Output_Stream is limited interface; type Output_Stream_Access is access all Output_Stream'Class; -- Write the buffer array to the output stream. procedure Write (Stream : in out Output_Stream; Buffer : in Ada.Streams.Stream_Element_Array) is abstract; -- Flush the buffer (if any) to the sink. procedure Flush (Stream : in out Output_Stream) is null; -- Close the sink. procedure Close (Stream : in out Output_Stream) is null; -- ----------------------- -- Input stream -- ----------------------- -- The <b>Input_Stream</b> is the interface that reads input bytes -- from a source and returns them. type Input_Stream is limited interface; type Input_Stream_Access is access all Input_Stream'Class; -- 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_Stream; Into : out Ada.Streams.Stream_Element_Array; Last : out Ada.Streams.Stream_Element_Offset) is abstract; -- Copy the input stream to the output stream until the end of the input stream -- is reached. procedure Copy (From : in out Input_Stream'Class; Into : in out Output_Stream'Class); -- Copy the stream array to the string. -- The string must be large enough to hold the stream array -- or a Constraint_Error exception is raised. procedure Copy (From : in Ada.Streams.Stream_Element_Array; Into : in out String); -- Copy the string to the stream array. -- The stream array must be large enough to hold the string -- or a Constraint_Error exception is raised. procedure Copy (From : in String; Into : in out Ada.Streams.Stream_Element_Array); -- Notes: -- ------ -- The <b>Ada.Streams.Root_Stream_Type</b> implements the <b>Output_Stream</b> -- and <b>Input_Stream</b>. It is however not easy to use for composing various -- stream behaviors. end Util.Streams;
Add some documentation
Add some documentation
Ada
apache-2.0
stcarrez/ada-util,stcarrez/ada-util
a20c3cec97d5bb88ed6f4caa3a116f8f7559360b
src/util-strings.adb
src/util-strings.adb
----------------------------------------------------------------------- -- Util-strings -- Various String Utility -- Copyright (C) 2001, 2002, 2003, 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.Fixed; with Ada.Strings.Hash; with Ada.Unchecked_Deallocation; package body Util.Strings is -- ------------------------------ -- Compute the hash value of the string. -- ------------------------------ function Hash (Key : Name_Access) return Ada.Containers.Hash_Type is begin return Ada.Strings.Hash (Key.all); end Hash; -- ------------------------------ -- Returns true if left and right strings are equivalent. -- ------------------------------ function Equivalent_Keys (Left, Right : Name_Access) return Boolean is begin if Left = null or Right = null then return False; end if; return Left.all = Right.all; end Equivalent_Keys; -- ------------------------------ -- Returns Integer'Image (Value) with the possible space stripped. -- ------------------------------ function Image (Value : in Integer) return String is S : constant String := Integer'Image (Value); begin if S (S'First) = ' ' then return S (S'First + 1 .. S'Last); else return S; end if; end Image; -- ------------------------------ -- Returns Integer'Image (Value) with the possible space stripped. -- ------------------------------ function Image (Value : in Long_Long_Integer) return String is S : constant String := Long_Long_Integer'Image (Value); begin if S (S'First) = ' ' then return S (S'First + 1 .. S'Last); else return S; end if; end Image; use Util.Concurrent.Counters; -- ------------------------------ -- Create a string reference from a string. -- ------------------------------ function To_String_Ref (S : in String) return String_Ref is Str : constant String_Record_Access := new String_Record '(Len => S'Length, Str => S, Counter => ONE); begin return String_Ref '(Ada.Finalization.Controlled with Str => Str); end To_String_Ref; -- ------------------------------ -- Create a string reference from an unbounded string. -- ------------------------------ function To_String_Ref (S : in Ada.Strings.Unbounded.Unbounded_String) return String_Ref is use Ada.Strings.Unbounded; Len : constant Natural := Length (S); Str : constant String_Record_Access := new String_Record '(Len => Len, Str => To_String (S), Counter => ONE); begin return String_Ref '(Ada.Finalization.Controlled with Str => Str); end To_String_Ref; -- ------------------------------ -- Get the string -- ------------------------------ function To_String (S : in String_Ref) return String is begin if S.Str /= null then return S.Str.Str; else return ""; end if; end To_String; -- ------------------------------ -- Get the string as an unbounded string -- ------------------------------ function To_Unbounded_String (S : in String_Ref) return Ada.Strings.Unbounded.Unbounded_String is begin if S.Str /= null then return Ada.Strings.Unbounded.To_Unbounded_String (S.Str.Str); else return Ada.Strings.Unbounded.Null_Unbounded_String; end if; end To_Unbounded_String; -- ------------------------------ -- Compute the hash value of the string reference. -- ------------------------------ function Hash (Key : String_Ref) return Ada.Containers.Hash_Type is begin if Key.Str /= null then return Ada.Strings.Hash (Key.Str.Str); else return 0; end if; end Hash; -- ------------------------------ -- Returns true if left and right string references are equivalent. -- ------------------------------ function Equivalent_Keys (Left, Right : String_Ref) return Boolean is begin if Left.Str = Right.Str then return True; elsif Left.Str = null or Right.Str = null then return False; else return Left.Str.Str = Right.Str.Str; end if; end Equivalent_Keys; function "=" (Left : in String_Ref; Right : in String) return Boolean is begin if Left.Str = null then return False; else return Left.Str.Str = Right; end if; end "="; function "=" (Left : in String_Ref; Right : in Ada.Strings.Unbounded.Unbounded_String) return Boolean is use Ada.Strings.Unbounded; begin if Left.Str = null then return Right = Null_Unbounded_String; else return Right = Left.Str.Str; end if; end "="; -- ------------------------------ -- Returns the string length. -- ------------------------------ function Length (S : in String_Ref) return Natural is begin if S.Str = null then return 0; else return S.Str.Len; end if; end Length; -- ------------------------------ -- Increment the reference counter. -- ------------------------------ overriding procedure Adjust (Object : in out String_Ref) is begin if Object.Str /= null then Util.Concurrent.Counters.Increment (Object.Str.Counter); end if; end Adjust; -- ------------------------------ -- Decrement the reference counter and free the allocated string. -- ------------------------------ overriding procedure Finalize (Object : in out String_Ref) is procedure Free is new Ada.Unchecked_Deallocation (String_Record, String_Record_Access); Is_Zero : Boolean; begin if Object.Str /= null then Util.Concurrent.Counters.Decrement (Object.Str.Counter, Is_Zero); if Is_Zero then Free (Object.Str); else Object.Str := null; end if; end if; end Finalize; -- ------------------------------ -- Search for the first occurrence of the character in the string -- after the from index. This implementation is 3-times faster than -- the Ada.Strings.Fixed version. -- Returns the index of the first occurrence or 0. -- ------------------------------ function Index (Source : in String; Char : in Character; From : in Natural := 0) return Natural is Pos : Natural := From; begin if Pos < Source'First then Pos := Source'First; end if; for I in Pos .. Source'Last loop if Source (I) = Char then return I; end if; end loop; return 0; end Index; -- ------------------------------ -- Search for the first occurrence of the pattern in the string. -- ------------------------------ function Index (Source : in String; Pattern : in String; From : in Positive; Going : in Ada.Strings.Direction := Ada.Strings.Forward) return Natural is begin return Ada.Strings.Fixed.Index (Source, Pattern, From, Going); end Index; -- ------------------------------ -- Search for the first occurrence of the character in the string -- before the from index and going backward. -- This implementation is 3-times faster than the Ada.Strings.Fixed version. -- Returns the index of the first occurrence or 0. -- ------------------------------ function Rindex (Source : in String; Ch : in Character; From : in Natural := 0) return Natural is Pos : Natural := From; begin if Pos < Source'First then Pos := Source'Last; end if; for I in reverse Source'First .. Pos loop if Source (I) = Ch then return I; end if; end loop; return 0; end Rindex; end Util.Strings;
----------------------------------------------------------------------- -- util-strings -- Various String Utility -- Copyright (C) 2001, 2002, 2003, 2009, 2010, 2011, 2012, 2017 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Strings.Fixed; with Ada.Strings.Hash; with Ada.Unchecked_Deallocation; package body Util.Strings is -- ------------------------------ -- Compute the hash value of the string. -- ------------------------------ function Hash (Key : Name_Access) return Ada.Containers.Hash_Type is begin return Ada.Strings.Hash (Key.all); end Hash; -- ------------------------------ -- Returns true if left and right strings are equivalent. -- ------------------------------ function Equivalent_Keys (Left, Right : Name_Access) return Boolean is begin if Left = null or Right = null then return False; end if; return Left.all = Right.all; end Equivalent_Keys; -- ------------------------------ -- Returns Integer'Image (Value) with the possible space stripped. -- ------------------------------ function Image (Value : in Integer) return String is S : constant String := Integer'Image (Value); begin if S (S'First) = ' ' then return S (S'First + 1 .. S'Last); else return S; end if; end Image; -- ------------------------------ -- Returns Integer'Image (Value) with the possible space stripped. -- ------------------------------ function Image (Value : in Long_Long_Integer) return String is S : constant String := Long_Long_Integer'Image (Value); begin if S (S'First) = ' ' then return S (S'First + 1 .. S'Last); else return S; end if; end Image; use Util.Concurrent.Counters; -- ------------------------------ -- Create a string reference from a string. -- ------------------------------ function To_String_Ref (S : in String) return String_Ref is Str : constant String_Record_Access := new String_Record '(Len => S'Length, Str => S, Counter => ONE); begin return String_Ref '(Ada.Finalization.Controlled with Str => Str); end To_String_Ref; -- ------------------------------ -- Create a string reference from an unbounded string. -- ------------------------------ function To_String_Ref (S : in Ada.Strings.Unbounded.Unbounded_String) return String_Ref is use Ada.Strings.Unbounded; Len : constant Natural := Length (S); Str : constant String_Record_Access := new String_Record '(Len => Len, Str => To_String (S), Counter => ONE); begin return String_Ref '(Ada.Finalization.Controlled with Str => Str); end To_String_Ref; -- ------------------------------ -- Get the string -- ------------------------------ function To_String (S : in String_Ref) return String is begin if S.Str = null then return ""; else return S.Str.Str; end if; end To_String; -- ------------------------------ -- Get the string as an unbounded string -- ------------------------------ function To_Unbounded_String (S : in String_Ref) return Ada.Strings.Unbounded.Unbounded_String is begin if S.Str = null then return Ada.Strings.Unbounded.Null_Unbounded_String; else return Ada.Strings.Unbounded.To_Unbounded_String (S.Str.Str); end if; end To_Unbounded_String; -- ------------------------------ -- Compute the hash value of the string reference. -- ------------------------------ function Hash (Key : String_Ref) return Ada.Containers.Hash_Type is begin if Key.Str = null then return 0; else return Ada.Strings.Hash (Key.Str.Str); end if; end Hash; -- ------------------------------ -- Returns true if left and right string references are equivalent. -- ------------------------------ function Equivalent_Keys (Left, Right : String_Ref) return Boolean is begin if Left.Str = Right.Str then return True; elsif Left.Str = null or Right.Str = null then return False; else return Left.Str.Str = Right.Str.Str; end if; end Equivalent_Keys; function "=" (Left : in String_Ref; Right : in String) return Boolean is begin if Left.Str = null then return False; else return Left.Str.Str = Right; end if; end "="; function "=" (Left : in String_Ref; Right : in Ada.Strings.Unbounded.Unbounded_String) return Boolean is use Ada.Strings.Unbounded; begin if Left.Str = null then return Right = Null_Unbounded_String; else return Right = Left.Str.Str; end if; end "="; -- ------------------------------ -- Returns the string length. -- ------------------------------ function Length (S : in String_Ref) return Natural is begin if S.Str = null then return 0; else return S.Str.Len; end if; end Length; -- ------------------------------ -- Increment the reference counter. -- ------------------------------ overriding procedure Adjust (Object : in out String_Ref) is begin if Object.Str /= null then Util.Concurrent.Counters.Increment (Object.Str.Counter); end if; end Adjust; -- ------------------------------ -- Decrement the reference counter and free the allocated string. -- ------------------------------ overriding procedure Finalize (Object : in out String_Ref) is procedure Free is new Ada.Unchecked_Deallocation (String_Record, String_Record_Access); Is_Zero : Boolean; begin if Object.Str /= null then Util.Concurrent.Counters.Decrement (Object.Str.Counter, Is_Zero); if Is_Zero then Free (Object.Str); else Object.Str := null; end if; end if; end Finalize; -- ------------------------------ -- Search for the first occurrence of the character in the string -- after the from index. This implementation is 3-times faster than -- the Ada.Strings.Fixed version. -- Returns the index of the first occurrence or 0. -- ------------------------------ function Index (Source : in String; Char : in Character; From : in Natural := 0) return Natural is Pos : Natural := From; begin if Pos < Source'First then Pos := Source'First; end if; for I in Pos .. Source'Last loop if Source (I) = Char then return I; end if; end loop; return 0; end Index; -- ------------------------------ -- Search for the first occurrence of the pattern in the string. -- ------------------------------ function Index (Source : in String; Pattern : in String; From : in Positive; Going : in Ada.Strings.Direction := Ada.Strings.Forward) return Natural is begin return Ada.Strings.Fixed.Index (Source, Pattern, From, Going); end Index; -- ------------------------------ -- Search for the first occurrence of the character in the string -- before the from index and going backward. -- This implementation is 3-times faster than the Ada.Strings.Fixed version. -- Returns the index of the first occurrence or 0. -- ------------------------------ function Rindex (Source : in String; Ch : in Character; From : in Natural := 0) return Natural is Pos : Natural := From; begin if Pos < Source'First then Pos := Source'Last; end if; for I in reverse Source'First .. Pos loop if Source (I) = Ch then return I; end if; end loop; return 0; end Rindex; end Util.Strings;
Update the header and invert some if condition as per AdaControl recommendation
Update the header and invert some if condition as per AdaControl recommendation
Ada
apache-2.0
stcarrez/ada-util,stcarrez/ada-util
940aa0e7dc1234d1c66598c984612197406bc2c6
src/wiki-parsers.ads
src/wiki-parsers.ads
----------------------------------------------------------------------- -- wiki-parsers -- Wiki parser -- Copyright (C) 2011, 2015, 2016 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Wiki.Attributes; with Wiki.Plugins; with Wiki.Filters; with Wiki.Strings; with Wiki.Documents; with Wiki.Streams; -- === Wiki Parsers === -- The <b>Wikis.Parsers</b> package implements a parser for several well known wiki formats -- but also for HTML. While reading the input, the parser populates a wiki <tt>Document</tt> -- instance with headers, paragraphs, links, and other elements. -- -- Engine : Wiki.Parsers.Parser; -- -- Before using the parser, it must be configured to choose the syntax by using the -- <tt>Set_Syntax</tt> procedure: -- -- Engine.Set_Syntax (Wiki.SYNTAX_HTML); -- -- The parser can be configured to use filters. A filter is added by using the -- <tt>Add_Filter</tt> procedure. A filter is added at begining of the chain so that -- the filter added last is called first. The wiki <tt>Document</tt> is always built through -- the filter chain so this allows filters to change or alter the content that was parsed. -- -- Engine.Add_Filter (TOC'Unchecked_Access); -- Engine.Add_Filter (Filter'Unchecked_Access); -- -- The <tt>Parse</tt> procedure is then used to parse either a string content or some stream -- represented by the <tt>Input_Stream</tt> interface. After the <tt>Parse</tt> procedure -- completes, the <tt>Document</tt> instance holds the wiki document. -- -- Engine.Parse (Some_Text, Doc); -- package Wiki.Parsers is pragma Preelaborate; type Parser is tagged limited private; -- Set the plugin factory to find and use plugins. procedure Set_Plugin_Factory (Engine : in out Parser; Factory : in Wiki.Plugins.Plugin_Factory_Access); -- Set the wiki syntax that the wiki engine must use. procedure Set_Syntax (Engine : in out Parser; Syntax : in Wiki_Syntax := SYNTAX_MIX); -- Add a filter in the wiki engine. procedure Add_Filter (Engine : in out Parser; Filter : in Wiki.Filters.Filter_Type_Access); -- Set the plugin context. procedure Set_Context (Engine : in out Parser; Context : in Wiki.Plugins.Plugin_Context); -- Parse the wiki text contained in <b>Text</b> according to the wiki syntax -- defined on the parser. The string is assumed to be in UTF-8 format. procedure Parse (Engine : in out Parser; Text : in String; Doc : in out Wiki.Documents.Document); -- Parse the wiki text contained in <b>Text</b> according to the wiki syntax -- defined on the parser. procedure Parse (Engine : in out Parser; Text : in Wiki.Strings.WString; Doc : in out Wiki.Documents.Document); -- Parse the wiki text contained in <b>Text</b> according to the wiki syntax -- defined on the parser. procedure Parse (Engine : in out Parser; Text : in Wiki.Strings.UString; Doc : in out Wiki.Documents.Document); -- Parse the wiki stream managed by <tt>Stream</tt> according to the wiki syntax configured -- on the wiki engine. procedure Parse (Engine : in out Parser; Stream : in Wiki.Streams.Input_Stream_Access; Doc : in out Wiki.Documents.Document); private type Parser_Handler is access procedure (P : in out Parser; Token : in Wiki.Strings.WChar); type Parser_Table is array (0 .. 127) of Parser_Handler; type Parser_Table_Access is access constant Parser_Table; type Parser is tagged limited record Context : Wiki.Plugins.Plugin_Context; Pending : Wiki.Strings.WChar; Has_Pending : Boolean; Previous_Syntax : Wiki_Syntax; Table : Parser_Table_Access; Document : Wiki.Documents.Document; Format : Wiki.Format_Map; Text : Wiki.Strings.BString (512); Empty_Line : Boolean := True; Is_Eof : Boolean := False; In_Paragraph : Boolean := False; In_List : Boolean := False; Need_Paragraph : Boolean := True; Link_Double_Bracket : Boolean := False; Link_No_Space : Boolean := False; Is_Dotclear : Boolean := False; Link_Title_First : Boolean := False; Check_Image_Link : Boolean := False; Is_Hidden : Boolean := False; Header_Offset : Integer := 0; Quote_Level : Natural := 0; Escape_Char : Wiki.Strings.WChar; Param_Char : Wiki.Strings.WChar; List_Level : Natural := 0; Reader : Wiki.Streams.Input_Stream_Access := null; Attributes : Wiki.Attributes.Attribute_List; end record; -- Peek the next character from the wiki text buffer. procedure Peek (P : in out Parser'Class; Token : out Wiki.Strings.WChar); pragma Inline (Peek); -- Put back the character so that it will be returned by the next call to Peek. procedure Put_Back (P : in out Parser; Token : in Wiki.Strings.WChar); -- Skip all the spaces and tabs as well as end of the current line (CR+LF). procedure Skip_End_Of_Line (P : in out Parser); -- Skip white spaces and tabs. procedure Skip_Spaces (P : in out Parser); -- Flush the wiki text that was collected in the text buffer. procedure Flush_Text (P : in out Parser); -- Flush the wiki dl/dt/dd definition list. procedure Flush_List (P : in out Parser); -- Append a character to the wiki text buffer. procedure Parse_Text (P : in out Parser; Token : in Wiki.Strings.WChar); -- Check if the link refers to an image and must be rendered as an image. -- Returns a positive index of the start the the image link. function Is_Image (P : in Parser; Link : in Wiki.Strings.WString) return Natural; -- Find the plugin with the given name. -- Returns null if there is no such plugin. function Find (P : in Parser; Name : in Wiki.Strings.WString) return Wiki.Plugins.Wiki_Plugin_Access; type String_Array is array (Positive range <>) of Wiki.String_Access; -- Extract a list of parameters separated by the given separator (ex: '|'). procedure Parse_Parameters (P : in out Parser; Separator : in Wiki.Strings.WChar; Terminator : in Wiki.Strings.WChar; Names : in String_Array; Max : in Positive := 200); procedure Start_Element (P : in out Parser; Tag : in Wiki.Html_Tag; Attributes : in out Wiki.Attributes.Attribute_List); procedure End_Element (P : in out Parser; Tag : in Wiki.Html_Tag); procedure Parse_Token (P : in out Parser); end Wiki.Parsers;
----------------------------------------------------------------------- -- wiki-parsers -- Wiki parser -- Copyright (C) 2011, 2015, 2016 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Wiki.Attributes; with Wiki.Plugins; with Wiki.Filters; with Wiki.Strings; with Wiki.Documents; with Wiki.Streams; -- === Wiki Parsers === -- The <b>Wikis.Parsers</b> package implements a parser for several well known wiki formats -- but also for HTML. While reading the input, the parser populates a wiki <tt>Document</tt> -- instance with headers, paragraphs, links, and other elements. -- -- Engine : Wiki.Parsers.Parser; -- -- Before using the parser, it must be configured to choose the syntax by using the -- <tt>Set_Syntax</tt> procedure: -- -- Engine.Set_Syntax (Wiki.SYNTAX_HTML); -- -- The parser can be configured to use filters. A filter is added by using the -- <tt>Add_Filter</tt> procedure. A filter is added at begining of the chain so that -- the filter added last is called first. The wiki <tt>Document</tt> is always built through -- the filter chain so this allows filters to change or alter the content that was parsed. -- -- Engine.Add_Filter (TOC'Unchecked_Access); -- Engine.Add_Filter (Filter'Unchecked_Access); -- -- The <tt>Parse</tt> procedure is then used to parse either a string content or some stream -- represented by the <tt>Input_Stream</tt> interface. After the <tt>Parse</tt> procedure -- completes, the <tt>Document</tt> instance holds the wiki document. -- -- Engine.Parse (Some_Text, Doc); -- package Wiki.Parsers is pragma Preelaborate; type Parser is tagged limited private; -- Set the plugin factory to find and use plugins. procedure Set_Plugin_Factory (Engine : in out Parser; Factory : in Wiki.Plugins.Plugin_Factory_Access); -- Set the wiki syntax that the wiki engine must use. procedure Set_Syntax (Engine : in out Parser; Syntax : in Wiki_Syntax := SYNTAX_MIX); -- Add a filter in the wiki engine. procedure Add_Filter (Engine : in out Parser; Filter : in Wiki.Filters.Filter_Type_Access); -- Set the plugin context. procedure Set_Context (Engine : in out Parser; Context : in Wiki.Plugins.Plugin_Context); -- Parse the wiki text contained in <b>Text</b> according to the wiki syntax -- defined on the parser. The string is assumed to be in UTF-8 format. procedure Parse (Engine : in out Parser; Text : in String; Doc : in out Wiki.Documents.Document); -- Parse the wiki text contained in <b>Text</b> according to the wiki syntax -- defined on the parser. procedure Parse (Engine : in out Parser; Text : in Wiki.Strings.WString; Doc : in out Wiki.Documents.Document); -- Parse the wiki text contained in <b>Text</b> according to the wiki syntax -- defined on the parser. procedure Parse (Engine : in out Parser; Text : in Wiki.Strings.UString; Doc : in out Wiki.Documents.Document); -- Parse the wiki stream managed by <tt>Stream</tt> according to the wiki syntax configured -- on the wiki engine. procedure Parse (Engine : in out Parser; Stream : in Wiki.Streams.Input_Stream_Access; Doc : in out Wiki.Documents.Document); private type Parser_Handler is access procedure (P : in out Parser; Token : in Wiki.Strings.WChar); type Parser_Table is array (0 .. 127) of Parser_Handler; type Parser_Table_Access is access constant Parser_Table; type Parser is tagged limited record Context : Wiki.Plugins.Plugin_Context; Pending : Wiki.Strings.WChar; Has_Pending : Boolean; Previous_Syntax : Wiki_Syntax; Table : Parser_Table_Access; Document : Wiki.Documents.Document; Format : Wiki.Format_Map; Text : Wiki.Strings.BString (512); Empty_Line : Boolean := True; Is_Eof : Boolean := False; In_Paragraph : Boolean := False; In_List : Boolean := False; Need_Paragraph : Boolean := True; Link_Double_Bracket : Boolean := False; Link_No_Space : Boolean := False; Is_Dotclear : Boolean := False; Link_Title_First : Boolean := False; Check_Image_Link : Boolean := False; Is_Hidden : Boolean := False; Header_Offset : Integer := 0; Preformat_Column : Natural := 1; Quote_Level : Natural := 0; Escape_Char : Wiki.Strings.WChar; Param_Char : Wiki.Strings.WChar; List_Level : Natural := 0; Reader : Wiki.Streams.Input_Stream_Access := null; Attributes : Wiki.Attributes.Attribute_List; end record; -- Peek the next character from the wiki text buffer. procedure Peek (P : in out Parser'Class; Token : out Wiki.Strings.WChar); pragma Inline (Peek); -- Put back the character so that it will be returned by the next call to Peek. procedure Put_Back (P : in out Parser; Token : in Wiki.Strings.WChar); -- Skip all the spaces and tabs as well as end of the current line (CR+LF). procedure Skip_End_Of_Line (P : in out Parser); -- Skip white spaces and tabs. procedure Skip_Spaces (P : in out Parser); -- Flush the wiki text that was collected in the text buffer. procedure Flush_Text (P : in out Parser); -- Flush the wiki dl/dt/dd definition list. procedure Flush_List (P : in out Parser); -- Append a character to the wiki text buffer. procedure Parse_Text (P : in out Parser; Token : in Wiki.Strings.WChar); -- Check if the link refers to an image and must be rendered as an image. -- Returns a positive index of the start the the image link. function Is_Image (P : in Parser; Link : in Wiki.Strings.WString) return Natural; -- Find the plugin with the given name. -- Returns null if there is no such plugin. function Find (P : in Parser; Name : in Wiki.Strings.WString) return Wiki.Plugins.Wiki_Plugin_Access; type String_Array is array (Positive range <>) of Wiki.String_Access; -- Extract a list of parameters separated by the given separator (ex: '|'). procedure Parse_Parameters (P : in out Parser; Separator : in Wiki.Strings.WChar; Terminator : in Wiki.Strings.WChar; Names : in String_Array; Max : in Positive := 200); procedure Start_Element (P : in out Parser; Tag : in Wiki.Html_Tag; Attributes : in out Wiki.Attributes.Attribute_List); procedure End_Element (P : in out Parser; Tag : in Wiki.Html_Tag); procedure Parse_Token (P : in out Parser); end Wiki.Parsers;
Add Preformat_Column member to the Parser type record
Add Preformat_Column member to the Parser type record
Ada
apache-2.0
stcarrez/ada-wiki,stcarrez/ada-wiki
9c9cba930b663213aadff398340288d262ea8b2e
awa/plugins/awa-questions/src/awa-questions-beans.adb
awa/plugins/awa-questions/src/awa-questions-beans.adb
----------------------------------------------------------------------- -- awa-questions-beans -- Beans for module questions -- Copyright (C) 2012, 2013 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- package body AWA.Questions.Beans is -- ------------------------------ -- Get the value identified by the name. -- ------------------------------ overriding function Get_Value (From : in Question_Bean; Name : in String) return Util.Beans.Objects.Object is begin if Name = "count" then return Util.Beans.Objects.To_Object (From.Count); else return Util.Beans.Objects.Null_Object; end if; end Get_Value; -- ------------------------------ -- Set the value identified by the name. -- ------------------------------ overriding procedure Set_Value (From : in out Question_Bean; Name : in String; Value : in Util.Beans.Objects.Object) is begin if Name = "count" then From.Count := Util.Beans.Objects.To_Integer (Value); end if; end Set_Value; procedure Save (Bean : in out Question_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is begin null; end Save; procedure Delete (Bean : in out Question_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is begin null; end Delete; -- ------------------------------ -- Create the Question_Bean bean instance. -- ------------------------------ function Create_Question_Bean (Module : in AWA.Questions.Modules.Question_Module_Access) return Util.Beans.Basic.Readonly_Bean_Access is Object : constant Question_Bean_Access := new Question_Bean; begin Object.Module := Module; return Object.all'Access; end Create_Question_Bean; end AWA.Questions.Beans;
----------------------------------------------------------------------- -- awa-questions-beans -- Beans for module questions -- Copyright (C) 2012, 2013 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with AWA.Questions.Services; package body AWA.Questions.Beans is -- ------------------------------ -- Get the value identified by the name. -- ------------------------------ overriding function Get_Value (From : in Question_Bean; Name : in String) return Util.Beans.Objects.Object is begin if Name = "count" then return Util.Beans.Objects.To_Object (From.Count); else return Util.Beans.Objects.Null_Object; end if; end Get_Value; -- ------------------------------ -- Set the value identified by the name. -- ------------------------------ overriding procedure Set_Value (From : in out Question_Bean; Name : in String; Value : in Util.Beans.Objects.Object) is begin if Name = "count" then From.Count := Util.Beans.Objects.To_Integer (Value); end if; end Set_Value; procedure Save (Bean : in out Question_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is Manager : constant Services.Question_Service_Access := Bean.Module.Get_Question_Manager; begin Manager.Save_Question (Bean); end Save; procedure Delete (Bean : in out Question_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is begin null; end Delete; -- ------------------------------ -- Create the Question_Bean bean instance. -- ------------------------------ function Create_Question_Bean (Module : in AWA.Questions.Modules.Question_Module_Access) return Util.Beans.Basic.Readonly_Bean_Access is Object : constant Question_Bean_Access := new Question_Bean; begin Object.Module := Module; return Object.all'Access; end Create_Question_Bean; end AWA.Questions.Beans;
Use the question manager to save/create the question
Use the question manager to save/create the question
Ada
apache-2.0
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
6e97e42b2c7c2033a5046b3925360588f73140a4
src/base/dates/util-dates-rfc7231.ads
src/base/dates/util-dates-rfc7231.ads
----------------------------------------------------------------------- -- util-dates-rfc7231-- RFC7231 date format utilities -- Copyright (C) 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.Calendar; with Util.Strings.Builders; -- == RFC7231 Dates == -- The RFC7231 defines a standard date format that is used by HTTP headers. -- The `Util.Dates.RFC7231` package provides an `Image` function to convert a date into -- that target format and a `Value` function to parse such format string and return the date. -- -- Now : constant Ada.Calendar.Time := Ada.Calendar.Clock; -- S : constant String := Util.Dates.RFC7231.Image (Now); -- Date : Ada.Calendar.time := Util.Dates.RFC7231.Value (S); -- -- A `Constraint_Error` exception is raised when the date string is not in the correct format. package Util.Dates.RFC7231 is -- Parses a HTTP date that follows the RFC7231 or RFC2616 format. -- Raises Constraint_Error if the date format is not recognized. function Value (Date : in String) return Ada.Calendar.Time; -- Return the RFC7231/RFC2616 date format. function Image (Date : in Ada.Calendar.Time) return String; -- Append the date in RFC7231/RFC2616 format in the string builder. -- The date separator can be changed to '-' to generate a cookie expires date. procedure Append_Date (Into : in out Util.Strings.Builders.Builder; Date : in Ada.Calendar.Time; Date_Separator : in Character := ' '); end Util.Dates.RFC7231;
----------------------------------------------------------------------- -- util-dates-rfc7231-- RFC7231 date format utilities -- Copyright (C) 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.Calendar; with Util.Strings.Builders; -- == RFC7231 Dates == -- The RFC 7231 defines a standard date format that is used by HTTP headers. -- The `Util.Dates.RFC7231` package provides an `Image` function to convert a date into -- that target format and a `Value` function to parse such format string and return the date. -- -- Now : constant Ada.Calendar.Time := Ada.Calendar.Clock; -- S : constant String := Util.Dates.RFC7231.Image (Now); -- Date : Ada.Calendar.time := Util.Dates.RFC7231.Value (S); -- -- A `Constraint_Error` exception is raised when the date string is not in the correct format. package Util.Dates.RFC7231 is -- Parses a HTTP date that follows the RFC7231 or RFC2616 format. -- Raises Constraint_Error if the date format is not recognized. function Value (Date : in String) return Ada.Calendar.Time; -- Return the RFC7231/RFC2616 date format. function Image (Date : in Ada.Calendar.Time) return String; -- Append the date in RFC7231/RFC2616 format in the string builder. -- The date separator can be changed to '-' to generate a cookie expires date. procedure Append_Date (Into : in out Util.Strings.Builders.Builder; Date : in Ada.Calendar.Time; Date_Separator : in Character := ' '); end Util.Dates.RFC7231;
Fix typo in comment
Fix typo in comment
Ada
apache-2.0
stcarrez/ada-util,stcarrez/ada-util
187a104b0b80fef3b0d1ce0327ab11b13b3fe671
src/wiki-parsers.ads
src/wiki-parsers.ads
----------------------------------------------------------------------- -- wiki-parsers -- Wiki parser -- Copyright (C) 2011, 2015, 2016 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Wiki.Attributes; with Wiki.Plugins; with Wiki.Filters; with Wiki.Strings; with Wiki.Documents; with Wiki.Streams; -- === Wiki Parsers === -- The <b>Wikis.Parsers</b> package implements a parser for several well known wiki formats -- but also for HTML. While reading the input, the parser populates a wiki <tt>Document</tt> -- instance with headers, paragraphs, links, and other elements. -- -- Engine : Wiki.Parsers.Parser; -- -- Before using the parser, it must be configured to choose the syntax by using the -- <tt>Set_Syntax</tt> procedure: -- -- Engine.Set_Syntax (Wiki.SYNTAX_HTML); -- -- The parser can be configured to use filters. A filter is added by using the -- <tt>Add_Filter</tt> procedure. A filter is added at begining of the chain so that -- the filter added last is called first. The wiki <tt>Document</tt> is always built through -- the filter chain so this allows filters to change or alter the content that was parsed. -- -- Engine.Add_Filter (TOC'Unchecked_Access); -- Engine.Add_Filter (Filter'Unchecked_Access); -- -- The <tt>Parse</tt> procedure is then used to parse either a string content or some stream -- represented by the <tt>Input_Stream</tt> interface. After the <tt>Parse</tt> procedure -- completes, the <tt>Document</tt> instance holds the wiki document. -- -- Engine.Parse (Some_Text, Doc); -- package Wiki.Parsers is pragma Preelaborate; type Parser is tagged limited private; -- Set the plugin factory to find and use plugins. procedure Set_Plugin_Factory (Engine : in out Parser; Factory : in Wiki.Plugins.Plugin_Factory_Access); -- Set the wiki syntax that the wiki engine must use. procedure Set_Syntax (Engine : in out Parser; Syntax : in Wiki_Syntax := SYNTAX_MIX); -- Add a filter in the wiki engine. procedure Add_Filter (Engine : in out Parser; Filter : in Wiki.Filters.Filter_Type_Access); -- Set the plugin context. procedure Set_Context (Engine : in out Parser; Context : in Wiki.Plugins.Plugin_Context); -- Parse the wiki text contained in <b>Text</b> according to the wiki syntax -- defined on the parser. procedure Parse (Engine : in out Parser; Text : in Wiki.Strings.WString; Doc : in out Wiki.Documents.Document); -- Parse the wiki text contained in <b>Text</b> according to the wiki syntax -- defined on the parser. procedure Parse (Engine : in out Parser; Text : in Wiki.Strings.UString; Doc : in out Wiki.Documents.Document); -- Parse the wiki stream managed by <tt>Stream</tt> according to the wiki syntax configured -- on the wiki engine. procedure Parse (Engine : in out Parser; Stream : in Wiki.Streams.Input_Stream_Access; Doc : in out Wiki.Documents.Document); private type Parser_Handler is access procedure (P : in out Parser; Token : in Wiki.Strings.WChar); type Parser_Table is array (0 .. 127) of Parser_Handler; type Parser_Table_Access is access constant Parser_Table; type Parser is tagged limited record Context : Wiki.Plugins.Plugin_Context; Pending : Wiki.Strings.WChar; Has_Pending : Boolean; Previous_Syntax : Wiki_Syntax; Table : Parser_Table_Access; Document : Wiki.Documents.Document; Format : Wiki.Format_Map; Text : Wiki.Strings.BString (512); Empty_Line : Boolean := True; Is_Eof : Boolean := False; In_Paragraph : Boolean := False; In_List : Boolean := False; Need_Paragraph : Boolean := True; Link_Double_Bracket : Boolean := False; Link_No_Space : Boolean := False; Is_Dotclear : Boolean := False; Link_Title_First : Boolean := False; Check_Image_Link : Boolean := False; Is_Hidden : Boolean := False; Header_Offset : Integer := 0; Quote_Level : Natural := 0; Escape_Char : Wiki.Strings.WChar; Param_Char : Wiki.Strings.WChar; List_Level : Natural := 0; Reader : Wiki.Streams.Input_Stream_Access := null; Attributes : Wiki.Attributes.Attribute_List; end record; -- Peek the next character from the wiki text buffer. procedure Peek (P : in out Parser'Class; Token : out Wiki.Strings.WChar); pragma Inline (Peek); -- Put back the character so that it will be returned by the next call to Peek. procedure Put_Back (P : in out Parser; Token : in Wiki.Strings.WChar); -- Skip all the spaces and tabs as well as end of the current line (CR+LF). procedure Skip_End_Of_Line (P : in out Parser); -- Skip white spaces and tabs. procedure Skip_Spaces (P : in out Parser); -- Flush the wiki text that was collected in the text buffer. procedure Flush_Text (P : in out Parser); -- Flush the wiki dl/dt/dd definition list. procedure Flush_List (P : in out Parser); -- Append a character to the wiki text buffer. procedure Parse_Text (P : in out Parser; Token : in Wiki.Strings.WChar); -- Check if the link refers to an image and must be rendered as an image. -- Returns a positive index of the start the the image link. function Is_Image (P : in Parser; Link : in Wiki.Strings.WString) return Natural; -- Find the plugin with the given name. -- Returns null if there is no such plugin. function Find (P : in Parser; Name : in Wiki.Strings.WString) return Wiki.Plugins.Wiki_Plugin_Access; type String_Array is array (Positive range <>) of Wiki.String_Access; -- Extract a list of parameters separated by the given separator (ex: '|'). procedure Parse_Parameters (P : in out Parser; Separator : in Wiki.Strings.WChar; Terminator : in Wiki.Strings.WChar; Names : in String_Array; Max : in Positive := 200); procedure Start_Element (P : in out Parser; Tag : in Wiki.Html_Tag; Attributes : in out Wiki.Attributes.Attribute_List); procedure End_Element (P : in out Parser; Tag : in Wiki.Html_Tag); procedure Parse_Token (P : in out Parser); end Wiki.Parsers;
----------------------------------------------------------------------- -- wiki-parsers -- Wiki parser -- Copyright (C) 2011, 2015, 2016 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Wiki.Attributes; with Wiki.Plugins; with Wiki.Filters; with Wiki.Strings; with Wiki.Documents; with Wiki.Streams; -- === Wiki Parsers === -- The <b>Wikis.Parsers</b> package implements a parser for several well known wiki formats -- but also for HTML. While reading the input, the parser populates a wiki <tt>Document</tt> -- instance with headers, paragraphs, links, and other elements. -- -- Engine : Wiki.Parsers.Parser; -- -- Before using the parser, it must be configured to choose the syntax by using the -- <tt>Set_Syntax</tt> procedure: -- -- Engine.Set_Syntax (Wiki.SYNTAX_HTML); -- -- The parser can be configured to use filters. A filter is added by using the -- <tt>Add_Filter</tt> procedure. A filter is added at begining of the chain so that -- the filter added last is called first. The wiki <tt>Document</tt> is always built through -- the filter chain so this allows filters to change or alter the content that was parsed. -- -- Engine.Add_Filter (TOC'Unchecked_Access); -- Engine.Add_Filter (Filter'Unchecked_Access); -- -- The <tt>Parse</tt> procedure is then used to parse either a string content or some stream -- represented by the <tt>Input_Stream</tt> interface. After the <tt>Parse</tt> procedure -- completes, the <tt>Document</tt> instance holds the wiki document. -- -- Engine.Parse (Some_Text, Doc); -- package Wiki.Parsers is pragma Preelaborate; type Parser is tagged limited private; -- Set the plugin factory to find and use plugins. procedure Set_Plugin_Factory (Engine : in out Parser; Factory : in Wiki.Plugins.Plugin_Factory_Access); -- Set the wiki syntax that the wiki engine must use. procedure Set_Syntax (Engine : in out Parser; Syntax : in Wiki_Syntax := SYNTAX_MIX); -- Add a filter in the wiki engine. procedure Add_Filter (Engine : in out Parser; Filter : in Wiki.Filters.Filter_Type_Access); -- Set the plugin context. procedure Set_Context (Engine : in out Parser; Context : in Wiki.Plugins.Plugin_Context); -- Parse the wiki text contained in <b>Text</b> according to the wiki syntax -- defined on the parser. The string is assumed to be in UTF-8 format. procedure Parse (Engine : in out Parser; Text : in String; Doc : in out Wiki.Documents.Document); -- Parse the wiki text contained in <b>Text</b> according to the wiki syntax -- defined on the parser. procedure Parse (Engine : in out Parser; Text : in Wiki.Strings.WString; Doc : in out Wiki.Documents.Document); -- Parse the wiki text contained in <b>Text</b> according to the wiki syntax -- defined on the parser. procedure Parse (Engine : in out Parser; Text : in Wiki.Strings.UString; Doc : in out Wiki.Documents.Document); -- Parse the wiki stream managed by <tt>Stream</tt> according to the wiki syntax configured -- on the wiki engine. procedure Parse (Engine : in out Parser; Stream : in Wiki.Streams.Input_Stream_Access; Doc : in out Wiki.Documents.Document); private type Parser_Handler is access procedure (P : in out Parser; Token : in Wiki.Strings.WChar); type Parser_Table is array (0 .. 127) of Parser_Handler; type Parser_Table_Access is access constant Parser_Table; type Parser is tagged limited record Context : Wiki.Plugins.Plugin_Context; Pending : Wiki.Strings.WChar; Has_Pending : Boolean; Previous_Syntax : Wiki_Syntax; Table : Parser_Table_Access; Document : Wiki.Documents.Document; Format : Wiki.Format_Map; Text : Wiki.Strings.BString (512); Empty_Line : Boolean := True; Is_Eof : Boolean := False; In_Paragraph : Boolean := False; In_List : Boolean := False; Need_Paragraph : Boolean := True; Link_Double_Bracket : Boolean := False; Link_No_Space : Boolean := False; Is_Dotclear : Boolean := False; Link_Title_First : Boolean := False; Check_Image_Link : Boolean := False; Is_Hidden : Boolean := False; Header_Offset : Integer := 0; Quote_Level : Natural := 0; Escape_Char : Wiki.Strings.WChar; Param_Char : Wiki.Strings.WChar; List_Level : Natural := 0; Reader : Wiki.Streams.Input_Stream_Access := null; Attributes : Wiki.Attributes.Attribute_List; end record; -- Peek the next character from the wiki text buffer. procedure Peek (P : in out Parser'Class; Token : out Wiki.Strings.WChar); pragma Inline (Peek); -- Put back the character so that it will be returned by the next call to Peek. procedure Put_Back (P : in out Parser; Token : in Wiki.Strings.WChar); -- Skip all the spaces and tabs as well as end of the current line (CR+LF). procedure Skip_End_Of_Line (P : in out Parser); -- Skip white spaces and tabs. procedure Skip_Spaces (P : in out Parser); -- Flush the wiki text that was collected in the text buffer. procedure Flush_Text (P : in out Parser); -- Flush the wiki dl/dt/dd definition list. procedure Flush_List (P : in out Parser); -- Append a character to the wiki text buffer. procedure Parse_Text (P : in out Parser; Token : in Wiki.Strings.WChar); -- Check if the link refers to an image and must be rendered as an image. -- Returns a positive index of the start the the image link. function Is_Image (P : in Parser; Link : in Wiki.Strings.WString) return Natural; -- Find the plugin with the given name. -- Returns null if there is no such plugin. function Find (P : in Parser; Name : in Wiki.Strings.WString) return Wiki.Plugins.Wiki_Plugin_Access; type String_Array is array (Positive range <>) of Wiki.String_Access; -- Extract a list of parameters separated by the given separator (ex: '|'). procedure Parse_Parameters (P : in out Parser; Separator : in Wiki.Strings.WChar; Terminator : in Wiki.Strings.WChar; Names : in String_Array; Max : in Positive := 200); procedure Start_Element (P : in out Parser; Tag : in Wiki.Html_Tag; Attributes : in out Wiki.Attributes.Attribute_List); procedure End_Element (P : in out Parser; Tag : in Wiki.Html_Tag); procedure Parse_Token (P : in out Parser); end Wiki.Parsers;
Declare the Parse procedure with a String as parameter with UTF-8 conversion support
Declare the Parse procedure with a String as parameter with UTF-8 conversion support
Ada
apache-2.0
stcarrez/ada-wiki,stcarrez/ada-wiki
1b7a0b54585926563e2ec5c2baca3fc4ec4dc390
src/ado-c.ads
src/ado-c.ads
----------------------------------------------------------------------- -- ado-c -- Support for driver implementation -- Copyright (C) 2009, 2010, 2011, 2012, 2018 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Interfaces.C; with Interfaces.C.Strings; with Ada.Finalization; with Ada.Strings.Unbounded; with Ada.Unchecked_Conversion; with System; package ADO.C is type String_Ptr is limited private; -- Convert a string to a C string. function To_String_Ptr (S : String) return String_Ptr; -- Get the C string pointer. function To_C (S : String_Ptr) return Interfaces.C.Strings.chars_ptr; -- Set the string procedure Set_String (S : in out String_Ptr; Value : in String); function To_chars_ptr is new Ada.Unchecked_Conversion (System.Address, Interfaces.C.Strings.chars_ptr); private use Interfaces.C; type String_Ptr is new Ada.Finalization.Limited_Controlled with record Ptr : Strings.chars_ptr := Interfaces.C.Strings.Null_Ptr; end record; -- Reclaim the storage held by the C string. procedure Finalize (S : in out String_Ptr); end ADO.C;
----------------------------------------------------------------------- -- ado-c -- Support for driver implementation -- Copyright (C) 2009, 2010, 2011, 2012, 2018 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Interfaces.C; with Interfaces.C.Strings; with Ada.Finalization; with Ada.Unchecked_Conversion; with System; package ADO.C is type String_Ptr is limited private; -- Convert a string to a C string. function To_String_Ptr (S : String) return String_Ptr; -- Get the C string pointer. function To_C (S : String_Ptr) return Interfaces.C.Strings.chars_ptr; -- Set the string procedure Set_String (S : in out String_Ptr; Value : in String); function To_chars_ptr is new Ada.Unchecked_Conversion (System.Address, Interfaces.C.Strings.chars_ptr); private use Interfaces.C; type String_Ptr is new Ada.Finalization.Limited_Controlled with record Ptr : Strings.chars_ptr := Interfaces.C.Strings.Null_Ptr; end record; -- Reclaim the storage held by the C string. procedure Finalize (S : in out String_Ptr); end ADO.C;
Fix compilation warning
Fix compilation warning
Ada
apache-2.0
stcarrez/ada-ado
2ce5fb5d5ba12bba2b77d83877d6355801eebb30
src/wiki-nodes.ads
src/wiki-nodes.ads
----------------------------------------------------------------------- -- wiki -- Ada Wiki Engine -- Copyright (C) 2016 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Wiki.Attributes; with Wiki.Documents; package Wiki.Nodes is subtype Format_Map is Wiki.Documents.Format_Map; subtype WString is Wide_Wide_String; type Node_Kind is (N_HEADER, N_LINE_BREAK, N_HORIZONTAL_RULE, N_PARAGRAPH, N_BLOCKQUOTE, N_QUOTE, N_TAG_START, N_TAG_END, N_INDENT, N_TEXT, N_LINK, N_IMAGE); -- The possible HTML tags as described in HTML5 specification. type Html_Tag_Type is ( -- Section 4.1 The root element HTML_TAG, -- Section 4.2 Document metadata HEAD_TAG, TITLE_TAG, BASE_TAG, LINK_TAG, META_TAG, STYLE_TAG, -- Section 4.3 Sections BODY_TAG, ARTICLE_TAG, SECTION_TAG, NAV_TAG, ASIDE_TAG, H1_TAG, H2_TAG, H3_TAG, H4_TAG, H5_TAG, H6_TAG, HEADER_TAG, FOOTER_TAG, ADDRESS_TAG, -- Section 4.4 Grouping content P_TAG, HR_TAG, PRE_TAG, BLOCKQUOTE_TAG, OL_TAG, UL_TAG, LI_TAG, DL_TAG, DT_TAG, DD_TAG, FIGURE_TAG, FIGCAPTION_TAG, DIV_TAG, MAIN_TAG, -- Section 4.5 Text-level semantics A_TAG, EM_TAG, STRONG_TAG, SMALL_TAG, S_TAG, CITE_TAG, Q_TAG, DFN_TAG, ABBR_TAG, DATA_TAG, TIME_TAG, CODE_TAG, VAR_TAG, SAMP_TAG, KBD_TAG, SUB_TAG, SUP_TAG, I_TAG, B_TAG, U_TAG, MARK_TAG, RUBY_TAG, RB_TAG, RT_TAG, RTC_TAG, RP_TAG, BDI_TAG, BDO_TAG, SPAN_TAG, BR_TAG, WBR_TAG, -- Section 4.6 Edits INS_TAG, DEL_TAG, -- Section 4.7 Embedded content IMG_TAG, IFRAME_TAG, EMBED_TAG, OBJECT_TAG, PARAM_TAG, VIDEO_TAG, AUDIO_TAG, SOURCE_TAG, TRACK_TAG, MAP_TAG, AREA_TAG, -- Section 4.9 Tabular data TABLE_TAG, CAPTION_TAG, COLGROUP_TAG, COL_TAG, TBODY_TAG, THEAD_TAG, TFOOT_TAG, TR_TAG, TD_TAG, TH_TAG, -- Section 4.10 Forms FORM_TAG, LABEL_TAG, INPUT_TAG, BUTTON_TAG, SELECT_TAG, DATALIST_TAG, OPTGROUP_TAG, OPTION_TAG, TEXTAREA_TAG, KEYGEN_TAG, OUTPUT_TAG, PROGRESS_TAG, METER_TAG, FIELDSET_TAG, LEGEND_TAG, -- Section 4.11 Scripting SCRIPT_TAG, NOSCRIPT_TAG, TEMPLATE_TAG, CANVAS_TAG, -- Unknown tags UNKNOWN_TAG ); type Node_List is limited private; type Node_List_Access is access all Node_List; type Node_Type (Kind : Node_Kind; Len : Natural) is limited record case Kind is when N_HEADER | N_BLOCKQUOTE | N_INDENT => Level : Natural := 0; Header : WString (1 .. Len); when N_TEXT => Format : Format_Map; Text : WString (1 .. Len); when N_LINK | N_IMAGE => Link : Wiki.Attributes.Attribute_List_Type; when N_QUOTE => Quote : WString (1 .. Len); when N_TAG_START => Tag_Start : Html_Tag_Type; Attributes : Wiki.Attributes.Attribute_List_Type; Children : Node_List_Access; when N_TAG_END => Tag_End : Html_Tag_Type; when others => null; end case; end record; type Node_Type_Access is access all Node_Type; -- Create a text node. function Create_Text (Text : in WString) return Node_Type_Access; -- procedure Add_Text (Doc : in out Document; -- Text : in WString); -- type Renderer is limited interface; -- -- procedure Render (Engine : in out Renderer; -- Doc : in Document; -- Node : in Node_Type) is abstract; -- -- procedure Iterate (Doc : in Document; -- Process : access procedure (Doc : in Document; Node : in Node_Type)) is -- Node : Document_Node_Access := Doc.First; -- begin -- while Node /= null loop -- Process (Doc, Node.Data); -- Node := Node.Next; -- end loop; -- end Iterate; private NODE_LIST_BLOCK_SIZE : constant Positive := 20; type Node_Array is array (Positive range <>) of Node_Type_Access; type Node_List_Block; type Node_List_Block_Access is access all Node_List_Block; type Node_List_Block (Max : Positive) is limited record Next : Node_List_Block_Access; Last : Natural := 0; List : Node_Array (1 .. Max); end record; type Node_List is limited record Current : Node_List_Block_Access; Length : Natural := 0; First : Node_List_Block (NODE_LIST_BLOCK_SIZE); end record; -- Append a node to the node list. procedure Append (Into : in out Node_List; Node : in Node_Type_Access); type Document is limited record Nodes : Node_List; end record; end Wiki.Nodes;
----------------------------------------------------------------------- -- wiki -- Ada Wiki Engine -- Copyright (C) 2016 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Wiki.Attributes; with Wiki.Documents; package Wiki.Nodes is subtype Format_Map is Wiki.Documents.Format_Map; subtype WString is Wide_Wide_String; type Node_Kind is (N_HEADER, N_LINE_BREAK, N_HORIZONTAL_RULE, N_PARAGRAPH, N_BLOCKQUOTE, N_QUOTE, N_TAG_START, N_TAG_END, N_INDENT, N_TEXT, N_LINK, N_IMAGE); -- The possible HTML tags as described in HTML5 specification. type Html_Tag_Type is ( -- Section 4.1 The root element HTML_TAG, -- Section 4.2 Document metadata HEAD_TAG, TITLE_TAG, BASE_TAG, LINK_TAG, META_TAG, STYLE_TAG, -- Section 4.3 Sections BODY_TAG, ARTICLE_TAG, SECTION_TAG, NAV_TAG, ASIDE_TAG, H1_TAG, H2_TAG, H3_TAG, H4_TAG, H5_TAG, H6_TAG, HEADER_TAG, FOOTER_TAG, ADDRESS_TAG, -- Section 4.4 Grouping content P_TAG, HR_TAG, PRE_TAG, BLOCKQUOTE_TAG, OL_TAG, UL_TAG, LI_TAG, DL_TAG, DT_TAG, DD_TAG, FIGURE_TAG, FIGCAPTION_TAG, DIV_TAG, MAIN_TAG, -- Section 4.5 Text-level semantics A_TAG, EM_TAG, STRONG_TAG, SMALL_TAG, S_TAG, CITE_TAG, Q_TAG, DFN_TAG, ABBR_TAG, DATA_TAG, TIME_TAG, CODE_TAG, VAR_TAG, SAMP_TAG, KBD_TAG, SUB_TAG, SUP_TAG, I_TAG, B_TAG, U_TAG, MARK_TAG, RUBY_TAG, RB_TAG, RT_TAG, RTC_TAG, RP_TAG, BDI_TAG, BDO_TAG, SPAN_TAG, BR_TAG, WBR_TAG, -- Section 4.6 Edits INS_TAG, DEL_TAG, -- Section 4.7 Embedded content IMG_TAG, IFRAME_TAG, EMBED_TAG, OBJECT_TAG, PARAM_TAG, VIDEO_TAG, AUDIO_TAG, SOURCE_TAG, TRACK_TAG, MAP_TAG, AREA_TAG, -- Section 4.9 Tabular data TABLE_TAG, CAPTION_TAG, COLGROUP_TAG, COL_TAG, TBODY_TAG, THEAD_TAG, TFOOT_TAG, TR_TAG, TD_TAG, TH_TAG, -- Section 4.10 Forms FORM_TAG, LABEL_TAG, INPUT_TAG, BUTTON_TAG, SELECT_TAG, DATALIST_TAG, OPTGROUP_TAG, OPTION_TAG, TEXTAREA_TAG, KEYGEN_TAG, OUTPUT_TAG, PROGRESS_TAG, METER_TAG, FIELDSET_TAG, LEGEND_TAG, -- Section 4.11 Scripting SCRIPT_TAG, NOSCRIPT_TAG, TEMPLATE_TAG, CANVAS_TAG, -- Unknown tags UNKNOWN_TAG ); type Node_List is limited private; type Node_List_Access is access all Node_List; type Node_Type (Kind : Node_Kind; Len : Natural) is limited record case Kind is when N_HEADER | N_BLOCKQUOTE | N_INDENT => Level : Natural := 0; Header : WString (1 .. Len); when N_TEXT => Format : Format_Map; Text : WString (1 .. Len); when N_LINK | N_IMAGE => Link : Wiki.Attributes.Attribute_List_Type; when N_QUOTE => Quote : WString (1 .. Len); when N_TAG_START => Tag_Start : Html_Tag_Type; Attributes : Wiki.Attributes.Attribute_List_Type; Children : Node_List_Access; when N_TAG_END => Tag_End : Html_Tag_Type; when others => null; end case; end record; type Node_Type_Access is access all Node_Type; -- Create a text node. function Create_Text (Text : in WString) return Node_Type_Access; type Document is limited private; -- Append a node to the document. procedure Append (Into : in out Document; Node : in Node_Type_Access); -- procedure Add_Text (Doc : in out Document; -- Text : in WString); -- type Renderer is limited interface; -- -- procedure Render (Engine : in out Renderer; -- Doc : in Document; -- Node : in Node_Type) is abstract; -- -- procedure Iterate (Doc : in Document; -- Process : access procedure (Doc : in Document; Node : in Node_Type)) is -- Node : Document_Node_Access := Doc.First; -- begin -- while Node /= null loop -- Process (Doc, Node.Data); -- Node := Node.Next; -- end loop; -- end Iterate; private NODE_LIST_BLOCK_SIZE : constant Positive := 20; type Node_Array is array (Positive range <>) of Node_Type_Access; type Node_List_Block; type Node_List_Block_Access is access all Node_List_Block; type Node_List_Block (Max : Positive) is limited record Next : Node_List_Block_Access; Last : Natural := 0; List : Node_Array (1 .. Max); end record; type Node_List is limited record Current : Node_List_Block_Access; Length : Natural := 0; First : Node_List_Block (NODE_LIST_BLOCK_SIZE); end record; -- Append a node to the node list. procedure Append (Into : in out Node_List; Node : in Node_Type_Access); type Document is limited record Nodes : Node_List; end record; end Wiki.Nodes;
Declare the Document type and the Append procedure on a Document
Declare the Document type and the Append procedure on a Document
Ada
apache-2.0
stcarrez/ada-wiki,stcarrez/ada-wiki
0368ec42110cd1a3055a85c17c70bd121db4c53e
awa/src/awa-events-services.adb
awa/src/awa-events-services.adb
----------------------------------------------------------------------- -- awa-events-services -- AWA Event Manager -- 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 Ada.Unchecked_Deallocation; with Util.Log.Loggers; with ADO.SQL; with ADO.Sessions; with AWA.Events.Dispatchers.Tasks; with AWA.Events.Dispatchers.Actions; package body AWA.Events.Services is use type Util.Strings.Name_Access; Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("AWA.Events.Services"); -- ------------------------------ -- Send the event to the modules that subscribed to it. -- The event is sent on each event queue. Event queues will dispatch the event -- by invoking immediately or later on the <b>Dispatch</b> operation. The synchronous -- or asynchronous reception of the event depends on the event queue. -- ------------------------------ procedure Send (Manager : in Event_Manager; Event : in Module_Event'Class) is procedure Send_Queue (Queue : in Queue_Dispatcher); procedure Send_Queue (Queue : in Queue_Dispatcher) is begin if Queue.Queue.Is_Null then Queue.Dispatcher.Dispatch (Event); else Queue.Queue.Enqueue (Event); end if; end Send_Queue; Name : constant Name_Access := Get_Event_Type_Name (Event.Kind); begin if Name = null then Log.Error ("Cannot send event type {0}", Event_Index'Image (Event.Kind)); raise Not_Found; end if; -- Find the event queues associated with the event. Post the event on each queue. -- Some queue can dispatch the event immediately while some others may dispatched it -- asynchronously. declare Pos : Queue_Dispatcher_Lists.Cursor := Manager.Actions (Event.Kind).Queues.First; begin if not Queue_Dispatcher_Lists.Has_Element (Pos) then Log.Debug ("Sending event {0} but there is no listener", Name.all); else Log.Debug ("Sending event {0}", Name.all); loop Queue_Dispatcher_Lists.Query_Element (Pos, Send_Queue'Access); Queue_Dispatcher_Lists.Next (Pos); exit when not Queue_Dispatcher_Lists.Has_Element (Pos); end loop; end if; end; end Send; -- ------------------------------ -- Set the event message type which correspond to the <tt>Kind</tt> event index. -- ------------------------------ procedure Set_Message_Type (Manager : in Event_Manager; Event : in out AWA.Events.Models.Message_Ref; Kind : in Event_Index) is begin if not Event_Arrays.Is_Valid (Kind) then Log.Error ("Cannot send event type {0}", Event_Index'Image (Kind)); raise Not_Found; end if; Event.Set_Status (AWA.Events.Models.QUEUED); Event.Set_Message_Type (Manager.Actions (Kind).Event); end Set_Message_Type; -- ------------------------------ -- Set the event queue associated with the event message. The event queue identified by -- <tt>Name</tt> is searched to find the <tt>Queue_Ref</tt> instance. -- ------------------------------ procedure Set_Event_Queue (Manager : in Event_Manager; Event : in out AWA.Events.Models.Message_Ref; Name : in String) is Queue : constant AWA.Events.Queues.Queue_Ref := Manager.Find_Queue (Name); begin Event.Set_Queue (Queue.Get_Queue); end Set_Event_Queue; -- ------------------------------ -- Dispatch the event identified by <b>Event</b> and associated with the event -- queue <b>Queue</b>. The event actions which are associated with the event are -- executed synchronously. -- ------------------------------ procedure Dispatch (Manager : in Event_Manager; Queue : in AWA.Events.Queues.Queue_Ref; Event : in Module_Event'Class) is procedure Find_Queue (List : in Queue_Dispatcher); Found : Boolean := False; procedure Find_Queue (List : in Queue_Dispatcher) is begin if List.Queue = Queue then List.Dispatcher.Dispatch (Event); Found := True; end if; end Find_Queue; Name : constant Name_Access := Get_Event_Type_Name (Event.Kind); begin if Name = null then Log.Error ("Cannot dispatch event type {0}", Event_Index'Image (Event.Kind)); raise Not_Found; end if; declare Pos : Queue_Dispatcher_Lists.Cursor := Manager.Actions (Event.Kind).Queues.First; begin if not Queue_Dispatcher_Lists.Has_Element (Pos) then Log.Debug ("Dispatching event {0} but there is no listener", Name.all); else Log.Debug ("Dispatching event {0}", Name.all); loop Queue_Dispatcher_Lists.Query_Element (Pos, Find_Queue'Access); exit when Found; Queue_Dispatcher_Lists.Next (Pos); if not Queue_Dispatcher_Lists.Has_Element (Pos) then Log.Debug ("Dispatched event {0} but there was no listener", Name.all); exit; end if; end loop; end if; end; end Dispatch; -- ------------------------------ -- Find the event queue identified by the given name. -- ------------------------------ function Find_Queue (Manager : in Event_Manager; Name : in String) return AWA.Events.Queues.Queue_Ref is Pos : constant Queues.Maps.Cursor := Manager.Queues.Find (Name); begin if Queues.Maps.Has_Element (Pos) then return Queues.Maps.Element (Pos); else Log.Error ("Event queue {0} not found", Name); return AWA.Events.Queues.Null_Queue; end if; end Find_Queue; -- ------------------------------ -- Add the event queue in the registry. -- ------------------------------ procedure Add_Queue (Manager : in out Event_Manager; Queue : in AWA.Events.Queues.Queue_Ref) is Name : constant String := Queue.Get_Name; begin if Manager.Queues.Contains (Name) then Log.Error ("Event queue {0} already defined"); else Log.Info ("Adding event queue {0}", Name); end if; Manager.Queues.Include (Key => Name, New_Item => Queue); end Add_Queue; -- ------------------------------ -- Add an action invoked when the event identified by <b>Event</b> is sent. -- The event is posted on the queue identified by <b>Queue</b>. -- When the event queue dispatches the event, the Ada bean identified by the method action -- represented by <b>Action</b> is created and initialized by evaluating and setting the -- parameters defined in <b>Params</b>. The action method is then invoked. -- ------------------------------ procedure Add_Action (Manager : in out Event_Manager; Event : in String; Queue : in AWA.Events.Queues.Queue_Ref; Action : in EL.Expressions.Method_Expression; Params : in EL.Beans.Param_Vectors.Vector) is procedure Find_Queue (List : in Queue_Dispatcher); procedure Add_Action (List : in out Queue_Dispatcher); procedure Add_Action (List : in out Queue_Dispatcher) is use type AWA.Events.Dispatchers.Dispatcher_Access; begin if List.Dispatcher = null then List.Dispatcher := AWA.Events.Dispatchers.Actions.Create_Dispatcher (Application => Manager.Application.all'Access); end if; List.Dispatcher.Add_Action (Action, Params); end Add_Action; Found : Boolean := False; procedure Find_Queue (List : in Queue_Dispatcher) is begin Found := List.Queue = Queue; end Find_Queue; Index : constant Event_Index := Find_Event_Index (Event); Pos : Queue_Dispatcher_Lists.Cursor := Manager.Actions (Index).Queues.First; begin Log.Info ("Adding action {0} to event {1}", Action.Get_Expression, Event); -- Find the queue. while Queue_Dispatcher_Lists.Has_Element (Pos) loop Queue_Dispatcher_Lists.Query_Element (Pos, Find_Queue'Access); exit when Found; Queue_Dispatcher_Lists.Next (Pos); end loop; -- Create it if it does not exist. if not Found then declare New_Queue : Queue_Dispatcher; begin New_Queue.Queue := Queue; Manager.Actions (Index).Queues.Append (New_Queue); Pos := Manager.Actions (Index).Queues.Last; end; end if; -- And append the new action to the event queue. Manager.Actions (Index).Queues.Update_Element (Pos, Add_Action'Access); end Add_Action; -- ------------------------------ -- Add a dispatcher to process the event queues matching the <b>Match</b> string. -- The dispatcher can create up to <b>Count</b> tasks running at the priority <b>Priority</b>. -- ------------------------------ procedure Add_Dispatcher (Manager : in out Event_Manager; Match : in String; Count : in Positive; Priority : in Positive) is use type AWA.Events.Dispatchers.Dispatcher_Access; begin Log.Info ("Adding event dispatcher with {0} tasks prio {1} and dispatching queues '{2}'", Positive'Image (Count), Positive'Image (Priority), Match); for I in Manager.Dispatchers'Range loop if Manager.Dispatchers (I) = null then Manager.Dispatchers (I) := AWA.Events.Dispatchers.Tasks.Create_Dispatcher (Manager'Unchecked_Access, Match, Count, Priority); return; end if; end loop; Log.Error ("Implementation limit is reached. Too many dispatcher."); end Add_Dispatcher; -- ------------------------------ -- Initialize the event manager. -- ------------------------------ procedure Initialize (Manager : in out Event_Manager; App : in Application_Access) is procedure Set_Events (Msg : in AWA.Events.Models.Message_Type_Ref); Msg_Types : AWA.Events.Models.Message_Type_Vector; Query : ADO.SQL.Query; procedure Set_Events (Msg : in AWA.Events.Models.Message_Type_Ref) is Name : constant String := Msg.Get_Name; begin declare Index : constant Event_Index := Find_Event_Index (Name); begin Manager.Actions (Index).Event := Msg; end; exception when others => Log.Warn ("Event {0} is no longer used", Name); end Set_Events; DB : ADO.Sessions.Master_Session := App.Get_Master_Session; begin Log.Info ("Initializing {0} events", Event_Index'Image (Event_Arrays.Get_Last)); Manager.Application := App; DB.Begin_Transaction; Manager.Actions := new Event_Queues_Array (1 .. Event_Arrays.Get_Last); AWA.Events.Models.List (Object => Msg_Types, Session => DB, Query => Query); declare Pos : AWA.Events.Models.Message_Type_Vectors.Cursor := Msg_Types.First; begin while AWA.Events.Models.Message_Type_Vectors.Has_Element (Pos) loop AWA.Events.Models.Message_Type_Vectors.Query_Element (Pos, Set_Events'Access); AWA.Events.Models.Message_Type_Vectors.Next (Pos); end loop; end; for I in Manager.Actions'Range loop if Manager.Actions (I).Event.Is_Null then declare Name : constant Name_Access := Get_Event_Type_Name (I); begin Log.Info ("Creating event type {0} in database", Name.all); Manager.Actions (I).Event.Set_Name (Name.all); Manager.Actions (I).Event.Save (DB); end; end if; end loop; DB.Commit; end Initialize; -- ------------------------------ -- Start the event manager. The dispatchers are configured to dispatch the event queues -- and tasks are started to process asynchronous events. -- ------------------------------ procedure Start (Manager : in out Event_Manager) is use type AWA.Events.Dispatchers.Dispatcher_Access; -- Dispatch the event queues to the dispatcher according to the dispatcher configuration. procedure Associate_Dispatcher (Key : in String; Queue : in out AWA.Events.Queues.Queue_Ref); -- ------------------------------ -- Dispatch the event queues to the dispatcher according to the dispatcher configuration. -- ------------------------------ procedure Associate_Dispatcher (Key : in String; Queue : in out AWA.Events.Queues.Queue_Ref) is pragma Unreferenced (Key); Added : Boolean := False; begin for I in reverse Manager.Dispatchers'Range loop if Manager.Dispatchers (I) /= null then Manager.Dispatchers (I).Add_Queue (Queue, Added); exit when Added; end if; end loop; end Associate_Dispatcher; Iter : AWA.Events.Queues.Maps.Cursor := Manager.Queues.First; begin Log.Info ("Starting the event manager"); while AWA.Events.Queues.Maps.Has_Element (Iter) loop Manager.Queues.Update_Element (Iter, Associate_Dispatcher'Access); AWA.Events.Queues.Maps.Next (Iter); end loop; -- Start the dispatchers. for I in Manager.Dispatchers'Range loop exit when Manager.Dispatchers (I) = null; Manager.Dispatchers (I).Start; end loop; end Start; -- ------------------------------ -- Get the application associated with the event manager. -- ------------------------------ function Get_Application (Manager : in Event_Manager) return Application_Access is begin return Manager.Application; end Get_Application; -- ------------------------------ -- Finalize the queue dispatcher releasing the dispatcher memory. -- ------------------------------ procedure Finalize (Object : in out Queue_Dispatcher) is procedure Free is new Ada.Unchecked_Deallocation (Object => AWA.Events.Dispatchers.Dispatcher'Class, Name => AWA.Events.Dispatchers.Dispatcher_Access); begin Free (Object.Dispatcher); end Finalize; -- ------------------------------ -- Finalize the event queues and the dispatchers. -- ------------------------------ procedure Finalize (Object : in out Event_Queues) is begin loop declare Pos : constant Queue_Dispatcher_Lists.Cursor := Object.Queues.First; begin exit when not Queue_Dispatcher_Lists.Has_Element (Pos); Object.Queues.Update_Element (Position => Pos, Process => Finalize'Access); Object.Queues.Delete_First; end; end loop; end Finalize; -- ------------------------------ -- Finalize the event manager by releasing the allocated storage. -- ------------------------------ overriding procedure Finalize (Manager : in out Event_Manager) is use type AWA.Events.Dispatchers.Dispatcher_Access; procedure Free is new Ada.Unchecked_Deallocation (Object => Event_Queues_Array, Name => Event_Queues_Array_Access); procedure Free is new Ada.Unchecked_Deallocation (Object => AWA.Events.Dispatchers.Dispatcher'Class, Name => AWA.Events.Dispatchers.Dispatcher_Access); begin -- Stop the dispatcher first. for I in Manager.Dispatchers'Range loop exit when Manager.Dispatchers (I) = null; Free (Manager.Dispatchers (I)); end loop; if Manager.Actions /= null then for I in Manager.Actions'Range loop Finalize (Manager.Actions (I)); end loop; Free (Manager.Actions); end if; end Finalize; end AWA.Events.Services;
----------------------------------------------------------------------- -- awa-events-services -- AWA Event Manager -- Copyright (C) 2012, 2015, 2016 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Unchecked_Deallocation; with Util.Log.Loggers; with ADO.SQL; with ADO.Sessions; with AWA.Events.Dispatchers.Tasks; with AWA.Events.Dispatchers.Actions; package body AWA.Events.Services is use type Util.Strings.Name_Access; Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("AWA.Events.Services"); -- ------------------------------ -- Send the event to the modules that subscribed to it. -- The event is sent on each event queue. Event queues will dispatch the event -- by invoking immediately or later on the <b>Dispatch</b> operation. The synchronous -- or asynchronous reception of the event depends on the event queue. -- ------------------------------ procedure Send (Manager : in Event_Manager; Event : in Module_Event'Class) is procedure Send_Queue (Queue : in Queue_Dispatcher); procedure Send_Queue (Queue : in Queue_Dispatcher) is begin if Queue.Queue.Is_Null then Queue.Dispatcher.Dispatch (Event); else Queue.Queue.Enqueue (Event); end if; end Send_Queue; Name : constant Name_Access := Get_Event_Type_Name (Event.Kind); begin if Name = null then Log.Error ("Cannot send event type {0}", Event_Index'Image (Event.Kind)); raise Not_Found; end if; -- Find the event queues associated with the event. Post the event on each queue. -- Some queue can dispatch the event immediately while some others may dispatched it -- asynchronously. declare Pos : Queue_Dispatcher_Lists.Cursor := Manager.Actions (Event.Kind).Queues.First; begin if not Queue_Dispatcher_Lists.Has_Element (Pos) then Log.Debug ("Sending event {0} but there is no listener", Name.all); else Log.Debug ("Sending event {0}", Name.all); loop Queue_Dispatcher_Lists.Query_Element (Pos, Send_Queue'Access); Queue_Dispatcher_Lists.Next (Pos); exit when not Queue_Dispatcher_Lists.Has_Element (Pos); end loop; end if; end; end Send; -- ------------------------------ -- Set the event message type which correspond to the <tt>Kind</tt> event index. -- ------------------------------ procedure Set_Message_Type (Manager : in Event_Manager; Event : in out AWA.Events.Models.Message_Ref; Kind : in Event_Index) is begin if not Event_Arrays.Is_Valid (Kind) then Log.Error ("Cannot send event type {0}", Event_Index'Image (Kind)); raise Not_Found; end if; Event.Set_Status (AWA.Events.Models.QUEUED); Event.Set_Message_Type (Manager.Actions (Kind).Event); end Set_Message_Type; -- ------------------------------ -- Set the event queue associated with the event message. The event queue identified by -- <tt>Name</tt> is searched to find the <tt>Queue_Ref</tt> instance. -- ------------------------------ procedure Set_Event_Queue (Manager : in Event_Manager; Event : in out AWA.Events.Models.Message_Ref; Name : in String) is Queue : constant AWA.Events.Queues.Queue_Ref := Manager.Find_Queue (Name); begin Event.Set_Queue (Queue.Get_Queue); end Set_Event_Queue; -- ------------------------------ -- Dispatch the event identified by <b>Event</b> and associated with the event -- queue <b>Queue</b>. The event actions which are associated with the event are -- executed synchronously. -- ------------------------------ procedure Dispatch (Manager : in Event_Manager; Queue : in AWA.Events.Queues.Queue_Ref; Event : in Module_Event'Class) is procedure Find_Queue (List : in Queue_Dispatcher); Found : Boolean := False; procedure Find_Queue (List : in Queue_Dispatcher) is begin if List.Queue = Queue then List.Dispatcher.Dispatch (Event); Found := True; end if; end Find_Queue; Name : constant Name_Access := Get_Event_Type_Name (Event.Kind); begin if Name = null then Log.Error ("Cannot dispatch event type {0}", Event_Index'Image (Event.Kind)); raise Not_Found; end if; declare Pos : Queue_Dispatcher_Lists.Cursor := Manager.Actions (Event.Kind).Queues.First; begin if not Queue_Dispatcher_Lists.Has_Element (Pos) then Log.Debug ("Dispatching event {0} but there is no listener", Name.all); else Log.Debug ("Dispatching event {0}", Name.all); loop Queue_Dispatcher_Lists.Query_Element (Pos, Find_Queue'Access); exit when Found; Queue_Dispatcher_Lists.Next (Pos); if not Queue_Dispatcher_Lists.Has_Element (Pos) then Log.Debug ("Dispatched event {0} but there was no listener", Name.all); exit; end if; end loop; end if; end; end Dispatch; -- ------------------------------ -- Find the event queue identified by the given name. -- ------------------------------ function Find_Queue (Manager : in Event_Manager; Name : in String) return AWA.Events.Queues.Queue_Ref is Pos : constant Queues.Maps.Cursor := Manager.Queues.Find (Name); begin if Queues.Maps.Has_Element (Pos) then return Queues.Maps.Element (Pos); else Log.Error ("Event queue {0} not found", Name); return AWA.Events.Queues.Null_Queue; end if; end Find_Queue; -- ------------------------------ -- Add the event queue in the registry. -- ------------------------------ procedure Add_Queue (Manager : in out Event_Manager; Queue : in AWA.Events.Queues.Queue_Ref) is Name : constant String := Queue.Get_Name; begin if Manager.Queues.Contains (Name) then Log.Error ("Event queue {0} already defined"); else Log.Info ("Adding event queue {0}", Name); end if; Manager.Queues.Include (Key => Name, New_Item => Queue); end Add_Queue; -- ------------------------------ -- Add an action invoked when the event identified by <b>Event</b> is sent. -- The event is posted on the queue identified by <b>Queue</b>. -- When the event queue dispatches the event, the Ada bean identified by the method action -- represented by <b>Action</b> is created and initialized by evaluating and setting the -- parameters defined in <b>Params</b>. The action method is then invoked. -- ------------------------------ procedure Add_Action (Manager : in out Event_Manager; Event : in String; Queue : in AWA.Events.Queues.Queue_Ref; Action : in EL.Expressions.Method_Expression; Params : in EL.Beans.Param_Vectors.Vector) is procedure Find_Queue (List : in Queue_Dispatcher); procedure Add_Action (List : in out Queue_Dispatcher); procedure Add_Action (List : in out Queue_Dispatcher) is use type AWA.Events.Dispatchers.Dispatcher_Access; begin if List.Dispatcher = null then List.Dispatcher := AWA.Events.Dispatchers.Actions.Create_Dispatcher (Application => Manager.Application.all'Access); end if; List.Dispatcher.Add_Action (Action, Params); end Add_Action; Found : Boolean := False; procedure Find_Queue (List : in Queue_Dispatcher) is begin Found := List.Queue = Queue; end Find_Queue; Index : constant Event_Index := Find_Event_Index (Event); Pos : Queue_Dispatcher_Lists.Cursor := Manager.Actions (Index).Queues.First; begin Log.Info ("Adding action {0} to event {1}", Action.Get_Expression, Event); -- Find the queue. while Queue_Dispatcher_Lists.Has_Element (Pos) loop Queue_Dispatcher_Lists.Query_Element (Pos, Find_Queue'Access); exit when Found; Queue_Dispatcher_Lists.Next (Pos); end loop; -- Create it if it does not exist. if not Found then declare New_Queue : Queue_Dispatcher; begin New_Queue.Queue := Queue; Manager.Actions (Index).Queues.Append (New_Queue); Pos := Manager.Actions (Index).Queues.Last; end; end if; -- And append the new action to the event queue. Manager.Actions (Index).Queues.Update_Element (Pos, Add_Action'Access); end Add_Action; -- ------------------------------ -- Add a dispatcher to process the event queues matching the <b>Match</b> string. -- The dispatcher can create up to <b>Count</b> tasks running at the priority <b>Priority</b>. -- ------------------------------ procedure Add_Dispatcher (Manager : in out Event_Manager; Match : in String; Count : in Positive; Priority : in Positive) is use type AWA.Events.Dispatchers.Dispatcher_Access; begin Log.Info ("Adding event dispatcher with {0} tasks prio {1} and dispatching queues '{2}'", Positive'Image (Count), Positive'Image (Priority), Match); for I in Manager.Dispatchers'Range loop if Manager.Dispatchers (I) = null then Manager.Dispatchers (I) := AWA.Events.Dispatchers.Tasks.Create_Dispatcher (Manager'Unchecked_Access, Match, Count, Priority); return; end if; end loop; Log.Error ("Implementation limit is reached. Too many dispatcher."); end Add_Dispatcher; -- ------------------------------ -- Initialize the event manager. -- ------------------------------ procedure Initialize (Manager : in out Event_Manager; App : in Application_Access) is procedure Set_Events (Msg : in AWA.Events.Models.Message_Type_Ref); Msg_Types : AWA.Events.Models.Message_Type_Vector; Query : ADO.SQL.Query; procedure Set_Events (Msg : in AWA.Events.Models.Message_Type_Ref) is Name : constant String := Msg.Get_Name; begin declare Index : constant Event_Index := Find_Event_Index (Name); begin Manager.Actions (Index).Event := Msg; end; exception when others => Log.Warn ("Event {0} is no longer used", Name); end Set_Events; DB : ADO.Sessions.Master_Session := App.Get_Master_Session; begin Log.Info ("Initializing {0} events", Event_Index'Image (Event_Arrays.Get_Last)); Manager.Application := App; DB.Begin_Transaction; Manager.Actions := new Event_Queues_Array (1 .. Event_Arrays.Get_Last); AWA.Events.Models.List (Object => Msg_Types, Session => DB, Query => Query); declare Pos : AWA.Events.Models.Message_Type_Vectors.Cursor := Msg_Types.First; begin while AWA.Events.Models.Message_Type_Vectors.Has_Element (Pos) loop AWA.Events.Models.Message_Type_Vectors.Query_Element (Pos, Set_Events'Access); AWA.Events.Models.Message_Type_Vectors.Next (Pos); end loop; end; for I in Manager.Actions'Range loop if Manager.Actions (I).Event.Is_Null then declare Name : constant Name_Access := Get_Event_Type_Name (I); begin Log.Info ("Creating event type {0} in database", Name.all); Manager.Actions (I).Event.Set_Name (Name.all); Manager.Actions (I).Event.Save (DB); end; end if; end loop; DB.Commit; end Initialize; -- ------------------------------ -- Start the event manager. The dispatchers are configured to dispatch the event queues -- and tasks are started to process asynchronous events. -- ------------------------------ procedure Start (Manager : in out Event_Manager) is use type AWA.Events.Dispatchers.Dispatcher_Access; -- Dispatch the event queues to the dispatcher according to the dispatcher configuration. procedure Associate_Dispatcher (Key : in String; Queue : in out AWA.Events.Queues.Queue_Ref); -- ------------------------------ -- Dispatch the event queues to the dispatcher according to the dispatcher configuration. -- ------------------------------ procedure Associate_Dispatcher (Key : in String; Queue : in out AWA.Events.Queues.Queue_Ref) is pragma Unreferenced (Key); Added : Boolean := False; begin for I in reverse Manager.Dispatchers'Range loop if Manager.Dispatchers (I) /= null then Manager.Dispatchers (I).Add_Queue (Queue, Added); exit when Added; end if; end loop; end Associate_Dispatcher; Iter : AWA.Events.Queues.Maps.Cursor := Manager.Queues.First; begin Log.Info ("Starting the event manager"); while AWA.Events.Queues.Maps.Has_Element (Iter) loop Manager.Queues.Update_Element (Iter, Associate_Dispatcher'Access); AWA.Events.Queues.Maps.Next (Iter); end loop; -- Start the dispatchers. for I in Manager.Dispatchers'Range loop exit when Manager.Dispatchers (I) = null; Manager.Dispatchers (I).Start; end loop; end Start; -- ------------------------------ -- Stop the event manager. -- ------------------------------ procedure Stop (Manager : in out Event_Manager) is use type AWA.Events.Dispatchers.Dispatcher_Access; begin Log.Info ("Stopping the event manager"); -- Stop the dispatchers. for I in Manager.Dispatchers'Range loop exit when Manager.Dispatchers (I) = null; Manager.Dispatchers (I).Stop; end loop; end Stop; -- ------------------------------ -- Get the application associated with the event manager. -- ------------------------------ function Get_Application (Manager : in Event_Manager) return Application_Access is begin return Manager.Application; end Get_Application; -- ------------------------------ -- Finalize the queue dispatcher releasing the dispatcher memory. -- ------------------------------ procedure Finalize (Object : in out Queue_Dispatcher) is procedure Free is new Ada.Unchecked_Deallocation (Object => AWA.Events.Dispatchers.Dispatcher'Class, Name => AWA.Events.Dispatchers.Dispatcher_Access); begin Free (Object.Dispatcher); end Finalize; -- ------------------------------ -- Finalize the event queues and the dispatchers. -- ------------------------------ procedure Finalize (Object : in out Event_Queues) is begin loop declare Pos : constant Queue_Dispatcher_Lists.Cursor := Object.Queues.First; begin exit when not Queue_Dispatcher_Lists.Has_Element (Pos); Object.Queues.Update_Element (Position => Pos, Process => Finalize'Access); Object.Queues.Delete_First; end; end loop; end Finalize; -- ------------------------------ -- Finalize the event manager by releasing the allocated storage. -- ------------------------------ overriding procedure Finalize (Manager : in out Event_Manager) is use type AWA.Events.Dispatchers.Dispatcher_Access; procedure Free is new Ada.Unchecked_Deallocation (Object => Event_Queues_Array, Name => Event_Queues_Array_Access); procedure Free is new Ada.Unchecked_Deallocation (Object => AWA.Events.Dispatchers.Dispatcher'Class, Name => AWA.Events.Dispatchers.Dispatcher_Access); begin -- Stop the dispatcher first. for I in Manager.Dispatchers'Range loop exit when Manager.Dispatchers (I) = null; Free (Manager.Dispatchers (I)); end loop; if Manager.Actions /= null then for I in Manager.Actions'Range loop Finalize (Manager.Actions (I)); end loop; Free (Manager.Actions); end if; end Finalize; end AWA.Events.Services;
Implement the Stop procedure to stop the event dispatchers
Implement the Stop procedure to stop the event dispatchers
Ada
apache-2.0
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
67d464e6105d243df1c81810666e596d7a1ad0b4
awa/plugins/awa-workspaces/src/awa-workspaces.ads
awa/plugins/awa-workspaces/src/awa-workspaces.ads
----------------------------------------------------------------------- -- awa-workspaces -- Module workspaces -- 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. ----------------------------------------------------------------------- -- == Introduction == -- The *workspaces* plugin defines a workspace area for other plugins. -- -- == Ada Beans == -- @include workspaces.xml -- -- == Data Model == -- @include Workspace.hbm.xml -- package AWA.Workspaces is end AWA.Workspaces;
----------------------------------------------------------------------- -- awa-workspaces -- Module workspaces -- 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. ----------------------------------------------------------------------- -- == Introduction == -- The *workspaces* plugin defines a workspace area for other plugins. -- The workspace is intended to link together all the data objects that an application -- manages for a given user or group of users. A workspace is a possible mechanism -- to provide and implement multi-tenancy in a web application. By using the workspace plugin, -- application data from different customers can be kept separate from each other in the -- same database. -- -- == Ada Beans == -- @include workspaces.xml -- -- == Data Model == -- @include Workspace.hbm.xml -- package AWA.Workspaces is end AWA.Workspaces;
Update the documentation
Update the documentation
Ada
apache-2.0
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
580c85a249496697c949e00958a71e17b6bae3be
src/wiki-helpers.ads
src/wiki-helpers.ads
----------------------------------------------------------------------- -- wiki-helpers -- Helper operations for wiki parsers and renderer -- Copyright (C) 2016, 2020, 2022 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Wiki.Strings; package Wiki.Helpers is pragma Preelaborate; LF : constant Wiki.Strings.WChar := Wiki.Strings.WChar'Val (16#0A#); CR : constant Wiki.Strings.WChar := Wiki.Strings.WChar'Val (16#0D#); HT : constant Wiki.Strings.WChar := Wiki.Strings.WChar'Val (16#09#); NBSP : constant Wiki.Strings.WChar := Wiki.Strings.WChar'Val (16#A0#); -- Returns True if the character is a space or tab. function Is_Space (C : in Wiki.Strings.WChar) return Boolean; -- Returns True if the character is a space, tab or a newline. function Is_Space_Or_Newline (C : in Wiki.Strings.WChar) return Boolean; -- Returns True if the character is a punctuation character. function Is_Punctuation (C : in Wiki.Strings.WChar) return Boolean; -- Returns True if the character is a line terminator. function Is_Newline (C : in Wiki.Strings.WChar) return Boolean; -- Returns True if the text is a valid URL function Is_Url (Text : in Wiki.Strings.WString) return Boolean; -- Returns True if the extension part correspond to an image. -- Recognized extension are: .png, .gif, .jpg, .jpeg. -- The extension case is ignored. function Is_Image_Extension (Ext : in Wiki.Strings.WString) return Boolean; -- Given the current tag on the top of the stack and the new tag that will be pushed, -- decide whether the current tag must be closed or not. -- Returns True if the current tag must be closed. function Need_Close (Tag : in Html_Tag; Current_Tag : in Html_Tag) return Boolean; -- Get the dimension represented by the string. The string has one of the following -- formats: -- original -> Width, Height := Natural'Last -- default -> Width := 800, Height := 0 -- upright -> Width := 800, Height := 0 -- <width>px -> Width := <width>, Height := 0 -- x<height>px -> Width := 0, Height := <height> -- <width>x<height>px -> Width := <width>, Height := <height> procedure Get_Sizes (Dimension : in Wiki.Strings.WString; Width : out Natural; Height : out Natural); -- Find the position of the first non space character in the text starting at the -- given position. Returns Text'Last + 1 if the text only contains spaces. function Skip_Spaces (Text : in Wiki.Strings.Wstring; From : in Positive) return Positive; end Wiki.Helpers;
----------------------------------------------------------------------- -- wiki-helpers -- Helper operations for wiki parsers and renderer -- Copyright (C) 2016, 2020, 2022 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Wiki.Strings; package Wiki.Helpers is pragma Preelaborate; LF : constant Wiki.Strings.WChar := Wiki.Strings.WChar'Val (16#0A#); CR : constant Wiki.Strings.WChar := Wiki.Strings.WChar'Val (16#0D#); HT : constant Wiki.Strings.WChar := Wiki.Strings.WChar'Val (16#09#); NBSP : constant Wiki.Strings.WChar := Wiki.Strings.WChar'Val (16#A0#); -- Returns True if the character is a space or tab. function Is_Space (C : in Wiki.Strings.WChar) return Boolean; -- Returns True if the character is a space, tab or a newline. function Is_Space_Or_Newline (C : in Wiki.Strings.WChar) return Boolean; -- Returns True if the character is a punctuation character. function Is_Punctuation (C : in Wiki.Strings.WChar) return Boolean; -- Returns True if the character is a line terminator. function Is_Newline (C : in Wiki.Strings.WChar) return Boolean; -- Returns True if the text is a valid URL function Is_Url (Text : in Wiki.Strings.WString) return Boolean; -- Returns True if the extension part correspond to an image. -- Recognized extension are: .png, .gif, .jpg, .jpeg. -- The extension case is ignored. function Is_Image_Extension (Ext : in Wiki.Strings.WString) return Boolean; -- Given the current tag on the top of the stack and the new tag that will be pushed, -- decide whether the current tag must be closed or not. -- Returns True if the current tag must be closed. function Need_Close (Tag : in Html_Tag; Current_Tag : in Html_Tag) return Boolean; -- Get the dimension represented by the string. The string has one of the following -- formats: -- original -> Width, Height := Natural'Last -- default -> Width := 800, Height := 0 -- upright -> Width := 800, Height := 0 -- <width>px -> Width := <width>, Height := 0 -- x<height>px -> Width := 0, Height := <height> -- <width>x<height>px -> Width := <width>, Height := <height> procedure Get_Sizes (Dimension : in Wiki.Strings.WString; Width : out Natural; Height : out Natural); -- Find the position of the first non space character in the text starting at the -- given position. Returns Text'Last + 1 if the text only contains spaces. function Skip_Spaces (Text : in Wiki.Strings.Wstring; From : in Positive) return Positive; -- Find the position of the last non space character scanning the text backward -- from the given position. Returns Text'First - 1 if the text only contains spaces. function Trim_Spaces (Text : in Wiki.Strings.Wstring; From : in Positive) return Natural; end Wiki.Helpers;
Add Trim_Spaces function
Add Trim_Spaces function
Ada
apache-2.0
stcarrez/ada-wiki,stcarrez/ada-wiki
b97e4a38037cd541b3d5dbc479f96b579c6e8cd1
src/wiki-parsers.ads
src/wiki-parsers.ads
----------------------------------------------------------------------- -- wiki-parsers -- Wiki parser -- Copyright (C) 2011, 2015, 2016 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Wiki.Attributes; with Wiki.Plugins; with Wiki.Filters; with Wiki.Strings; with Wiki.Nodes; with Wiki.Documents; with Wiki.Streams; -- == Wiki Parsers == -- The <b>Wikis.Parsers</b> package implements a parser for several well known wiki formats. -- The parser works with the <b>Document_Reader</b> interface type which defines several -- procedures that are called by the parser when the wiki text is scanned. package Wiki.Parsers is pragma Preelaborate; type Parser is tagged limited private; -- Add the plugin to the wiki engine. procedure Add_Plugin (Engine : in out Parser; Name : in String; Plugin : in Wiki.Plugins.Wiki_Plugin_Access); -- Set the wiki syntax that the wiki engine must use. procedure Set_Syntax (Engine : in out Parser; Syntax : in Wiki_Syntax := SYNTAX_MIX); -- Add a filter in the wiki engine. procedure Add_Filter (Engine : in out Parser; Filter : in Wiki.Filters.Filter_Type_Access); -- Parse the wiki text contained in <b>Text</b> according to the wiki syntax -- defined on the parser. procedure Parse (Engine : in out Parser; Text : in Wide_Wide_String; Doc : in out Wiki.Documents.Document); -- Parse the wiki stream managed by <tt>Stream</tt> according to the wiki syntax configured -- on the wiki engine. procedure Parse (Engine : in out Parser; Stream : in Wiki.Streams.Input_Stream_Access; Doc : in out Wiki.Documents.Document); private type Parser is tagged limited record Pending : Wide_Wide_Character; Has_Pending : Boolean; Syntax : Wiki_Syntax; Document : Wiki.Documents.Document; Filters : Wiki.Filters.Filter_Chain; Format : Wiki.Format_Map; Text : Wiki.Strings.BString (512); Token : Wiki.Strings.BString (512); Empty_Line : Boolean := True; Is_Eof : Boolean := False; In_Paragraph : Boolean := False; In_List : Boolean := False; Need_Paragraph : Boolean := True; Link_Double_Bracket : Boolean := False; Is_Dotclear : Boolean := False; Link_Title_First : Boolean := False; Check_Image_Link : Boolean := False; Header_Offset : Integer := 0; Quote_Level : Natural := 0; Escape_Char : Wide_Wide_Character; List_Level : Natural := 0; Reader : Wiki.Streams.Input_Stream_Access := null; Attributes : Wiki.Attributes.Attribute_List; end record; type Parser_Handler is access procedure (P : in out Parser; Token : in Wide_Wide_Character); type Parser_Table is array (0 .. 127) of Parser_Handler; type Parser_Table_Access is access Parser_Table; -- Peek the next character from the wiki text buffer. procedure Peek (P : in out Parser; Token : out Wide_Wide_Character); -- Put back the character so that it will be returned by the next call to Peek. procedure Put_Back (P : in out Parser; Token : in Wide_Wide_Character); -- Skip all the spaces and tabs as well as end of the current line (CR+LF). procedure Skip_End_Of_Line (P : in out Parser); -- Skip white spaces and tabs. procedure Skip_Spaces (P : in out Parser); -- Flush the wiki text that was collected in the text buffer. procedure Flush_Text (P : in out Parser); -- Flush the wiki dl/dt/dd definition list. procedure Flush_List (P : in out Parser); -- Append a character to the wiki text buffer. procedure Parse_Text (P : in out Parser; Token : in Wide_Wide_Character); -- Check if the link refers to an image and must be rendered as an image. function Is_Image (P : in Parser; Link : in Wide_Wide_String) return Boolean; procedure Start_Element (P : in out Parser; Tag : in Wiki.Html_Tag; Attributes : in out Wiki.Attributes.Attribute_List); procedure End_Element (P : in out Parser; Tag : in Wiki.Html_Tag); end Wiki.Parsers;
----------------------------------------------------------------------- -- wiki-parsers -- Wiki parser -- Copyright (C) 2011, 2015, 2016 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Wiki.Attributes; with Wiki.Plugins; with Wiki.Filters; with Wiki.Strings; with Wiki.Documents; with Wiki.Streams; -- == Wiki Parsers == -- The <b>Wikis.Parsers</b> package implements a parser for several well known wiki formats. -- The parser works with the <b>Document_Reader</b> interface type which defines several -- procedures that are called by the parser when the wiki text is scanned. package Wiki.Parsers is pragma Preelaborate; type Parser is tagged limited private; -- Add the plugin to the wiki engine. procedure Add_Plugin (Engine : in out Parser; Name : in String; Plugin : in Wiki.Plugins.Wiki_Plugin_Access); -- Set the wiki syntax that the wiki engine must use. procedure Set_Syntax (Engine : in out Parser; Syntax : in Wiki_Syntax := SYNTAX_MIX); -- Add a filter in the wiki engine. procedure Add_Filter (Engine : in out Parser; Filter : in Wiki.Filters.Filter_Type_Access); -- Parse the wiki text contained in <b>Text</b> according to the wiki syntax -- defined on the parser. procedure Parse (Engine : in out Parser; Text : in Wide_Wide_String; Doc : in out Wiki.Documents.Document); -- Parse the wiki stream managed by <tt>Stream</tt> according to the wiki syntax configured -- on the wiki engine. procedure Parse (Engine : in out Parser; Stream : in Wiki.Streams.Input_Stream_Access; Doc : in out Wiki.Documents.Document); private type Parser is tagged limited record Pending : Wide_Wide_Character; Has_Pending : Boolean; Syntax : Wiki_Syntax; Document : Wiki.Documents.Document; Filters : Wiki.Filters.Filter_Chain; Format : Wiki.Format_Map; Text : Wiki.Strings.BString (512); Token : Wiki.Strings.BString (512); Empty_Line : Boolean := True; Is_Eof : Boolean := False; In_Paragraph : Boolean := False; In_List : Boolean := False; Need_Paragraph : Boolean := True; Link_Double_Bracket : Boolean := False; Is_Dotclear : Boolean := False; Link_Title_First : Boolean := False; Check_Image_Link : Boolean := False; Header_Offset : Integer := 0; Quote_Level : Natural := 0; Escape_Char : Wide_Wide_Character; List_Level : Natural := 0; Reader : Wiki.Streams.Input_Stream_Access := null; Attributes : Wiki.Attributes.Attribute_List; end record; type Parser_Handler is access procedure (P : in out Parser; Token : in Wide_Wide_Character); type Parser_Table is array (0 .. 127) of Parser_Handler; type Parser_Table_Access is access Parser_Table; -- Peek the next character from the wiki text buffer. procedure Peek (P : in out Parser; Token : out Wide_Wide_Character); -- Put back the character so that it will be returned by the next call to Peek. procedure Put_Back (P : in out Parser; Token : in Wide_Wide_Character); -- Skip all the spaces and tabs as well as end of the current line (CR+LF). procedure Skip_End_Of_Line (P : in out Parser); -- Skip white spaces and tabs. procedure Skip_Spaces (P : in out Parser); -- Flush the wiki text that was collected in the text buffer. procedure Flush_Text (P : in out Parser); -- Flush the wiki dl/dt/dd definition list. procedure Flush_List (P : in out Parser); -- Append a character to the wiki text buffer. procedure Parse_Text (P : in out Parser; Token : in Wide_Wide_Character); -- Check if the link refers to an image and must be rendered as an image. function Is_Image (P : in Parser; Link : in Wide_Wide_String) return Boolean; procedure Start_Element (P : in out Parser; Tag : in Wiki.Html_Tag; Attributes : in out Wiki.Attributes.Attribute_List); procedure End_Element (P : in out Parser; Tag : in Wiki.Html_Tag); end Wiki.Parsers;
Remove use of Wiki.Nodes package
Remove use of Wiki.Nodes package
Ada
apache-2.0
stcarrez/ada-wiki,stcarrez/ada-wiki
2bcfc8584fd2a85668bf8cc6ae11923524ce4f73
src/asf-applications.ads
src/asf-applications.ads
----------------------------------------------------------------------- -- applications -- Ada Web Application -- Copyright (C) 2009, 2010, 2013, 2015 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Strings.Unbounded; with Util.Strings; with Util.Properties; package ASF.Applications is use Util.Properties; type Config is new Util.Properties.Manager with private; type Config_Param is private; -- Directory where the facelet files are stored. VIEW_DIR_PARAM : constant Config_Param; VIEW_DIR : aliased constant String := "view.dir"; DEF_VIEW_DIR : aliased constant String := "web"; -- Extension used by requests VIEW_EXT_PARAM : constant Config_Param; VIEW_EXT : aliased constant String := "view.ext"; DEF_VIEW_EXT : aliased constant String := ""; -- Extension used by facelet files VIEW_FILE_EXT_PARAM : constant Config_Param; VIEW_FILE_EXT : aliased constant String := "view.file_ext"; DEF_VIEW_FILE_EXT : aliased constant String := ".xhtml"; -- Whether white spaces in XHTML files are ignored. VIEW_IGNORE_WHITE_SPACES_PARAM : constant Config_Param; VIEW_IGNORE_WHITE_SPACES : aliased constant String := "view.ignore_white_spaces"; DEF_IGNORE_WHITE_SPACES : aliased constant String := "false"; -- Whether empty lines in XHTML files are ignored. VIEW_IGNORE_EMPTY_LINES_PARAM : constant Config_Param; VIEW_IGNORE_EMPTY_LINES : aliased constant String := "view.ignore_empty_lines"; DEF_IGNORE_EMPTY_LINES : aliased constant String := "false"; -- Whether the unknown tags are escaped in the output VIEW_ESCAPE_UNKNOWN_TAGS_PARAM : constant Config_Param; VIEW_ESCAPE_UNKNOWN_TAGS : aliased constant String := "view.escape_unknown_tags"; DEF_ESCAPE_UNKNOWN_TAGS : aliased constant String := "false"; -- Extensions used by static pages VIEW_STATIC_EXT_PARAM : constant Config_Param; VIEW_STATIC_EXT : aliased constant String := "view.static.ext"; DEF_STATIC_EXT : aliased constant String := ""; -- Directories which contain static pages VIEW_STATIC_DIR_PARAM : constant Config_Param; VIEW_STATIC_DIR : aliased constant String := "view.static.dir"; DEF_STATIC_DIR : aliased constant String := "css,js,scripts,themes"; -- The 404 error page to render ERROR_404_PARAM : constant Config_Param; ERROR_404_PAGE : aliased constant String := "view.error.404"; DEF_ERROR_404 : aliased constant String := "errors/404"; -- The 500 error page to render ERROR_500_PARAM : constant Config_Param; ERROR_500_PAGE : aliased constant String := "view.error.500"; DEF_ERROR_500 : aliased constant String := "errors/500"; -- Get the configuration parameter; function Get (Self : Config; Param : Config_Param) return String; -- Get the configuration parameter; function Get (Self : Config; Param : Config_Param) return Ada.Strings.Unbounded.Unbounded_String; -- Get the configuration parameter; function Get (Self : Config; Param : Config_Param) return Boolean; -- Create the configuration parameter definition instance. generic -- The parameter name. Name : in String; -- The default value. Default : in String; package Parameter is -- Returns the configuration parameter. function P return Config_Param; pragma Inline_Always (P); PARAM_NAME : aliased constant String := Name; PARAM_VALUE : aliased constant String := Default; end Parameter; private type Config_Param is record Name : Util.Strings.Name_Access; Default : Util.Strings.Name_Access; end record; subtype P is Config_Param; VIEW_DIR_PARAM : constant Config_Param := P '(Name => VIEW_DIR'Access, Default => DEF_VIEW_DIR'Access); VIEW_EXT_PARAM : constant Config_Param := P '(Name => VIEW_EXT'Access, Default => DEF_VIEW_EXT'Access); VIEW_FILE_EXT_PARAM : constant Config_Param := P '(Name => VIEW_FILE_EXT'Access, Default => DEF_VIEW_FILE_EXT'Access); VIEW_IGNORE_WHITE_SPACES_PARAM : constant Config_Param := P '(Name => VIEW_IGNORE_WHITE_SPACES'Access, Default => DEF_IGNORE_WHITE_SPACES'Access); VIEW_IGNORE_EMPTY_LINES_PARAM : constant Config_Param := P '(Name => VIEW_IGNORE_EMPTY_LINES'Access, Default => DEF_IGNORE_EMPTY_LINES'Access); VIEW_ESCAPE_UNKNOWN_TAGS_PARAM : constant Config_Param := P '(Name => VIEW_ESCAPE_UNKNOWN_TAGS'Access, Default => DEF_ESCAPE_UNKNOWN_TAGS'Access); VIEW_STATIC_EXT_PARAM : constant Config_Param := P '(Name => VIEW_STATIC_EXT'Access, Default => DEF_STATIC_EXT'Access); VIEW_STATIC_DIR_PARAM : constant Config_Param := P '(Name => VIEW_STATIC_DIR'Access, Default => DEF_STATIC_DIR'Access); ERROR_404_PARAM : constant Config_Param := P '(Name => ERROR_404_PAGE'Access, Default => DEF_ERROR_404'Access); ERROR_500_PARAM : constant Config_Param := P '(Name => ERROR_500_PAGE'Access, Default => DEF_ERROR_500'Access); type Config is new Util.Properties.Manager with null record; end ASF.Applications;
----------------------------------------------------------------------- -- applications -- Ada Web Application -- Copyright (C) 2009, 2010, 2013, 2015, 2020 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Strings.Unbounded; with Util.Strings; with Util.Properties; package ASF.Applications is use Util.Properties; type Config is new Util.Properties.Manager with private; type Config_Param is private; -- Directory where the facelet files are stored. VIEW_DIR_PARAM : constant Config_Param; VIEW_DIR : aliased constant String := "view.dir"; DEF_VIEW_DIR : aliased constant String := "web"; -- Extension used by requests VIEW_EXT_PARAM : constant Config_Param; VIEW_EXT : aliased constant String := "view.ext"; DEF_VIEW_EXT : aliased constant String := ""; -- Extension used by facelet files VIEW_FILE_EXT_PARAM : constant Config_Param; VIEW_FILE_EXT : aliased constant String := "view.file_ext"; DEF_VIEW_FILE_EXT : aliased constant String := ".xhtml"; -- Whether white spaces in XHTML files are ignored. VIEW_IGNORE_WHITE_SPACES_PARAM : constant Config_Param; VIEW_IGNORE_WHITE_SPACES : aliased constant String := "view.ignore_white_spaces"; DEF_IGNORE_WHITE_SPACES : aliased constant String := "false"; -- Whether empty lines in XHTML files are ignored. VIEW_IGNORE_EMPTY_LINES_PARAM : constant Config_Param; VIEW_IGNORE_EMPTY_LINES : aliased constant String := "view.ignore_empty_lines"; DEF_IGNORE_EMPTY_LINES : aliased constant String := "false"; -- Whether the unknown tags are escaped in the output VIEW_ESCAPE_UNKNOWN_TAGS_PARAM : constant Config_Param; VIEW_ESCAPE_UNKNOWN_TAGS : aliased constant String := "view.escape_unknown_tags"; DEF_ESCAPE_UNKNOWN_TAGS : aliased constant String := "false"; -- Extensions used by static pages VIEW_STATIC_EXT_PARAM : constant Config_Param; VIEW_STATIC_EXT : aliased constant String := "view.static.ext"; DEF_STATIC_EXT : aliased constant String := ""; -- Directories which contain static pages VIEW_STATIC_DIR_PARAM : constant Config_Param; VIEW_STATIC_DIR : aliased constant String := "view.static.dir"; DEF_STATIC_DIR : aliased constant String := "css,js,scripts,themes"; -- The 404 error page to render ERROR_404_PARAM : constant Config_Param; ERROR_404_PAGE : aliased constant String := "view.error.404"; DEF_ERROR_404 : aliased constant String := "errors/404"; -- The 500 error page to render ERROR_500_PARAM : constant Config_Param; ERROR_500_PAGE : aliased constant String := "view.error.500"; DEF_ERROR_500 : aliased constant String := "errors/500"; -- Get the configuration parameter; function Get (Self : Config; Param : Config_Param) return String; -- Get the configuration parameter; function Get (Self : Config; Param : Config_Param) return Ada.Strings.Unbounded.Unbounded_String; -- Get the configuration parameter; function Get (Self : Config; Param : Config_Param) return Boolean; function Get (Self : Config; Param : Config_Param) return Integer; -- Create the configuration parameter definition instance. generic -- The parameter name. Name : in String; -- The default value. Default : in String; package Parameter is -- Returns the configuration parameter. function P return Config_Param; pragma Inline_Always (P); PARAM_NAME : aliased constant String := Name; PARAM_VALUE : aliased constant String := Default; end Parameter; private type Config_Param is record Name : Util.Strings.Name_Access; Default : Util.Strings.Name_Access; end record; subtype P is Config_Param; VIEW_DIR_PARAM : constant Config_Param := P '(Name => VIEW_DIR'Access, Default => DEF_VIEW_DIR'Access); VIEW_EXT_PARAM : constant Config_Param := P '(Name => VIEW_EXT'Access, Default => DEF_VIEW_EXT'Access); VIEW_FILE_EXT_PARAM : constant Config_Param := P '(Name => VIEW_FILE_EXT'Access, Default => DEF_VIEW_FILE_EXT'Access); VIEW_IGNORE_WHITE_SPACES_PARAM : constant Config_Param := P '(Name => VIEW_IGNORE_WHITE_SPACES'Access, Default => DEF_IGNORE_WHITE_SPACES'Access); VIEW_IGNORE_EMPTY_LINES_PARAM : constant Config_Param := P '(Name => VIEW_IGNORE_EMPTY_LINES'Access, Default => DEF_IGNORE_EMPTY_LINES'Access); VIEW_ESCAPE_UNKNOWN_TAGS_PARAM : constant Config_Param := P '(Name => VIEW_ESCAPE_UNKNOWN_TAGS'Access, Default => DEF_ESCAPE_UNKNOWN_TAGS'Access); VIEW_STATIC_EXT_PARAM : constant Config_Param := P '(Name => VIEW_STATIC_EXT'Access, Default => DEF_STATIC_EXT'Access); VIEW_STATIC_DIR_PARAM : constant Config_Param := P '(Name => VIEW_STATIC_DIR'Access, Default => DEF_STATIC_DIR'Access); ERROR_404_PARAM : constant Config_Param := P '(Name => ERROR_404_PAGE'Access, Default => DEF_ERROR_404'Access); ERROR_500_PARAM : constant Config_Param := P '(Name => ERROR_500_PAGE'Access, Default => DEF_ERROR_500'Access); type Config is new Util.Properties.Manager with null record; end ASF.Applications;
Add a new Get function that returns the configuration parameter value as integer
Add a new Get function that returns the configuration parameter value as integer
Ada
apache-2.0
stcarrez/ada-asf,stcarrez/ada-asf,stcarrez/ada-asf
17ec91e415dcb5618f3fef61cc52e59674cd6994
mat/src/mat-commands.adb
mat/src/mat-commands.adb
----------------------------------------------------------------------- -- mat-interp -- Command interpreter -- 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.Strings; with Util.Log.Loggers; with Ada.Containers.Indefinite_Hashed_Maps; with Ada.Strings.Hash; with Ada.IO_Exceptions; with Ada.Text_IO; with Ada.Strings.Unbounded; with Bfd; with MAT.Types; with MAT.Readers.Files; with MAT.Memory.Tools; with MAT.Memory.Targets; with MAT.Symbols.Targets; with MAT.Frames; with MAT.Frames.Print; with MAT.Consoles; package body MAT.Commands is -- The logger Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("MAT.Commands"); package Command_Map is new Ada.Containers.Indefinite_Hashed_Maps (Key_Type => String, Element_Type => Command_Handler, Equivalent_Keys => "=", Hash => Ada.Strings.Hash); Commands : Command_Map.Map; -- ------------------------------ -- Sizes command. -- Collect statistics about the used memory slots and report the different slot -- sizes with count. -- ------------------------------ procedure Slot_Command (Target : in out MAT.Targets.Target_Type'Class; Args : in String) is Slots : MAT.Memory.Allocation_Map; Iter : MAT.Memory.Allocation_Cursor; procedure Print (Addr : in MAT.Types.Target_Addr; Slot : in MAT.Memory.Allocation) is use type MAT.Frames.Frame_Type; Backtrace : MAT.Frames.Frame_Table := MAT.Frames.Backtrace (Slot.Frame); Name : Ada.Strings.Unbounded.Unbounded_String; Func : Ada.Strings.Unbounded.Unbounded_String; Line : Natural; begin Ada.Text_IO.Put (MAT.Types.Hex_Image (Addr)); Ada.Text_IO.Set_Col (14); Ada.Text_IO.Put (MAT.Types.Target_Size'Image (Slot.Size)); Ada.Text_IO.Set_Col (30); Ada.Text_IO.Put (MAT.Types.Target_Thread_Ref'Image (Slot.Thread)); Ada.Text_IO.Set_Col (50); Ada.Text_IO.Put (MAT.Types.Target_Tick_Ref'Image (Slot.Time)); Ada.Text_IO.New_Line; for I in Backtrace'Range loop Ada.Text_IO.Put (" "); Ada.Text_IO.Put (Natural'Image (I)); Ada.Text_IO.Put (" "); Ada.Text_IO.Put (MAT.Types.Hex_Image (Backtrace (I))); MAT.Symbols.Targets.Find_Nearest_Line (Symbols => Target.Symbols, Addr => Backtrace (I), Name => Name, Func => Func, Line => Line); Ada.Text_IO.Put (" "); Ada.Text_IO.Put (Ada.Strings.Unbounded.To_String (Func)); Ada.Text_IO.Put (" "); Ada.Text_IO.Put (Ada.Strings.Unbounded.To_String (Name)); if Line /= 0 then Ada.Text_IO.Put (":"); Ada.Text_IO.Put (Util.Strings.Image (Line)); end if; Ada.Text_IO.New_Line; end loop; end Print; begin Target.Memory.Find (From => MAT.Types.Target_Addr'First, To => MAT.Types.Target_Addr'Last, Into => Slots); Iter := Slots.First; while MAT.Memory.Allocation_Maps.Has_Element (Iter) loop MAT.Memory.Allocation_Maps.Query_Element (Iter, Print'Access); MAT.Memory.Allocation_Maps.Next (Iter); end loop; end Slot_Command; -- ------------------------------ -- Sizes command. -- Collect statistics about the used memory slots and report the different slot -- sizes with count. -- ------------------------------ procedure Sizes_Command (Target : in out MAT.Targets.Target_Type'Class; Args : in String) is Sizes : MAT.Memory.Tools.Size_Info_Map; Iter : MAT.Memory.Tools.Size_Info_Cursor; Console : constant MAT.Consoles.Console_Access := Target.Console; begin Console.Start_Title; Console.Print_Title (MAT.Consoles.F_SIZE, "Slot size", 25); Console.Print_Title (MAT.Consoles.F_COUNT, "Count", 15); Console.Print_Title (MAT.Consoles.F_TOTAL_SIZE, "Total size", 15); Console.End_Title; MAT.Memory.Targets.Size_Information (Memory => Target.Memory, Sizes => Sizes); Iter := Sizes.First; while MAT.Memory.Tools.Size_Info_Maps.Has_Element (Iter) loop declare use type MAT.Types.Target_Size; Size : MAT.Types.Target_Size := MAT.Memory.Tools.Size_Info_Maps.Key (Iter); Info : MAT.Memory.Tools.Size_Info_Type := MAT.Memory.Tools.Size_Info_Maps.Element (Iter); Total : MAT.Types.Target_Size := Size * MAT.Types.Target_Size (Info.Count); begin Console.Start_Row; Console.Print_Size (MAT.Consoles.F_SIZE, Size); Console.Print_Field (MAT.Consoles.F_COUNT, Info.Count); Console.Print_Field (MAT.Consoles.F_TOTAL_SIZE, Total); Console.End_Row; end; MAT.Memory.Tools.Size_Info_Maps.Next (Iter); end loop; end Sizes_Command; -- ------------------------------ -- Threads command. -- Collect statistics about the threads and their allocation. -- ------------------------------ procedure Threads_Command (Target : in out MAT.Targets.Target_Type'Class; Args : in String) is Sizes : MAT.Memory.Tools.Size_Info_Map; Threads : MAT.Memory.Memory_Info_Map; Iter : MAT.Memory.Memory_Info_Cursor; Console : constant MAT.Consoles.Console_Access := Target.Console; begin Console.Start_Title; Console.Print_Title (MAT.Consoles.F_Thread, "Thread", 10); Console.Print_Title (MAT.Consoles.F_COUNT, "# Allocation", 12); Console.Print_Title (MAT.Consoles.F_TOTAL_SIZE, "Total size", 15); Console.Print_Title (MAT.Consoles.F_MIN_SIZE, "Min slot size", 15); Console.Print_Title (MAT.Consoles.F_MAX_SIZE, "Max slot size", 15); Console.Print_Title (MAT.Consoles.F_MIN_ADDR, "Low address", 15); Console.Print_Title (MAT.Consoles.F_MAX_ADDR, "High address", 15); Console.End_Title; MAT.Memory.Targets.Thread_Information (Memory => Target.Memory, Threads => Threads); Iter := Threads.First; while MAT.Memory.Memory_Info_Maps.Has_Element (Iter) loop declare use type MAT.Types.Target_Size; Thread : constant Types.Target_Thread_Ref := MAT.Memory.Memory_Info_Maps.Key (Iter); Info : constant Memory.Memory_Info := MAT.Memory.Memory_Info_Maps.Element (Iter); begin Console.Start_Row; Console.Print_Field (MAT.Consoles.F_THREAD, Integer (Thread)); Console.Print_Field (MAT.Consoles.F_COUNT, Info.Alloc_Count); Console.Print_Size (MAT.Consoles.F_TOTAL_SIZE, Info.Total_Size); Console.Print_Size (MAT.Consoles.F_MIN_SIZE, Info.Min_Slot_Size); Console.Print_Size (MAT.Consoles.F_MAX_SIZE, Info.Max_Slot_Size); Console.Print_Field (MAT.Consoles.F_MIN_ADDR, Info.Min_Addr); Console.Print_Field (MAT.Consoles.F_MAX_ADDR, Info.Max_Addr); Console.End_Row; end; MAT.Memory.Memory_Info_Maps.Next (Iter); end loop; end Threads_Command; -- ------------------------------ -- Symbol command. -- Load the symbols from the binary file. -- ------------------------------ procedure Symbol_Command (Target : in out MAT.Targets.Target_Type'Class; Args : in String) is begin MAT.Symbols.Targets.Open (Target.Symbols, Args); exception when Bfd.OPEN_ERROR => Target.Console.Error ("Cannot open symbol file '" & Args & "'"); end Symbol_Command; -- ------------------------------ -- Exit command. -- ------------------------------ procedure Exit_Command (Target : in out MAT.Targets.Target_Type'Class; Args : in String) is begin raise Stop_Interp; end Exit_Command; -- ------------------------------ -- Open a MAT file and read the events. -- ------------------------------ procedure Open_Command (Target : in out MAT.Targets.Target_Type'Class; Args : in String) is Reader : MAT.Readers.Files.File_Reader_Type; begin Target.Initialize (Reader); Reader.Open (Args); Reader.Read_All; exception when E : Ada.IO_Exceptions.Name_Error => Log.Error ("Cannot open {0}", Args); end Open_Command; function Get_Command (Line : in String) return String is Pos : Natural := Util.Strings.Index (Line, ' '); begin if Pos <= 0 then return Line; else return Line (Line'First .. Pos - 1); end if; end Get_Command; -- ------------------------------ -- Execute the command given in the line. -- ------------------------------ procedure Execute (Target : in out MAT.Targets.Target_Type'Class; Line : in String) is Command : constant String := Get_Command (Line); Index : constant Natural := Util.Strings.Index (Line, ' '); Pos : constant Command_Map.Cursor := Commands.Find (Command); begin if Command_Map.Has_Element (Pos) then Command_Map.Element (Pos) (Target, Line (Index + 1 .. Line'Last)); elsif Command'Length > 0 then Target.Console.Error ("Command '" & Command & "' not found"); end if; end Execute; begin Commands.Insert ("exit", Exit_Command'Access); Commands.Insert ("quit", Exit_Command'Access); Commands.Insert ("open", Open_Command'Access); Commands.Insert ("sizes", Sizes_Command'Access); Commands.Insert ("symbol", Symbol_Command'Access); Commands.Insert ("slots", Slot_Command'Access); Commands.Insert ("threads", Threads_Command'Access); end MAT.Commands;
----------------------------------------------------------------------- -- mat-interp -- Command interpreter -- 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.Strings; with Util.Log.Loggers; with Ada.Containers.Indefinite_Hashed_Maps; with Ada.Strings.Hash; with Ada.IO_Exceptions; with Ada.Text_IO; with Ada.Strings.Unbounded; with Bfd; with MAT.Types; with MAT.Readers.Files; with MAT.Memory.Tools; with MAT.Memory.Targets; with MAT.Symbols.Targets; with MAT.Expressions; with MAT.Frames; with MAT.Frames.Print; with MAT.Consoles; package body MAT.Commands is -- The logger Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("MAT.Commands"); package Command_Map is new Ada.Containers.Indefinite_Hashed_Maps (Key_Type => String, Element_Type => Command_Handler, Equivalent_Keys => "=", Hash => Ada.Strings.Hash); Commands : Command_Map.Map; -- ------------------------------ -- Sizes command. -- Collect statistics about the used memory slots and report the different slot -- sizes with count. -- ------------------------------ procedure Slot_Command (Target : in out MAT.Targets.Target_Type'Class; Args : in String) is Slots : MAT.Memory.Allocation_Map; Iter : MAT.Memory.Allocation_Cursor; procedure Print (Addr : in MAT.Types.Target_Addr; Slot : in MAT.Memory.Allocation) is use type MAT.Frames.Frame_Type; Backtrace : MAT.Frames.Frame_Table := MAT.Frames.Backtrace (Slot.Frame); Name : Ada.Strings.Unbounded.Unbounded_String; Func : Ada.Strings.Unbounded.Unbounded_String; Line : Natural; begin Ada.Text_IO.Put (MAT.Types.Hex_Image (Addr)); Ada.Text_IO.Set_Col (14); Ada.Text_IO.Put (MAT.Types.Target_Size'Image (Slot.Size)); Ada.Text_IO.Set_Col (30); Ada.Text_IO.Put (MAT.Types.Target_Thread_Ref'Image (Slot.Thread)); Ada.Text_IO.Set_Col (50); Ada.Text_IO.Put (MAT.Types.Target_Tick_Ref'Image (Slot.Time)); Ada.Text_IO.New_Line; for I in Backtrace'Range loop Ada.Text_IO.Put (" "); Ada.Text_IO.Put (Natural'Image (I)); Ada.Text_IO.Put (" "); Ada.Text_IO.Put (MAT.Types.Hex_Image (Backtrace (I))); MAT.Symbols.Targets.Find_Nearest_Line (Symbols => Target.Symbols, Addr => Backtrace (I), Name => Name, Func => Func, Line => Line); Ada.Text_IO.Put (" "); Ada.Text_IO.Put (Ada.Strings.Unbounded.To_String (Func)); Ada.Text_IO.Put (" "); Ada.Text_IO.Put (Ada.Strings.Unbounded.To_String (Name)); if Line /= 0 then Ada.Text_IO.Put (":"); Ada.Text_IO.Put (Util.Strings.Image (Line)); end if; Ada.Text_IO.New_Line; end loop; end Print; Filter : MAT.Expressions.Expression_Type; begin Target.Memory.Find (From => MAT.Types.Target_Addr'First, To => MAT.Types.Target_Addr'Last, Filter => Filter, Into => Slots); Iter := Slots.First; while MAT.Memory.Allocation_Maps.Has_Element (Iter) loop MAT.Memory.Allocation_Maps.Query_Element (Iter, Print'Access); MAT.Memory.Allocation_Maps.Next (Iter); end loop; end Slot_Command; -- ------------------------------ -- Sizes command. -- Collect statistics about the used memory slots and report the different slot -- sizes with count. -- ------------------------------ procedure Sizes_Command (Target : in out MAT.Targets.Target_Type'Class; Args : in String) is Sizes : MAT.Memory.Tools.Size_Info_Map; Iter : MAT.Memory.Tools.Size_Info_Cursor; Console : constant MAT.Consoles.Console_Access := Target.Console; begin Console.Start_Title; Console.Print_Title (MAT.Consoles.F_SIZE, "Slot size", 25); Console.Print_Title (MAT.Consoles.F_COUNT, "Count", 15); Console.Print_Title (MAT.Consoles.F_TOTAL_SIZE, "Total size", 15); Console.End_Title; MAT.Memory.Targets.Size_Information (Memory => Target.Memory, Sizes => Sizes); Iter := Sizes.First; while MAT.Memory.Tools.Size_Info_Maps.Has_Element (Iter) loop declare use type MAT.Types.Target_Size; Size : MAT.Types.Target_Size := MAT.Memory.Tools.Size_Info_Maps.Key (Iter); Info : MAT.Memory.Tools.Size_Info_Type := MAT.Memory.Tools.Size_Info_Maps.Element (Iter); Total : MAT.Types.Target_Size := Size * MAT.Types.Target_Size (Info.Count); begin Console.Start_Row; Console.Print_Size (MAT.Consoles.F_SIZE, Size); Console.Print_Field (MAT.Consoles.F_COUNT, Info.Count); Console.Print_Field (MAT.Consoles.F_TOTAL_SIZE, Total); Console.End_Row; end; MAT.Memory.Tools.Size_Info_Maps.Next (Iter); end loop; end Sizes_Command; -- ------------------------------ -- Threads command. -- Collect statistics about the threads and their allocation. -- ------------------------------ procedure Threads_Command (Target : in out MAT.Targets.Target_Type'Class; Args : in String) is Sizes : MAT.Memory.Tools.Size_Info_Map; Threads : MAT.Memory.Memory_Info_Map; Iter : MAT.Memory.Memory_Info_Cursor; Console : constant MAT.Consoles.Console_Access := Target.Console; begin Console.Start_Title; Console.Print_Title (MAT.Consoles.F_Thread, "Thread", 10); Console.Print_Title (MAT.Consoles.F_COUNT, "# Allocation", 12); Console.Print_Title (MAT.Consoles.F_TOTAL_SIZE, "Total size", 15); Console.Print_Title (MAT.Consoles.F_MIN_SIZE, "Min slot size", 15); Console.Print_Title (MAT.Consoles.F_MAX_SIZE, "Max slot size", 15); Console.Print_Title (MAT.Consoles.F_MIN_ADDR, "Low address", 15); Console.Print_Title (MAT.Consoles.F_MAX_ADDR, "High address", 15); Console.End_Title; MAT.Memory.Targets.Thread_Information (Memory => Target.Memory, Threads => Threads); Iter := Threads.First; while MAT.Memory.Memory_Info_Maps.Has_Element (Iter) loop declare use type MAT.Types.Target_Size; Thread : constant Types.Target_Thread_Ref := MAT.Memory.Memory_Info_Maps.Key (Iter); Info : constant Memory.Memory_Info := MAT.Memory.Memory_Info_Maps.Element (Iter); begin Console.Start_Row; Console.Print_Field (MAT.Consoles.F_THREAD, Integer (Thread)); Console.Print_Field (MAT.Consoles.F_COUNT, Info.Alloc_Count); Console.Print_Size (MAT.Consoles.F_TOTAL_SIZE, Info.Total_Size); Console.Print_Size (MAT.Consoles.F_MIN_SIZE, Info.Min_Slot_Size); Console.Print_Size (MAT.Consoles.F_MAX_SIZE, Info.Max_Slot_Size); Console.Print_Field (MAT.Consoles.F_MIN_ADDR, Info.Min_Addr); Console.Print_Field (MAT.Consoles.F_MAX_ADDR, Info.Max_Addr); Console.End_Row; end; MAT.Memory.Memory_Info_Maps.Next (Iter); end loop; end Threads_Command; -- ------------------------------ -- Symbol command. -- Load the symbols from the binary file. -- ------------------------------ procedure Symbol_Command (Target : in out MAT.Targets.Target_Type'Class; Args : in String) is begin MAT.Symbols.Targets.Open (Target.Symbols, Args); exception when Bfd.OPEN_ERROR => Target.Console.Error ("Cannot open symbol file '" & Args & "'"); end Symbol_Command; -- ------------------------------ -- Exit command. -- ------------------------------ procedure Exit_Command (Target : in out MAT.Targets.Target_Type'Class; Args : in String) is begin raise Stop_Interp; end Exit_Command; -- ------------------------------ -- Open a MAT file and read the events. -- ------------------------------ procedure Open_Command (Target : in out MAT.Targets.Target_Type'Class; Args : in String) is Reader : MAT.Readers.Files.File_Reader_Type; begin Target.Initialize (Reader); Reader.Open (Args); Reader.Read_All; exception when E : Ada.IO_Exceptions.Name_Error => Log.Error ("Cannot open {0}", Args); end Open_Command; function Get_Command (Line : in String) return String is Pos : Natural := Util.Strings.Index (Line, ' '); begin if Pos <= 0 then return Line; else return Line (Line'First .. Pos - 1); end if; end Get_Command; -- ------------------------------ -- Execute the command given in the line. -- ------------------------------ procedure Execute (Target : in out MAT.Targets.Target_Type'Class; Line : in String) is Command : constant String := Get_Command (Line); Index : constant Natural := Util.Strings.Index (Line, ' '); Pos : constant Command_Map.Cursor := Commands.Find (Command); begin if Command_Map.Has_Element (Pos) then Command_Map.Element (Pos) (Target, Line (Index + 1 .. Line'Last)); elsif Command'Length > 0 then Target.Console.Error ("Command '" & Command & "' not found"); end if; end Execute; begin Commands.Insert ("exit", Exit_Command'Access); Commands.Insert ("quit", Exit_Command'Access); Commands.Insert ("open", Open_Command'Access); Commands.Insert ("sizes", Sizes_Command'Access); Commands.Insert ("symbol", Symbol_Command'Access); Commands.Insert ("slots", Slot_Command'Access); Commands.Insert ("threads", Threads_Command'Access); end MAT.Commands;
Add a Filter instance to the Find operation
Add a Filter instance to the Find operation
Ada
apache-2.0
stcarrez/mat,stcarrez/mat,stcarrez/mat
b7bab24a107f6ced422b161137a5cc4c14c7ef56
mat/src/mat-commands.adb
mat/src/mat-commands.adb
----------------------------------------------------------------------- -- mat-interp -- Command interpreter -- 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.Strings; with Util.Log.Loggers; with Ada.Containers.Indefinite_Hashed_Maps; with Ada.Strings.Hash; with Ada.IO_Exceptions; with Ada.Text_IO; with MAT.Types; with MAT.Readers.Files; with MAT.Memory.Targets; with MAT.Symbols.Targets; with MAT.Frames; with MAT.Frames.Print; package body MAT.Commands is -- The logger Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("MAT.Commands"); package Command_Map is new Ada.Containers.Indefinite_Hashed_Maps (Key_Type => String, Element_Type => Command_Handler, Equivalent_Keys => "=", Hash => Ada.Strings.Hash); Commands : Command_Map.Map; -- ------------------------------ -- Sizes command. -- Collect statistics about the used memory slots and report the different slot -- sizes with count. -- ------------------------------ procedure Slot_Command (Target : in out MAT.Targets.Target_Type'Class; Args : in String) is Iter : MAT.Memory.Allocation_Cursor := Target.Memory.Memory_Slots.First; procedure Print (Addr : in MAT.Types.Target_Addr; Slot : in MAT.Memory.Allocation) is use type MAT.Frames.Frame_Ptr; Backtrace : MAT.Frames.PC_Table := MAT.Frames.Backtrace (Slot.Frame); begin Ada.Text_IO.Put (MAT.Types.Hex_Image (Addr)); Ada.Text_IO.Set_Col (14); Ada.Text_IO.Put (MAT.Types.Target_Size'Image (Slot.Size)); Ada.Text_IO.New_Line; for I in Backtrace'Range loop Ada.Text_IO.Put (" "); Ada.Text_IO.Put (Natural'Image (I)); Ada.Text_IO.Put (" "); Ada.Text_IO.Put_Line (MAT.Types.Hex_Image (Backtrace (I))); end loop; end Print; begin while MAT.Memory.Allocation_Maps.Has_Element (Iter) loop MAT.Memory.Allocation_Maps.Query_Element (Iter, Print'Access); MAT.Memory.Allocation_Maps.Next (Iter); end loop; end Slot_Command; -- ------------------------------ -- Sizes command. -- Collect statistics about the used memory slots and report the different slot -- sizes with count. -- ------------------------------ procedure Sizes_Command (Target : in out MAT.Targets.Target_Type'Class; Args : in String) is Sizes : MAT.Memory.Targets.Size_Info_Map; Iter : MAT.Memory.Targets.Size_Info_Cursor; begin MAT.Memory.Targets.Size_Information (Memory => Target.Memory, Sizes => Sizes); Iter := Sizes.First; while MAT.Memory.Targets.Size_Info_Maps.Has_Element (Iter) loop declare use type MAT.Types.Target_Size; Size : MAT.Types.Target_Size := MAT.Memory.Targets.Size_Info_Maps.Key (Iter); Info : MAT.Memory.Targets.Size_Info_Type := MAT.Memory.Targets.Size_Info_Maps.Element (Iter); Total : MAT.Types.Target_Size := Size * MAT.Types.Target_Size (Info.Count); begin Ada.Text_IO.Put (MAT.Types.Target_Size'Image (Size)); Ada.Text_IO.Set_Col (20); Ada.Text_IO.Put (Natural'Image (Info.Count)); Ada.Text_IO.Set_Col (30); Ada.Text_IO.Put_Line (MAT.Types.Target_Size'Image (Total)); end; MAT.Memory.Targets.Size_Info_Maps.Next (Iter); end loop; end Sizes_Command; -- ------------------------------ -- Symbol command. -- Load the symbols from the binary file. -- ------------------------------ procedure Symbol_Command (Target : in out MAT.Targets.Target_Type'Class; Args : in String) is begin MAT.Symbols.Targets.Open (Target.Symbols, Args); end Symbol_Command; -- ------------------------------ -- Exit command. -- ------------------------------ procedure Exit_Command (Target : in out MAT.Targets.Target_Type'Class; Args : in String) is begin raise Stop_Interp; end Exit_Command; -- ------------------------------ -- Open a MAT file and read the events. -- ------------------------------ procedure Open_Command (Target : in out MAT.Targets.Target_Type'Class; Args : in String) is Reader : MAT.Readers.Files.File_Reader_Type; begin Target.Initialize (Reader); Reader.Open (Args); Reader.Read_All; exception when E : Ada.IO_Exceptions.Name_Error => Log.Error ("Cannot open {0}", Args); end Open_Command; function Get_Command (Line : in String) return String is Pos : Natural := Util.Strings.Index (Line, ' '); begin if Pos <= 0 then return Line; else return Line (Line'First .. Pos - 1); end if; end Get_Command; -- ------------------------------ -- Execute the command given in the line. -- ------------------------------ procedure Execute (Target : in out MAT.Targets.Target_Type'Class; Line : in String) is Command : constant String := Get_Command (Line); Index : constant Natural := Util.Strings.Index (Line, ' '); Pos : constant Command_Map.Cursor := Commands.Find (Command); begin if Command_Map.Has_Element (Pos) then Command_Map.Element (Pos) (Target, Line (Index + 1 .. Line'Last)); end if; end Execute; begin Commands.Insert ("exit", Exit_Command'Access); Commands.Insert ("quit", Exit_Command'Access); Commands.Insert ("open", Open_Command'Access); Commands.Insert ("sizes", Sizes_Command'Access); Commands.Insert ("symbol", Symbol_Command'Access); Commands.Insert ("slots", Slot_Command'Access); end MAT.Commands;
----------------------------------------------------------------------- -- mat-interp -- Command interpreter -- 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.Strings; with Util.Log.Loggers; with Ada.Containers.Indefinite_Hashed_Maps; with Ada.Strings.Hash; with Ada.IO_Exceptions; with Ada.Text_IO; with Ada.Strings.Unbounded; with MAT.Types; with MAT.Readers.Files; with MAT.Memory.Targets; with MAT.Symbols.Targets; with MAT.Frames; with MAT.Frames.Print; package body MAT.Commands is -- The logger Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("MAT.Commands"); package Command_Map is new Ada.Containers.Indefinite_Hashed_Maps (Key_Type => String, Element_Type => Command_Handler, Equivalent_Keys => "=", Hash => Ada.Strings.Hash); Commands : Command_Map.Map; -- ------------------------------ -- Sizes command. -- Collect statistics about the used memory slots and report the different slot -- sizes with count. -- ------------------------------ procedure Slot_Command (Target : in out MAT.Targets.Target_Type'Class; Args : in String) is Iter : MAT.Memory.Allocation_Cursor := Target.Memory.Memory_Slots.First; procedure Print (Addr : in MAT.Types.Target_Addr; Slot : in MAT.Memory.Allocation) is use type MAT.Frames.Frame_Ptr; Backtrace : MAT.Frames.PC_Table := MAT.Frames.Backtrace (Slot.Frame); Name : Ada.Strings.Unbounded.Unbounded_String; Func : Ada.Strings.Unbounded.Unbounded_String; Line : Natural; begin Ada.Text_IO.Put (MAT.Types.Hex_Image (Addr)); Ada.Text_IO.Set_Col (14); Ada.Text_IO.Put (MAT.Types.Target_Size'Image (Slot.Size)); Ada.Text_IO.New_Line; for I in Backtrace'Range loop Ada.Text_IO.Put (" "); Ada.Text_IO.Put (Natural'Image (I)); Ada.Text_IO.Put (" "); Ada.Text_IO.Put (MAT.Types.Hex_Image (Backtrace (I))); MAT.Symbols.Targets.Find_Nearest_Line (Symbols => Target.Symbols, Addr => Backtrace (I), Name => Name, Func => Func, Line => Line); Ada.Text_IO.Put (" "); Ada.Text_IO.Put (Ada.Strings.Unbounded.To_String (Func)); Ada.Text_IO.Put (" "); Ada.Text_IO.Put (Ada.Strings.Unbounded.To_String (Name)); if Line /= 0 then Ada.Text_IO.Put (":"); Ada.Text_IO.Put (Util.Strings.Image (Line)); end if; Ada.Text_IO.New_Line; end loop; end Print; begin while MAT.Memory.Allocation_Maps.Has_Element (Iter) loop MAT.Memory.Allocation_Maps.Query_Element (Iter, Print'Access); MAT.Memory.Allocation_Maps.Next (Iter); end loop; end Slot_Command; -- ------------------------------ -- Sizes command. -- Collect statistics about the used memory slots and report the different slot -- sizes with count. -- ------------------------------ procedure Sizes_Command (Target : in out MAT.Targets.Target_Type'Class; Args : in String) is Sizes : MAT.Memory.Targets.Size_Info_Map; Iter : MAT.Memory.Targets.Size_Info_Cursor; begin MAT.Memory.Targets.Size_Information (Memory => Target.Memory, Sizes => Sizes); Iter := Sizes.First; while MAT.Memory.Targets.Size_Info_Maps.Has_Element (Iter) loop declare use type MAT.Types.Target_Size; Size : MAT.Types.Target_Size := MAT.Memory.Targets.Size_Info_Maps.Key (Iter); Info : MAT.Memory.Targets.Size_Info_Type := MAT.Memory.Targets.Size_Info_Maps.Element (Iter); Total : MAT.Types.Target_Size := Size * MAT.Types.Target_Size (Info.Count); begin Ada.Text_IO.Put (MAT.Types.Target_Size'Image (Size)); Ada.Text_IO.Set_Col (20); Ada.Text_IO.Put (Natural'Image (Info.Count)); Ada.Text_IO.Set_Col (30); Ada.Text_IO.Put_Line (MAT.Types.Target_Size'Image (Total)); end; MAT.Memory.Targets.Size_Info_Maps.Next (Iter); end loop; end Sizes_Command; -- ------------------------------ -- Symbol command. -- Load the symbols from the binary file. -- ------------------------------ procedure Symbol_Command (Target : in out MAT.Targets.Target_Type'Class; Args : in String) is begin MAT.Symbols.Targets.Open (Target.Symbols, Args); end Symbol_Command; -- ------------------------------ -- Exit command. -- ------------------------------ procedure Exit_Command (Target : in out MAT.Targets.Target_Type'Class; Args : in String) is begin raise Stop_Interp; end Exit_Command; -- ------------------------------ -- Open a MAT file and read the events. -- ------------------------------ procedure Open_Command (Target : in out MAT.Targets.Target_Type'Class; Args : in String) is Reader : MAT.Readers.Files.File_Reader_Type; begin Target.Initialize (Reader); Reader.Open (Args); Reader.Read_All; exception when E : Ada.IO_Exceptions.Name_Error => Log.Error ("Cannot open {0}", Args); end Open_Command; function Get_Command (Line : in String) return String is Pos : Natural := Util.Strings.Index (Line, ' '); begin if Pos <= 0 then return Line; else return Line (Line'First .. Pos - 1); end if; end Get_Command; -- ------------------------------ -- Execute the command given in the line. -- ------------------------------ procedure Execute (Target : in out MAT.Targets.Target_Type'Class; Line : in String) is Command : constant String := Get_Command (Line); Index : constant Natural := Util.Strings.Index (Line, ' '); Pos : constant Command_Map.Cursor := Commands.Find (Command); begin if Command_Map.Has_Element (Pos) then Command_Map.Element (Pos) (Target, Line (Index + 1 .. Line'Last)); end if; end Execute; begin Commands.Insert ("exit", Exit_Command'Access); Commands.Insert ("quit", Exit_Command'Access); Commands.Insert ("open", Open_Command'Access); Commands.Insert ("sizes", Sizes_Command'Access); Commands.Insert ("symbol", Symbol_Command'Access); Commands.Insert ("slots", Slot_Command'Access); end MAT.Commands;
Use the symbol table to find the file, function and line when printing the backtrace
Use the symbol table to find the file, function and line when printing the backtrace
Ada
apache-2.0
stcarrez/mat,stcarrez/mat,stcarrez/mat
ae8d599c3ed0177bb4e57047755d1edcad906c91
src/wiki-nodes-dump.adb
src/wiki-nodes-dump.adb
----------------------------------------------------------------------- -- wiki-nodes-dump -- Dump the wiki nodes -- Copyright (C) 2022 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Wiki.Nodes.Lists; with Wiki.Strings; with Wiki.Attributes; procedure Wiki.Nodes.Dump (Node : in Wiki.Nodes.Node_Type) is procedure Dump_Node (Node : in Wiki.Nodes.Node_Type); Level : Positive := 1; procedure Dump_Node (Node : in Wiki.Nodes.Node_Type) is procedure Print_Length (Len : Natural); procedure Print (Name : in String; Value : in Wiki.Strings.WString); Kind : constant Wiki.Strings.WString := Node_Kind'Wide_Wide_Image (Node.Kind); Result : Wiki.Strings.BString (256); procedure Print (Name : in String; Value : in Wiki.Strings.WString) is begin Strings.Append_String (Result, " "); Strings.Append_String (Result, Strings.To_WString (Name)); Strings.Append_String (Result, "="); Strings.Append_String (Result, Value); end Print; procedure Print_Length (Len : Natural) is S : constant Wide_Wide_String := Natural'Wide_Wide_Image (Len); begin Strings.Append_String (Result, " ("); Strings.Append_String (Result, S (S'First + 1 .. S'Last)); Strings.Append_String (Result, ")"); end Print_Length; begin if Node.Kind = N_TAG_START then Strings.Append_String (Result, Html_Tag'Wide_Wide_Image (Node.Tag_Start)); else Strings.Append_String (Result, Kind); end if; Print_Length (Node.Len); case Node.Kind is when N_HEADER | N_BLOCKQUOTE | N_INDENT | N_TOC_ENTRY | N_NUM_LIST_START | N_LIST_START | N_DEFINITION => Strings.Append_String (Result, Natural'Wide_Wide_Image (Node.Level)); Strings.Append_String (Result, " "); -- Strings.Append_String (Result, Node.Header); if Node.Content /= null then Level := Level + 1; Lists.Iterate (Node.Content, Dump_Node'Access); Level := Level - 1; end if; when N_TEXT => for Format in Format_Type'Range loop if Node.Format (Format) then Strings.Append_String (Result, " "); Strings.Append_String (Result, Format_Type'Wide_Wide_Image (Format)); end if; end loop; Strings.Append_String (Result, " "); Strings.Append_String (Result, Node.Text); when N_IMAGE | N_LINK | N_QUOTE => Strings.Append_String (Result, " "); Strings.Append_String (Result, Node.Title); Attributes.Iterate (Node.Link_Attr, Print'Access); when N_TAG_START | N_TABLE | N_ROW | N_COLUMN => Attributes.Iterate (Node.Attributes, Print'Access); Write (Level, Wiki.Strings.To_WString (Result)); if Node.Children /= null then Level := Level + 1; Lists.Iterate (Node.Children, Dump_Node'Access); Level := Level - 1; end if; return; when N_PREFORMAT => Strings.Append_String (Result, " "); Strings.Append_String (Result, Strings.To_WString (Node.Language)); Strings.Append_String (Result, " "); Strings.Append_String (Result, Node.Preformatted); when others => null; end case; Write (Level, Wiki.Strings.To_WString (Result)); end Dump_Node; begin Dump_Node (Node); end Wiki.Nodes.Dump;
----------------------------------------------------------------------- -- wiki-nodes-dump -- Dump the wiki nodes -- Copyright (C) 2022 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Wiki.Nodes.Lists; with Wiki.Strings; with Wiki.Attributes; procedure Wiki.Nodes.Dump (Node : in Wiki.Nodes.Node_Type) is procedure Dump_Node (Node : in Wiki.Nodes.Node_Type); Level : Positive := 1; procedure Dump_Node (Node : in Wiki.Nodes.Node_Type) is procedure Print_Length (Len : Natural); procedure Print (Name : in String; Value : in Wiki.Strings.WString); Kind : constant Wiki.Strings.WString := Node_Kind'Wide_Wide_Image (Node.Kind); Result : Wiki.Strings.BString (256); procedure Print (Name : in String; Value : in Wiki.Strings.WString) is begin Strings.Append_String (Result, " "); Strings.Append_String (Result, Strings.To_WString (Name)); Strings.Append_String (Result, "="); Strings.Append_String (Result, Value); end Print; procedure Print_Length (Len : Natural) is S : constant Wide_Wide_String := Natural'Wide_Wide_Image (Len); begin Strings.Append_String (Result, " ("); Strings.Append_String (Result, S (S'First + 1 .. S'Last)); Strings.Append_String (Result, ")"); end Print_Length; begin if Node.Kind = N_TAG_START then Strings.Append_String (Result, Html_Tag'Wide_Wide_Image (Node.Tag_Start)); else Strings.Append_String (Result, Kind); end if; Print_Length (Node.Len); case Node.Kind is when N_HEADER | N_BLOCKQUOTE | N_INDENT | N_TOC_ENTRY | N_NUM_LIST_START | N_LIST_START | N_DEFINITION => Strings.Append_String (Result, Natural'Wide_Wide_Image (Node.Level)); Strings.Append_String (Result, " "); Write (Level, Wiki.Strings.To_WString (Result)); if Node.Content /= null then Level := Level + 1; Lists.Iterate (Node.Content, Dump_Node'Access); Level := Level - 1; end if; return; when N_TEXT => for Format in Format_Type'Range loop if Node.Format (Format) then Strings.Append_String (Result, " "); Strings.Append_String (Result, Format_Type'Wide_Wide_Image (Format)); end if; end loop; Strings.Append_String (Result, " "); Strings.Append_String (Result, Node.Text); when N_IMAGE | N_LINK | N_QUOTE => Strings.Append_String (Result, " "); Strings.Append_String (Result, Node.Title); Attributes.Iterate (Node.Link_Attr, Print'Access); when N_TAG_START | N_TABLE | N_ROW | N_COLUMN => Attributes.Iterate (Node.Attributes, Print'Access); Write (Level, Wiki.Strings.To_WString (Result)); if Node.Children /= null then Level := Level + 1; Lists.Iterate (Node.Children, Dump_Node'Access); Level := Level - 1; end if; return; when N_PREFORMAT => Strings.Append_String (Result, " "); Strings.Append_String (Result, Strings.To_WString (Node.Language)); Strings.Append_String (Result, " "); Strings.Append_String (Result, Node.Preformatted); when others => null; end case; Write (Level, Wiki.Strings.To_WString (Result)); end Dump_Node; begin Dump_Node (Node); end Wiki.Nodes.Dump;
Fix dumping new header nodes
Fix dumping new header nodes
Ada
apache-2.0
stcarrez/ada-wiki,stcarrez/ada-wiki
70d620eaeaf933772b639a319bd6673b24aa3b0d
regtests/ado-sql-tests.adb
regtests/ado-sql-tests.adb
----------------------------------------------------------------------- -- ado-sql-tests -- SQL tests -- Copyright (C) 2022 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Test_Caller; with Util.Strings; package body ADO.SQL.Tests is package Caller is new Util.Test_Caller (Test, "ADO.SQL"); procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is begin Caller.Add_Test (Suite, "Test ADO.SQL.Read_File", Test_Read_File'Access); end Add_Tests; -- ------------------------------ -- Test Read_SQL file and spliting a file in SQL statements. -- ------------------------------ procedure Test_Read_File (T : in out Test) is Count : Natural := 0; procedure Process (SQL : in String) is begin T.Assert_Equals (")", SQL (SQL'Last .. SQL'Last)); if SQL (SQL'First) = 'I' then Util.Tests.Assert_Matches (T, "INSERT .*", SQL, "invalid SQL"); else Util.Tests.Assert_Matches (T, ".*CREATE TABLE.*", SQL, "invalid SQL"); end if; Count := Count + 1; end Process; begin ADO.SQL.Read_File ("regtests/files/read-1.sql", Process'Access); Util.Tests.Assert_Equals (T, 6, Count, "Invalid number of SQL statements"); Count := 0; ADO.SQL.Read_File ("regtests/files/read-2.sql", Process'Access); Util.Tests.Assert_Equals (T, 3, Count, "Invalid number of SQL statements"); end Test_Read_File; end ADO.SQL.Tests;
----------------------------------------------------------------------- -- ado-sql-tests -- SQL tests -- Copyright (C) 2022 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Test_Caller; package body ADO.SQL.Tests is package Caller is new Util.Test_Caller (Test, "ADO.SQL"); procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is begin Caller.Add_Test (Suite, "Test ADO.SQL.Read_File", Test_Read_File'Access); end Add_Tests; -- ------------------------------ -- Test Read_SQL file and spliting a file in SQL statements. -- ------------------------------ procedure Test_Read_File (T : in out Test) is procedure Process (SQL : in String); Count : Natural := 0; procedure Process (SQL : in String) is begin T.Assert_Equals (")", SQL (SQL'Last .. SQL'Last)); if SQL (SQL'First) = 'I' then Util.Tests.Assert_Matches (T, "INSERT .*", SQL, "invalid SQL"); else Util.Tests.Assert_Matches (T, ".*CREATE TABLE.*", SQL, "invalid SQL"); end if; Count := Count + 1; end Process; begin ADO.SQL.Read_File ("regtests/files/read-1.sql", Process'Access); Util.Tests.Assert_Equals (T, 6, Count, "Invalid number of SQL statements"); Count := 0; ADO.SQL.Read_File ("regtests/files/read-2.sql", Process'Access); Util.Tests.Assert_Equals (T, 3, Count, "Invalid number of SQL statements"); end Test_Read_File; end ADO.SQL.Tests;
Fix compilation warning
Fix compilation warning
Ada
apache-2.0
stcarrez/ada-ado
9cf0fd26025d51eff9736ca333eac8eb9dc477b3
src/asf-servlets-files.adb
src/asf-servlets-files.adb
----------------------------------------------------------------------- -- asf.servlets.files -- Static file servlet -- Copyright (C) 2010, 2011, 2013, 2015 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Files; with Util.Strings; with Util.Streams; with Util.Streams.Files; with Ada.Streams; with Ada.Streams.Stream_IO; with Ada.Directories; with ASF.Streams; with ASF.Applications; package body ASF.Servlets.Files is use Ada.Streams; use Ada.Streams.Stream_IO; use Ada.Directories; -- ------------------------------ -- Called by the servlet container to indicate to a servlet that the servlet -- is being placed into service. -- ------------------------------ procedure Initialize (Server : in out File_Servlet; Context : in Servlet_Registry'Class) is Dir : constant String := Context.Get_Init_Parameter (ASF.Applications.VIEW_DIR); Def_Type : constant String := Context.Get_Init_Parameter ("content-type.default"); begin Server.Dir := new String '(Dir); Server.Default_Content_Type := new String '(Def_Type); end Initialize; -- ------------------------------ -- Returns the time the Request object was last modified, in milliseconds since -- midnight January 1, 1970 GMT. If the time is unknown, this method returns -- a negative number (the default). -- -- Servlets that support HTTP GET requests and can quickly determine their -- last modification time should override this method. This makes browser and -- proxy caches work more effectively, reducing the load on server and network -- resources. -- ------------------------------ function Get_Last_Modified (Server : in File_Servlet; Request : in Requests.Request'Class) return Ada.Calendar.Time is pragma Unreferenced (Server, Request); begin return Ada.Calendar.Clock; end Get_Last_Modified; -- ------------------------------ -- Set the content type associated with the given file -- ------------------------------ procedure Set_Content_Type (Server : in File_Servlet; Path : in String; Response : in out Responses.Response'Class) is Pos : constant Natural := Util.Strings.Rindex (Path, '.'); begin if Pos = 0 then Response.Set_Content_Type (Server.Default_Content_Type.all); return; end if; if Path (Pos .. Path'Last) = ".css" then Response.Set_Content_Type ("text/css"); return; end if; if Path (Pos .. Path'Last) = ".js" then Response.Set_Content_Type ("text/javascript"); return; end if; if Path (Pos .. Path'Last) = ".html" then Response.Set_Content_Type ("text/html"); return; end if; if Path (Pos .. Path'Last) = ".txt" then Response.Set_Content_Type ("text/plain"); return; end if; if Path (Pos .. Path'Last) = ".png" then Response.Set_Content_Type ("image/png"); return; end if; if Path (Pos .. Path'Last) = ".jpg" then Response.Set_Content_Type ("image/jpg"); return; end if; Response.Set_Content_Type (Server.Default_Content_Type.all); end Set_Content_Type; -- ------------------------------ -- Called by the server (via the service method) to allow a servlet to handle -- a GET request. -- -- Overriding this method to support a GET request also automatically supports -- an HTTP HEAD request. A HEAD request is a GET request that returns no body -- in the response, only the request header fields. -- -- When overriding this method, read the request data, write the response headers, -- get the response's writer or output stream object, and finally, write the -- response data. It's best to include content type and encoding. -- When using a PrintWriter object to return the response, set the content type -- before accessing the PrintWriter object. -- -- The servlet container must write the headers before committing the response, -- because in HTTP the headers must be sent before the response body. -- -- Where possible, set the Content-Length header (with the -- Response.Set_Content_Length method), to allow the servlet container -- to use a persistent connection to return its response to the client, -- improving performance. The content length is automatically set if the entire -- response fits inside the response buffer. -- -- When using HTTP 1.1 chunked encoding (which means that the response has a -- Transfer-Encoding header), do not set the Content-Length header. -- -- The GET method should be safe, that is, without any side effects for which -- users are held responsible. For example, most form queries have no side effects. -- If a client request is intended to change stored data, the request should use -- some other HTTP method. -- -- The GET method should also be idempotent, meaning that it can be safely repeated. -- Sometimes making a method safe also makes it idempotent. For example, repeating -- queries is both safe and idempotent, but buying a product online or modifying -- data is neither safe nor idempotent. -- -- If the request is incorrectly formatted, Do_Get returns an HTTP "Bad Request" -- ------------------------------ procedure Do_Get (Server : in File_Servlet; Request : in out Requests.Request'Class; Response : in out Responses.Response'Class) is use Util.Files; URI : constant String := Request.Get_Path_Info; Path : constant String := Find_File_Path (Name => URI, Paths => Server.Dir.all); begin if not Ada.Directories.Exists (Path) or else Ada.Directories.Kind (Path) /= Ada.Directories.Ordinary_File then Response.Send_Error (Responses.SC_NOT_FOUND); return; end if; File_Servlet'Class (Server).Set_Content_Type (Path, Response); declare Output : ASF.Streams.Print_Stream := Response.Get_Output_Stream; Input : Util.Streams.Files.File_Stream; begin Input.Open (Name => Path, Mode => In_File); Util.Streams.Copy (From => Input, Into => Output); end; end Do_Get; end ASF.Servlets.Files;
----------------------------------------------------------------------- -- asf.servlets.files -- Static file servlet -- Copyright (C) 2010, 2011, 2013, 2015 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Files; with Util.Strings; with Util.Streams; with Util.Streams.Files; with Ada.Streams; with Ada.Streams.Stream_IO; with Ada.Directories; with ASF.Streams; with ASF.Applications; package body ASF.Servlets.Files is use Ada.Streams; use Ada.Streams.Stream_IO; use Ada.Directories; -- ------------------------------ -- Called by the servlet container to indicate to a servlet that the servlet -- is being placed into service. -- ------------------------------ procedure Initialize (Server : in out File_Servlet; Context : in Servlet_Registry'Class) is Dir : constant String := Context.Get_Init_Parameter (ASF.Applications.VIEW_DIR); Def_Type : constant String := Context.Get_Init_Parameter ("content-type.default"); begin Server.Dir := new String '(Dir); Server.Default_Content_Type := new String '(Def_Type); end Initialize; -- ------------------------------ -- Returns the time the Request object was last modified, in milliseconds since -- midnight January 1, 1970 GMT. If the time is unknown, this method returns -- a negative number (the default). -- -- Servlets that support HTTP GET requests and can quickly determine their -- last modification time should override this method. This makes browser and -- proxy caches work more effectively, reducing the load on server and network -- resources. -- ------------------------------ function Get_Last_Modified (Server : in File_Servlet; Request : in Requests.Request'Class) return Ada.Calendar.Time is pragma Unreferenced (Server, Request); begin return Ada.Calendar.Clock; end Get_Last_Modified; -- ------------------------------ -- Set the content type associated with the given file -- ------------------------------ procedure Set_Content_Type (Server : in File_Servlet; Path : in String; Response : in out Responses.Response'Class) is Pos : constant Natural := Util.Strings.Rindex (Path, '.'); begin if Pos = 0 then Response.Set_Content_Type (Server.Default_Content_Type.all); return; end if; if Path (Pos .. Path'Last) = ".css" then Response.Set_Content_Type ("text/css"); return; end if; if Path (Pos .. Path'Last) = ".js" then Response.Set_Content_Type ("text/javascript"); return; end if; if Path (Pos .. Path'Last) = ".html" then Response.Set_Content_Type ("text/html"); return; end if; if Path (Pos .. Path'Last) = ".txt" then Response.Set_Content_Type ("text/plain"); return; end if; if Path (Pos .. Path'Last) = ".png" then Response.Set_Content_Type ("image/png"); return; end if; if Path (Pos .. Path'Last) = ".jpg" then Response.Set_Content_Type ("image/jpg"); return; end if; Response.Set_Content_Type (Server.Default_Content_Type.all); end Set_Content_Type; -- ------------------------------ -- Called by the server (via the service method) to allow a servlet to handle -- a GET request. -- -- Overriding this method to support a GET request also automatically supports -- an HTTP HEAD request. A HEAD request is a GET request that returns no body -- in the response, only the request header fields. -- -- When overriding this method, read the request data, write the response headers, -- get the response's writer or output stream object, and finally, write the -- response data. It's best to include content type and encoding. -- When using a PrintWriter object to return the response, set the content type -- before accessing the PrintWriter object. -- -- The servlet container must write the headers before committing the response, -- because in HTTP the headers must be sent before the response body. -- -- Where possible, set the Content-Length header (with the -- Response.Set_Content_Length method), to allow the servlet container -- to use a persistent connection to return its response to the client, -- improving performance. The content length is automatically set if the entire -- response fits inside the response buffer. -- -- When using HTTP 1.1 chunked encoding (which means that the response has a -- Transfer-Encoding header), do not set the Content-Length header. -- -- The GET method should be safe, that is, without any side effects for which -- users are held responsible. For example, most form queries have no side effects. -- If a client request is intended to change stored data, the request should use -- some other HTTP method. -- -- The GET method should also be idempotent, meaning that it can be safely repeated. -- Sometimes making a method safe also makes it idempotent. For example, repeating -- queries is both safe and idempotent, but buying a product online or modifying -- data is neither safe nor idempotent. -- -- If the request is incorrectly formatted, Do_Get returns an HTTP "Bad Request" -- ------------------------------ procedure Do_Get (Server : in File_Servlet; Request : in out Requests.Request'Class; Response : in out Responses.Response'Class) is use Util.Files; URI : constant String := Request.Get_Servlet_Path; Path : constant String := Find_File_Path (Name => URI, Paths => Server.Dir.all); begin if not Ada.Directories.Exists (Path) or else Ada.Directories.Kind (Path) /= Ada.Directories.Ordinary_File then Response.Send_Error (Responses.SC_NOT_FOUND); return; end if; File_Servlet'Class (Server).Set_Content_Type (Path, Response); declare Output : ASF.Streams.Print_Stream := Response.Get_Output_Stream; Input : Util.Streams.Files.File_Stream; begin Input.Open (Name => Path, Mode => In_File); Util.Streams.Copy (From => Input, Into => Output); end; end Do_Get; end ASF.Servlets.Files;
Use Get_Servlet_Path instead of Get_Path_Info
Use Get_Servlet_Path instead of Get_Path_Info
Ada
apache-2.0
stcarrez/ada-asf,stcarrez/ada-asf,stcarrez/ada-asf
c169071082bfcec3f05ae37b6c0e0f38f4e8f44f
src/gen-model-packages.ads
src/gen-model-packages.ads
----------------------------------------------------------------------- -- gen-model-packages -- Packages holding model, query representation -- Copyright (C) 2009, 2010, 2011, 2012, 2013, 2016, 2018 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Containers.Hashed_Maps; with Ada.Strings.Unbounded; with Ada.Strings.Unbounded.Hash; with Util.Beans.Objects; with Util.Beans.Objects.Vectors; with Util.Strings.Sets; with Gen.Model.List; with Gen.Model.Mappings; limited with Gen.Model.Enums; limited with Gen.Model.Tables; limited with Gen.Model.Queries; limited with Gen.Model.Beans; package Gen.Model.Packages is use Ada.Strings.Unbounded; -- ------------------------------ -- Model Definition -- ------------------------------ -- The <b>Model_Definition</b> contains the complete model from one or -- several files. It maintains a list of Ada packages that must be generated. type Model_Definition is new Definition with private; type Model_Definition_Access is access all Model_Definition'Class; -- Validate the definition by checking and reporting problems to the logger interface. overriding procedure Validate (Def : in out Model_Definition; Log : in out Util.Log.Logging'Class); -- ------------------------------ -- Package Definition -- ------------------------------ -- The <b>Package_Definition</b> holds the tables, queries and other information -- that must be generated for a given Ada package. type Package_Definition is new Definition with private; type Package_Definition_Access is access all Package_Definition'Class; -- Get the value identified by the name. -- If the name cannot be found, the method should return the Null object. overriding function Get_Value (From : in Package_Definition; Name : in String) return Util.Beans.Objects.Object; -- Prepare the generation of the package: -- o identify the column types which are used -- o build a list of package for the with clauses. overriding procedure Prepare (O : in out Package_Definition); -- Validate the definition by checking and reporting problems to the logger interface. overriding procedure Validate (Def : in out Package_Definition; Log : in out Util.Log.Logging'Class); -- Initialize the package instance overriding procedure Initialize (O : in out Package_Definition); -- Find the type identified by the name. function Find_Type (From : in Package_Definition; Name : in Unbounded_String) return Gen.Model.Mappings.Mapping_Definition_Access; -- Get the model which contains all the package definitions. function Get_Model (From : in Package_Definition) return Model_Definition_Access; -- Returns True if the package is a pre-defined package and must not be generated. function Is_Predefined (From : in Package_Definition) return Boolean; -- Set the package as a pre-defined package. procedure Set_Predefined (From : in out Package_Definition); -- Get the value identified by the name. -- If the name cannot be found, the method should return the Null object. overriding function Get_Value (From : Model_Definition; Name : String) return Util.Beans.Objects.Object; -- Initialize the model definition instance. overriding procedure Initialize (O : in out Model_Definition); -- Returns True if the model contains at least one package. function Has_Packages (O : in Model_Definition) return Boolean; -- Register or find the package knowing its name procedure Register_Package (O : in out Model_Definition; Name : in Unbounded_String; Result : out Package_Definition_Access); -- Register the declaration of the given enum in the model. procedure Register_Enum (O : in out Model_Definition; Enum : access Gen.Model.Enums.Enum_Definition'Class); -- Register the declaration of the given table in the model. procedure Register_Table (O : in out Model_Definition; Table : access Gen.Model.Tables.Table_Definition'Class); -- Register the declaration of the given query in the model. procedure Register_Query (O : in out Model_Definition; Table : access Gen.Model.Queries.Query_File_Definition'Class); -- Register the declaration of the given bean in the model. procedure Register_Bean (O : in out Model_Definition; Bean : access Gen.Model.Beans.Bean_Definition'Class); -- Register a type mapping. The <b>From</b> type describes a type in the XML -- configuration files (hibernate, query, ...) and the <b>To</b> represents the -- corresponding Ada type. procedure Register_Type (O : in out Model_Definition; From : in String; To : in String); -- Find the type identified by the name. function Find_Type (From : in Model_Definition; Name : in Unbounded_String) return Gen.Model.Mappings.Mapping_Definition_Access; -- Set the directory name associated with the model. This directory name allows to -- save and build a model in separate directories for the application, the unit tests -- and others. procedure Set_Dirname (O : in out Model_Definition; Target_Dir : in String; Model_Dir : in String); -- Get the directory name associated with the model. function Get_Dirname (O : in Model_Definition) return String; -- Get the directory name which contains the model. function Get_Model_Directory (O : in Model_Definition) return String; -- Enable the generation of the Ada package given by the name. By default all the Ada -- packages found in the model are generated. When called, this enables the generation -- only for the Ada packages registered here. procedure Enable_Package_Generation (Model : in out Model_Definition; Name : in String); -- Returns True if the generation is enabled for the given package name. function Is_Generation_Enabled (Model : in Model_Definition; Name : in String) return Boolean; -- Iterate over the model tables. procedure Iterate_Tables (Model : in Model_Definition; Process : not null access procedure (Item : in out Tables.Table_Definition)); -- Iterate over the model enums. procedure Iterate_Enums (Model : in Model_Definition; Process : not null access procedure (Item : in out Enums.Enum_Definition)); -- Prepare the generation of the package: -- o identify the column types which are used -- o build a list of package for the with clauses. overriding procedure Prepare (O : in out Model_Definition); package Package_Map is new Ada.Containers.Hashed_Maps (Key_Type => Unbounded_String, Element_Type => Package_Definition_Access, Hash => Ada.Strings.Unbounded.Hash, Equivalent_Keys => "="); subtype Package_Cursor is Package_Map.Cursor; -- Get the first package of the model definition. function First (From : Model_Definition) return Package_Cursor; -- Returns true if the package cursor contains a valid package function Has_Element (Position : Package_Cursor) return Boolean renames Package_Map.Has_Element; -- Returns the package definition. function Element (Position : Package_Cursor) return Package_Definition_Access renames Package_Map.Element; -- Move the iterator to the next package definition. procedure Next (Position : in out Package_Cursor) renames Package_Map.Next; private package Table_List is new Gen.Model.List (T => Definition, T_Access => Definition_Access); -- Returns False if the <tt>Left</tt> table does not depend on <tt>Right</tt>. -- Returns True if the <tt>Left</tt> table depends on the <tt>Right</tt> table. function Dependency_Compare (Left, Right : in Definition_Access) return Boolean; -- Sort the tables on their dependency. procedure Dependency_Sort is new Table_List.Sort_On ("<" => Dependency_Compare); subtype Table_List_Definition is Table_List.List_Definition; subtype Enum_List_Definition is Table_List.List_Definition; type List_Object is new Util.Beans.Basic.List_Bean with record Values : Util.Beans.Objects.Vectors.Vector; Row : Natural; Value_Bean : Util.Beans.Objects.Object; end record; -- Get the number of elements in the list. overriding function Get_Count (From : in List_Object) return Natural; -- Set the current row index. Valid row indexes start at 1. overriding procedure Set_Row_Index (From : in out List_Object; Index : in Natural); -- Get the element at the current row index. overriding function Get_Row (From : in List_Object) return Util.Beans.Objects.Object; -- Get the value identified by the name. -- If the name cannot be found, the method should return the Null object. overriding function Get_Value (From : in List_Object; Name : in String) return Util.Beans.Objects.Object; type Package_Definition is new Definition with record -- Enums defined in the package. Enums : aliased Enum_List_Definition; Enums_Bean : Util.Beans.Objects.Object; -- Hibernate tables Tables : aliased Table_List_Definition; Tables_Bean : Util.Beans.Objects.Object; -- Custom queries Queries : aliased Table_List_Definition; Queries_Bean : Util.Beans.Objects.Object; -- Ada Beans Beans : aliased Table_List_Definition; Beans_Bean : Util.Beans.Objects.Object; -- A list of external packages which are used (used for with clause generation). Used_Spec_Types : aliased List_Object; Used_Spec : Util.Beans.Objects.Object; -- A list of external packages which are used (used for with clause generation). Used_Body_Types : aliased List_Object; Used_Body : Util.Beans.Objects.Object; -- A map of all types defined in this package. Types : Gen.Model.Mappings.Mapping_Maps.Map; -- The base name for the package (ex: gen-model-users) Base_Name : Unbounded_String; -- The global model (used to resolve types from other packages). Model : Model_Definition_Access; -- True if the package uses Ada.Calendar.Time Uses_Calendar_Time : Boolean := False; -- True if the package is a pre-defined package (ie, defined by a UML profile). Is_Predefined : Boolean := False; end record; type Model_Definition is new Definition with record -- List of all enums. Enums : aliased Enum_List_Definition; Enums_Bean : Util.Beans.Objects.Object; -- List of all tables. Tables : aliased Table_List_Definition; Tables_Bean : Util.Beans.Objects.Object; -- List of all queries. Queries : aliased Table_List_Definition; Queries_Bean : Util.Beans.Objects.Object; -- Ada Beans Beans : aliased Table_List_Definition; Beans_Bean : Util.Beans.Objects.Object; -- Map of all packages. Packages : Package_Map.Map; -- Directory associated with the model ('src', 'samples', 'regtests', ...). Dir_Name : Unbounded_String; -- Directory that contains the SQL and model files. DB_Name : Unbounded_String; -- When not empty, a list of packages that must be taken into account for the generation. -- By default all packages and tables defined in the model are generated. Gen_Packages : Util.Strings.Sets.Set; end record; end Gen.Model.Packages;
----------------------------------------------------------------------- -- gen-model-packages -- Packages holding model, query representation -- Copyright (C) 2009 - 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.Containers.Hashed_Maps; with Ada.Strings.Unbounded; with Ada.Strings.Unbounded.Hash; with Util.Beans.Objects; with Util.Beans.Objects.Vectors; with Util.Strings.Sets; with Gen.Model.List; with Gen.Model.Mappings; limited with Gen.Model.Enums; limited with Gen.Model.Tables; limited with Gen.Model.Queries; limited with Gen.Model.Beans; limited with Gen.Model.Stypes; package Gen.Model.Packages is use Ada.Strings.Unbounded; -- ------------------------------ -- Model Definition -- ------------------------------ -- The <b>Model_Definition</b> contains the complete model from one or -- several files. It maintains a list of Ada packages that must be generated. type Model_Definition is new Definition with private; type Model_Definition_Access is access all Model_Definition'Class; -- Validate the definition by checking and reporting problems to the logger interface. overriding procedure Validate (Def : in out Model_Definition; Log : in out Util.Log.Logging'Class); -- ------------------------------ -- Package Definition -- ------------------------------ -- The <b>Package_Definition</b> holds the tables, queries and other information -- that must be generated for a given Ada package. type Package_Definition is new Definition with private; type Package_Definition_Access is access all Package_Definition'Class; -- Get the value identified by the name. -- If the name cannot be found, the method should return the Null object. overriding function Get_Value (From : in Package_Definition; Name : in String) return Util.Beans.Objects.Object; -- Prepare the generation of the package: -- o identify the column types which are used -- o build a list of package for the with clauses. overriding procedure Prepare (O : in out Package_Definition); -- Validate the definition by checking and reporting problems to the logger interface. overriding procedure Validate (Def : in out Package_Definition; Log : in out Util.Log.Logging'Class); -- Initialize the package instance overriding procedure Initialize (O : in out Package_Definition); -- Find the type identified by the name. function Find_Type (From : in Package_Definition; Name : in Unbounded_String) return Gen.Model.Mappings.Mapping_Definition_Access; -- Get the model which contains all the package definitions. function Get_Model (From : in Package_Definition) return Model_Definition_Access; -- Returns True if the package is a pre-defined package and must not be generated. function Is_Predefined (From : in Package_Definition) return Boolean; -- Set the package as a pre-defined package. procedure Set_Predefined (From : in out Package_Definition); -- Get the value identified by the name. -- If the name cannot be found, the method should return the Null object. overriding function Get_Value (From : Model_Definition; Name : String) return Util.Beans.Objects.Object; -- Initialize the model definition instance. overriding procedure Initialize (O : in out Model_Definition); -- Returns True if the model contains at least one package. function Has_Packages (O : in Model_Definition) return Boolean; -- Register or find the package knowing its name procedure Register_Package (O : in out Model_Definition; Name : in Unbounded_String; Result : out Package_Definition_Access); -- Register the declaration of the given enum in the model. procedure Register_Enum (O : in out Model_Definition; Enum : access Gen.Model.Enums.Enum_Definition'Class); -- Register the declaration of the given data type in the model. procedure Register_Stype (O : in out Model_Definition; Stype : access Gen.Model.Stypes.Stype_Definition'Class); -- Register the declaration of the given table in the model. procedure Register_Table (O : in out Model_Definition; Table : access Gen.Model.Tables.Table_Definition'Class); -- Register the declaration of the given query in the model. procedure Register_Query (O : in out Model_Definition; Table : access Gen.Model.Queries.Query_File_Definition'Class); -- Register the declaration of the given bean in the model. procedure Register_Bean (O : in out Model_Definition; Bean : access Gen.Model.Beans.Bean_Definition'Class); -- Register a type mapping. The <b>From</b> type describes a type in the XML -- configuration files (hibernate, query, ...) and the <b>To</b> represents the -- corresponding Ada type. procedure Register_Type (O : in out Model_Definition; From : in String; To : in String); -- Find the type identified by the name. function Find_Type (From : in Model_Definition; Name : in Unbounded_String) return Gen.Model.Mappings.Mapping_Definition_Access; -- Set the directory name associated with the model. This directory name allows to -- save and build a model in separate directories for the application, the unit tests -- and others. procedure Set_Dirname (O : in out Model_Definition; Target_Dir : in String; Model_Dir : in String); -- Get the directory name associated with the model. function Get_Dirname (O : in Model_Definition) return String; -- Get the directory name which contains the model. function Get_Model_Directory (O : in Model_Definition) return String; -- Enable the generation of the Ada package given by the name. By default all the Ada -- packages found in the model are generated. When called, this enables the generation -- only for the Ada packages registered here. procedure Enable_Package_Generation (Model : in out Model_Definition; Name : in String); -- Returns True if the generation is enabled for the given package name. function Is_Generation_Enabled (Model : in Model_Definition; Name : in String) return Boolean; -- Iterate over the model tables. procedure Iterate_Tables (Model : in Model_Definition; Process : not null access procedure (Item : in out Tables.Table_Definition)); -- Iterate over the model enums. procedure Iterate_Enums (Model : in Model_Definition; Process : not null access procedure (Item : in out Enums.Enum_Definition)); -- Prepare the generation of the package: -- o identify the column types which are used -- o build a list of package for the with clauses. overriding procedure Prepare (O : in out Model_Definition); package Package_Map is new Ada.Containers.Hashed_Maps (Key_Type => Unbounded_String, Element_Type => Package_Definition_Access, Hash => Ada.Strings.Unbounded.Hash, Equivalent_Keys => "="); subtype Package_Cursor is Package_Map.Cursor; -- Get the first package of the model definition. function First (From : Model_Definition) return Package_Cursor; -- Returns true if the package cursor contains a valid package function Has_Element (Position : Package_Cursor) return Boolean renames Package_Map.Has_Element; -- Returns the package definition. function Element (Position : Package_Cursor) return Package_Definition_Access renames Package_Map.Element; -- Move the iterator to the next package definition. procedure Next (Position : in out Package_Cursor) renames Package_Map.Next; private package Table_List is new Gen.Model.List (T => Definition, T_Access => Definition_Access); -- Returns False if the <tt>Left</tt> table does not depend on <tt>Right</tt>. -- Returns True if the <tt>Left</tt> table depends on the <tt>Right</tt> table. function Dependency_Compare (Left, Right : in Definition_Access) return Boolean; -- Sort the tables on their dependency. procedure Dependency_Sort is new Table_List.Sort_On ("<" => Dependency_Compare); subtype Table_List_Definition is Table_List.List_Definition; subtype Enum_List_Definition is Table_List.List_Definition; subtype Types_List_Definition is Table_List.List_Definition; subtype Stype_List_Definition is Table_List.List_Definition; type List_Object is new Util.Beans.Basic.List_Bean with record Values : Util.Beans.Objects.Vectors.Vector; Row : Natural; Value_Bean : Util.Beans.Objects.Object; end record; -- Get the number of elements in the list. overriding function Get_Count (From : in List_Object) return Natural; -- Set the current row index. Valid row indexes start at 1. overriding procedure Set_Row_Index (From : in out List_Object; Index : in Natural); -- Get the element at the current row index. overriding function Get_Row (From : in List_Object) return Util.Beans.Objects.Object; -- Get the value identified by the name. -- If the name cannot be found, the method should return the Null object. overriding function Get_Value (From : in List_Object; Name : in String) return Util.Beans.Objects.Object; type Package_Definition is new Definition with record -- Enums defined in the package. Enums : aliased Enum_List_Definition; Enums_Bean : Util.Beans.Objects.Object; -- Simple data types defined in the package. Stypes : aliased Stype_List_Definition; Stypes_Bean : Util.Beans.Objects.Object; -- Hibernate tables Tables : aliased Table_List_Definition; Tables_Bean : Util.Beans.Objects.Object; -- Custom queries Queries : aliased Table_List_Definition; Queries_Bean : Util.Beans.Objects.Object; -- Ada Beans Beans : aliased Table_List_Definition; Beans_Bean : Util.Beans.Objects.Object; -- A list of external packages which are used (used for with clause generation). Used_Spec_Types : aliased List_Object; Used_Spec : Util.Beans.Objects.Object; -- A list of external packages which are used (used for with clause generation). Used_Body_Types : aliased List_Object; Used_Body : Util.Beans.Objects.Object; -- A map of all types defined in this package. Types : Gen.Model.Mappings.Mapping_Maps.Map; -- The base name for the package (ex: gen-model-users) Base_Name : Unbounded_String; -- The global model (used to resolve types from other packages). Model : Model_Definition_Access; -- True if the package uses Ada.Calendar.Time Uses_Calendar_Time : Boolean := False; -- True if the package is a pre-defined package (ie, defined by a UML profile). Is_Predefined : Boolean := False; end record; type Model_Definition is new Definition with record -- List of all enums. Enums : aliased Enum_List_Definition; Enums_Bean : Util.Beans.Objects.Object; -- Simple data types defined in the package. Stypes : aliased Stype_List_Definition; Stypes_Bean : Util.Beans.Objects.Object; -- List of all tables. Tables : aliased Table_List_Definition; Tables_Bean : Util.Beans.Objects.Object; -- List of all queries. Queries : aliased Table_List_Definition; Queries_Bean : Util.Beans.Objects.Object; -- Ada Beans Beans : aliased Table_List_Definition; Beans_Bean : Util.Beans.Objects.Object; -- Map of all packages. Packages : Package_Map.Map; -- Directory associated with the model ('src', 'samples', 'regtests', ...). Dir_Name : Unbounded_String; -- Directory that contains the SQL and model files. DB_Name : Unbounded_String; -- When not empty, a list of packages that must be taken into account for the generation. -- By default all packages and tables defined in the model are generated. Gen_Packages : Util.Strings.Sets.Set; end record; end Gen.Model.Packages;
Add Register_Stype to register and keep the simple types defined by a model
Add Register_Stype to register and keep the simple types defined by a model
Ada
apache-2.0
stcarrez/dynamo,stcarrez/dynamo,stcarrez/dynamo
d432d6a18cacf7f0bc273b7a2aba6edc848cd837
ARM/STMicro/STM32/driver_demos/demo_serial_ports/src/peripherals_blocking.ads
ARM/STMicro/STM32/driver_demos/demo_serial_ports/src/peripherals_blocking.ads
------------------------------------------------------------------------------ -- -- -- Copyright (C) 2015, AdaCore -- -- -- -- Redistribution and use in source and binary forms, with or without -- -- modification, are permitted provided that the following conditions are -- -- met: -- -- 1. Redistributions of source code must retain the above copyright -- -- notice, this list of conditions and the following disclaimer. -- -- 2. Redistributions in binary form must reproduce the above copyright -- -- notice, this list of conditions and the following disclaimer in -- -- the documentation and/or other materials provided with the -- -- distribution. -- -- 3. Neither the name of STMicroelectronics nor the names of its -- -- contributors may be used to endorse or promote products derived -- -- from this software without specific prior written permission. -- -- -- -- THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -- -- "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -- -- LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -- -- A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -- -- HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -- -- SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -- -- LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -- -- DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -- -- THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -- -- (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -- -- OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -- -- -- ------------------------------------------------------------------------------ with STM32F4; use STM32F4; with STM32F4.GPIO; use STM32F4.GPIO; with STM32F4_Discovery; use STM32F4_Discovery; with STM32F4.Reset_Clock_Control; use STM32F4.Reset_Clock_Control; with Serial_IO.Blocking; use Serial_IO.Blocking; use Serial_IO; package Peripherals_Blocking is -- the specific port, pins, and USART selections are arbitrary. Hardware : aliased Peripheral_Descriptor := (Port => GPIO_B'Access, Transceiver => USART_1'Access, Enable_Port_Clock => GPIOB_Clock_Enable'Access, Enable_USART_Clock => USART1_Clock_Enable'Access, Transceiver_AF => GPIO_AF_USART1, Tx_Pin => Pin_6, Rx_Pin => Pin_7); COM : Serial_Port (Hardware'Access); end Peripherals_Blocking;
------------------------------------------------------------------------------ -- -- -- Copyright (C) 2015, AdaCore -- -- -- -- Redistribution and use in source and binary forms, with or without -- -- modification, are permitted provided that the following conditions are -- -- met: -- -- 1. Redistributions of source code must retain the above copyright -- -- notice, this list of conditions and the following disclaimer. -- -- 2. Redistributions in binary form must reproduce the above copyright -- -- notice, this list of conditions and the following disclaimer in -- -- the documentation and/or other materials provided with the -- -- distribution. -- -- 3. Neither the name of STMicroelectronics nor the names of its -- -- contributors may be used to endorse or promote products derived -- -- from this software without specific prior written permission. -- -- -- -- THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -- -- "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -- -- LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -- -- A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -- -- HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -- -- SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -- -- LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -- -- DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -- -- THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -- -- (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -- -- OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -- -- -- ------------------------------------------------------------------------------ with STM32F4_Discovery; use STM32F4_Discovery; with STM32F4; use STM32F4; with STM32F4.GPIO; use STM32F4.GPIO; with STM32F4.RCC; use STM32F4.RCC; with Serial_IO.Blocking; use Serial_IO.Blocking; use Serial_IO; package Peripherals_Blocking is -- the specific port, pins, and USART selections are arbitrary. Hardware : aliased Peripheral_Descriptor := (Port => GPIO_B'Access, Transceiver => USART_1'Access, Enable_Port_Clock => GPIOB_Clock_Enable'Access, Enable_USART_Clock => USART1_Clock_Enable'Access, Transceiver_AF => GPIO_AF_USART1, Tx_Pin => Pin_6, Rx_Pin => Pin_7); COM : Serial_Port (Hardware'Access); end Peripherals_Blocking;
use new name for RCC package
use new name for RCC package
Ada
bsd-3-clause
simonjwright/Ada_Drivers_Library,ellamosi/Ada_BMP_Library,AdaCore/Ada_Drivers_Library,lambourg/Ada_Drivers_Library,AdaCore/Ada_Drivers_Library,Fabien-Chouteau/Ada_Drivers_Library,Fabien-Chouteau/Ada_Drivers_Library,simonjwright/Ada_Drivers_Library
8b74ab3fafded7cd0951830628ba6fdba5332267
src/util-streams-texts.adb
src/util-streams-texts.adb
----------------------------------------------------------------------- -- Util.Streams.Files -- File Stream utilities -- 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.IO_Exceptions; package body Util.Streams.Texts is procedure Initialize (Stream : in out Print_Stream; To : in Output_Stream_Access) is begin Stream.Initialize (Output => To, Input => null, Size => 4096); end Initialize; -- ------------------------------ -- Write an integer on the stream. -- ------------------------------ procedure Write (Stream : in out Print_Stream; Item : in Integer) is S : constant String := Integer'Image (Item); begin if Item > 0 then Stream.Write (S (S'First + 1 .. S'Last)); else Stream.Write (S); end if; end Write; -- ------------------------------ -- Write an integer on the stream. -- ------------------------------ procedure Write (Stream : in out Print_Stream; Item : in Long_Long_Integer) is S : constant String := Long_Long_Integer'Image (Item); begin if Item > 0 then Stream.Write (S (S'First + 1 .. S'Last)); else Stream.Write (S); end if; end Write; -- ------------------------------ -- Write a string on the stream. -- ------------------------------ procedure Write (Stream : in out Print_Stream; Item : in Ada.Strings.Unbounded.Unbounded_String) is begin Stream.Write (Ada.Strings.Unbounded.To_String (Item)); end Write; -- ------------------------------ -- Write a date on the stream. -- ------------------------------ procedure Write (Stream : in out Print_Stream; Item : in Ada.Calendar.Time; Format : in GNAT.Calendar.Time_IO.Picture_String := GNAT.Calendar.Time_IO.ISO_Date) is begin Stream.Write (GNAT.Calendar.Time_IO.Image (Item, Format)); end Write; -- ------------------------------ -- Get the output stream content as a string. -- ------------------------------ function To_String (Stream : in Buffered.Buffered_Stream) return String is use Ada.Streams; Size : constant Natural := Stream.Get_Size; Buffer : constant Streams.Buffered.Buffer_Access := Stream.Get_Buffer; Result : String (1 .. Size); begin for I in Result'Range loop Result (I) := Character'Val (Buffer (Stream_Element_Offset (I))); end loop; return Result; end To_String; -- ------------------------------ -- Write a character on the stream. -- ------------------------------ procedure Write_Char (Stream : in out Buffered.Buffered_Stream'Class; Item : in Character) is begin Stream.Write (Item); end Write_Char; -- ------------------------------ -- Write a character on the stream. -- ------------------------------ procedure Write_Char (Stream : in out Buffered.Buffered_Stream'Class; Item : in Wide_Wide_Character) is begin Stream.Write_Wide (Item); end Write_Char; -- ------------------------------ -- Initialize the reader to read the input from the input stream given in <b>From</b>. -- ------------------------------ procedure Initialize (Stream : in out Reader_Stream; From : in Input_Stream_Access) is begin Stream.Initialize (Output => null, Input => From, Size => 4096); end Initialize; -- ------------------------------ -- Read an input line from the input stream. The line is terminated by ASCII.LF. -- When <b>Strip</b> is set, the line terminators (ASCII.CR, ASCII.LF) are removed. -- ------------------------------ procedure Read_Line (Stream : in out Reader_Stream; Into : out Ada.Strings.Unbounded.Unbounded_String; Strip : in Boolean := False) is C : Character; begin while not Stream.Is_Eof loop Stream.Read (C); if C = ASCII.LF then if not Strip then Ada.Strings.Unbounded.Append (Into, C); end if; return; elsif C /= ASCII.CR or not Strip then Ada.Strings.Unbounded.Append (Into, C); end if; end loop; exception when Ada.IO_Exceptions.Data_Error => return; end Read_Line; end Util.Streams.Texts;
----------------------------------------------------------------------- -- Util.Streams.Files -- File Stream utilities -- Copyright (C) 2010, 2011, 2012, 2016, 2017 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.IO_Exceptions; package body Util.Streams.Texts is procedure Initialize (Stream : in out Print_Stream; To : in Output_Stream_Access) is begin Stream.Initialize (Output => To, Input => null, Size => 4096); end Initialize; -- ------------------------------ -- Write an integer on the stream. -- ------------------------------ procedure Write (Stream : in out Print_Stream; Item : in Integer) is S : constant String := Integer'Image (Item); begin if Item > 0 then Stream.Write (S (S'First + 1 .. S'Last)); else Stream.Write (S); end if; end Write; -- ------------------------------ -- Write an integer on the stream. -- ------------------------------ procedure Write (Stream : in out Print_Stream; Item : in Long_Long_Integer) is S : constant String := Long_Long_Integer'Image (Item); begin if Item > 0 then Stream.Write (S (S'First + 1 .. S'Last)); else Stream.Write (S); end if; end Write; -- ------------------------------ -- Write a string on the stream. -- ------------------------------ procedure Write (Stream : in out Print_Stream; Item : in Ada.Strings.Unbounded.Unbounded_String) is begin Stream.Write (Ada.Strings.Unbounded.To_String (Item)); end Write; -- ------------------------------ -- Write a date on the stream. -- ------------------------------ procedure Write (Stream : in out Print_Stream; Item : in Ada.Calendar.Time; Format : in GNAT.Calendar.Time_IO.Picture_String := GNAT.Calendar.Time_IO.ISO_Date) is begin Stream.Write (GNAT.Calendar.Time_IO.Image (Item, Format)); end Write; -- ------------------------------ -- Get the output stream content as a string. -- ------------------------------ function To_String (Stream : in Buffered.Buffered_Stream'Class) return String is use Ada.Streams; Size : constant Natural := Stream.Get_Size; Buffer : constant Streams.Buffered.Buffer_Access := Stream.Get_Buffer; Result : String (1 .. Size); begin for I in Result'Range loop Result (I) := Character'Val (Buffer (Stream_Element_Offset (I))); end loop; return Result; end To_String; -- ------------------------------ -- Write a character on the stream. -- ------------------------------ procedure Write_Char (Stream : in out Buffered.Buffered_Stream'Class; Item : in Character) is begin Stream.Write (Item); end Write_Char; -- ------------------------------ -- Write a character on the stream. -- ------------------------------ procedure Write_Char (Stream : in out Buffered.Buffered_Stream'Class; Item : in Wide_Wide_Character) is begin Stream.Write_Wide (Item); end Write_Char; -- ------------------------------ -- Initialize the reader to read the input from the input stream given in <b>From</b>. -- ------------------------------ procedure Initialize (Stream : in out Reader_Stream; From : in Input_Stream_Access) is begin Stream.Initialize (Output => null, Input => From, Size => 4096); end Initialize; -- ------------------------------ -- Read an input line from the input stream. The line is terminated by ASCII.LF. -- When <b>Strip</b> is set, the line terminators (ASCII.CR, ASCII.LF) are removed. -- ------------------------------ procedure Read_Line (Stream : in out Reader_Stream; Into : out Ada.Strings.Unbounded.Unbounded_String; Strip : in Boolean := False) is C : Character; begin while not Stream.Is_Eof loop Stream.Read (C); if C = ASCII.LF then if not Strip then Ada.Strings.Unbounded.Append (Into, C); end if; return; elsif C /= ASCII.CR or not Strip then Ada.Strings.Unbounded.Append (Into, C); end if; end loop; exception when Ada.IO_Exceptions.Data_Error => return; end Read_Line; end Util.Streams.Texts;
Change To_String function to accept class wide buffer stream objects
Change To_String function to accept class wide buffer stream objects
Ada
apache-2.0
stcarrez/ada-util,stcarrez/ada-util
79666f60d61e5628c31d05e26956cf10199e357b
src/util-beans-factory.adb
src/util-beans-factory.adb
----------------------------------------------------------------------- -- Util.beans.factory -- Bean Registration and Factory -- Copyright (C) 2009, 2010 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Log.Loggers; package body Util.Beans.Factory is use Util.Log; -- The logger Log : constant Loggers.Logger := Loggers.Create ("EL.Beans.Factory"); -- ------------------------------ -- 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 (Factory : in out Bean_Factory; Name : in String; Definition : in Bean_Definition_Access; Scope : in Scope_Type := REQUEST_SCOPE) is B : constant Simple_Binding_Access := new Simple_Binding '(Def => Definition, Scope => Scope); begin Log.Info ("Register bean '{0}' in scope {1}", Name, Scope_Type'Image (Scope)); Register (Factory, Name, B.all'Access); end Register; -- ------------------------------ -- 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 (Factory : in out Bean_Factory; Name : in String; Bind : in Binding_Access) is begin Log.Info ("Register bean binding '{0}'", Name); Factory.Map.Include (Key => To_Unbounded_String (Name), New_Item => Bind); end Register; -- ------------------------------ -- Register all the definitions from a factory to a main factory. -- ------------------------------ procedure Register (Factory : in out Bean_Factory; From : in Bean_Factory) is Pos : Bean_Maps.Cursor := Bean_Maps.First (From.Map); begin while Bean_Maps.Has_Element (Pos) loop Factory.Map.Include (Key => Bean_Maps.Key (Pos), New_Item => Bean_Maps.Element (Pos)); Bean_Maps.Next (Pos); end loop; end Register; -- ------------------------------ -- Create a bean by using the create operation registered for the name -- ------------------------------ procedure Create (Factory : in Bean_Factory; Name : in Unbounded_String; Result : out Util.Beans.Basic.Readonly_Bean_Access; Definition : out Bean_Definition_Access; Scope : out Scope_Type) is Pos : constant Bean_Maps.Cursor := Factory.Map.Find (Name); begin if Bean_Maps.Has_Element (Pos) then declare B : constant Binding_Access := Bean_Maps.Element (Pos); begin B.Create (Name, Result, Definition, Scope); end; end if; end Create; procedure Create (Factory : in Simple_Binding; Name : in Ada.Strings.Unbounded.Unbounded_String; Result : out Util.Beans.Basic.Readonly_Bean_Access; Definition : out Bean_Definition_Access; Scope : out Scope_Type) is pragma Unreferenced (Name); begin Result := Factory.Def.Create; Definition := Factory.Def; Scope := Factory.Scope; end Create; end Util.Beans.Factory;
----------------------------------------------------------------------- -- Util.beans.factory -- Bean Registration and Factory -- Copyright (C) 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.Log.Loggers; package body Util.Beans.Factory is -- The logger Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("Util.Beans.Factory"); -- ------------------------------ -- 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 (Factory : in out Bean_Factory; Name : in String; Definition : in Bean_Definition_Access; Scope : in Scope_Type := REQUEST_SCOPE) is B : constant Simple_Binding_Access := new Simple_Binding '(Def => Definition, Scope => Scope); begin Log.Info ("Register bean '{0}' in scope {1}", Name, Scope_Type'Image (Scope)); Register (Factory, Name, B.all'Access); end Register; -- ------------------------------ -- 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 (Factory : in out Bean_Factory; Name : in String; Bind : in Binding_Access) is begin Log.Info ("Register bean binding '{0}'", Name); Factory.Map.Include (Key => To_Unbounded_String (Name), New_Item => Bind); end Register; -- ------------------------------ -- Register all the definitions from a factory to a main factory. -- ------------------------------ procedure Register (Factory : in out Bean_Factory; From : in Bean_Factory) is Pos : Bean_Maps.Cursor := Bean_Maps.First (From.Map); begin while Bean_Maps.Has_Element (Pos) loop Factory.Map.Include (Key => Bean_Maps.Key (Pos), New_Item => Bean_Maps.Element (Pos)); Bean_Maps.Next (Pos); end loop; end Register; -- ------------------------------ -- Create a bean by using the create operation registered for the name -- ------------------------------ procedure Create (Factory : in Bean_Factory; Name : in Unbounded_String; Result : out Util.Beans.Basic.Readonly_Bean_Access; Definition : out Bean_Definition_Access; Scope : out Scope_Type) is Pos : constant Bean_Maps.Cursor := Factory.Map.Find (Name); begin if Bean_Maps.Has_Element (Pos) then declare B : constant Binding_Access := Bean_Maps.Element (Pos); begin B.Create (Name, Result, Definition, Scope); end; end if; end Create; procedure Create (Factory : in Simple_Binding; Name : in Ada.Strings.Unbounded.Unbounded_String; Result : out Util.Beans.Basic.Readonly_Bean_Access; Definition : out Bean_Definition_Access; Scope : out Scope_Type) is pragma Unreferenced (Name); begin Result := Factory.Def.Create; Definition := Factory.Def; Scope := Factory.Scope; end Create; end Util.Beans.Factory;
Rename the logger into Util.Beans.Factory to match the package name
Rename the logger into Util.Beans.Factory to match the package name
Ada
apache-2.0
stcarrez/ada-util,stcarrez/ada-util
86eacc8430a6688ddb895ff0fe414763f6fae10f
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); 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; 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;
Declare Test_AES_Stream test
Declare Test_AES_Stream test
Ada
apache-2.0
stcarrez/ada-util,stcarrez/ada-util
944af0793c3eaa70a87b072f0840cf32c4ad2a46
awa/src/awa-events-dispatchers-actions.adb
awa/src/awa-events-dispatchers-actions.adb
----------------------------------------------------------------------- -- awa-events-dispatchers-actions -- Event dispatcher to Ada bean actions -- 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 Ada.Strings.Unbounded; with Ada.Exceptions; with Util.Beans.Objects; with Util.Beans.Basic; with Util.Log.Loggers; with EL.Contexts; with EL.Contexts.TLS; with EL.Variables; with EL.Variables.Default; with ASF.Beans; with ASF.Requests; with ASF.Sessions; with AWA.Events.Action_Method; package body AWA.Events.Dispatchers.Actions is use Ada.Strings.Unbounded; use Util.Log; Log : constant Loggers.Logger := Loggers.Create ("AWA.Events.Dispatchers.Actions"); -- ------------------------------ -- Dispatch the event identified by <b>Event</b>. -- The event actions which are associated with the event are executed synchronously. -- ------------------------------ overriding procedure Dispatch (Manager : in Action_Dispatcher; Event : in Module_Event'Class) is use Util.Beans.Objects; -- Dispatch the event to the event action identified by <b>Action</b>. procedure Dispatch_One (Action : in Event_Action); type Event_Bean is new Util.Beans.Basic.Readonly_Bean with null record; overriding function Get_Value (From : in Event_Bean; Name : in String) return Util.Beans.Objects.Object; -- ------------------------------ -- Get the value identified by the name. -- If the name cannot be found, the method should return the Null object. -- ------------------------------ overriding function Get_Value (From : in Event_Bean; Name : in String) return Util.Beans.Objects.Object is pragma Unreferenced (From); begin return Event.Get_Value (Name); end Get_Value; Variables : aliased EL.Variables.Default.Default_Variable_Mapper; -- ------------------------------ -- Default Resolver -- ------------------------------ type Event_ELResolver is limited new EL.Contexts.ELResolver with record Request : ASF.Requests.Request_Access; Application : AWA.Applications.Application_Access; end record; overriding function Get_Value (Resolver : Event_ELResolver; Context : EL.Contexts.ELContext'Class; Base : access Util.Beans.Basic.Readonly_Bean'Class; Name : Unbounded_String) return Util.Beans.Objects.Object; overriding procedure Set_Value (Resolver : in out Event_ELResolver; Context : in EL.Contexts.ELContext'Class; Base : access Util.Beans.Basic.Bean'Class; Name : in Unbounded_String; Value : in Util.Beans.Objects.Object); -- ------------------------------ -- Get the value associated with a base object and a given property. -- ------------------------------ overriding function Get_Value (Resolver : Event_ELResolver; Context : EL.Contexts.ELContext'Class; Base : access Util.Beans.Basic.Readonly_Bean'Class; Name : Unbounded_String) return Util.Beans.Objects.Object is use Util.Beans.Basic; use EL.Variables; use type ASF.Requests.Request_Access; Result : Object; Bean : Util.Beans.Basic.Readonly_Bean_Access; Scope : ASF.Beans.Scope_Type; Key : constant String := To_String (Name); begin if Base /= null then return Base.Get_Value (Key); end if; if Resolver.Request /= null then Result := Resolver.Request.Get_Attribute (Key); if not Util.Beans.Objects.Is_Null (Result) then return Result; end if; -- If there is a session, look if the attribute is defined there. declare Session : constant ASF.Sessions.Session := Resolver.Request.Get_Session; begin if Session.Is_Valid then Result := Session.Get_Attribute (Key); if not Util.Beans.Objects.Is_Null (Result) then return Result; end if; end if; end; end if; Resolver.Application.Create (Name, Context, Bean, Scope); if Bean = null then return Resolver.Application.Get_Global (Name, Context); end if; Result := To_Object (Bean); if Resolver.Request /= null then Resolver.Request.Set_Attribute (Key, Result); else Variables.Bind (Key, Result); end if; return Result; end Get_Value; -- ------------------------------ -- Set the value associated with a base object and a given property. -- ------------------------------ overriding procedure Set_Value (Resolver : in out Event_ELResolver; Context : in EL.Contexts.ELContext'Class; Base : access Util.Beans.Basic.Bean'Class; Name : in Unbounded_String; Value : in Util.Beans.Objects.Object) is pragma Unreferenced (Context); use type ASF.Requests.Request_Access; Key : constant String := To_String (Name); begin if Base /= null then Base.Set_Value (Name => Key, Value => Value); elsif Resolver.Request /= null then Resolver.Request.Set_Attribute (Name => Key, Value => Value); else Variables.Bind (To_String (Name), Value); end if; end Set_Value; Local_Event : aliased Event_Bean; Resolver : aliased Event_ELResolver; ELContext : aliased EL.Contexts.TLS.TLS_Context; -- ------------------------------ -- Dispatch the event to the event action identified by <b>Action</b>. -- ------------------------------ procedure Dispatch_One (Action : in Event_Action) is use Ada.Exceptions; Method : EL.Expressions.Method_Info; begin Method := Action.Action.Get_Method_Info (Context => ELContext); if Method.Object.all in Util.Beans.Basic.Bean'Class then -- If we have a prepare method and the bean provides a Set_Value method, -- call the preparation method to fill the bean with some values. EL.Beans.Initialize (Util.Beans.Basic.Bean'Class (Method.Object.all), Action.Properties, ELContext); end if; -- Execute the specified method on the bean and give it the event object. AWA.Events.Action_Method.Execute (Method => Method, Param => Event); -- If an exception is raised by the action, do not propagate it: -- o We have to dispatch the event to other actions. -- o The event may be dispatched asynchronously and there is no handler -- that could handle such exception exception when E : others => Log.Error ("Error when executing event action {0}: {1}: {2}", Action.Action.Get_Expression, Exception_Name (E), Exception_Message (E)); end Dispatch_One; Pos : Event_Action_Lists.Cursor := Manager.Actions.First; begin Resolver.Application := Manager.Application; ELContext.Set_Resolver (Resolver'Unchecked_Access); ELContext.Set_Variable_Mapper (Variables'Unchecked_Access); Variables.Bind (Name => "event", Value => To_Object (Local_Event'Unchecked_Access, STATIC)); while Event_Action_Lists.Has_Element (Pos) loop Event_Action_Lists.Query_Element (Pos, Dispatch_One'Access); Event_Action_Lists.Next (Pos); end loop; end Dispatch; -- ------------------------------ -- Add an action invoked when an event is dispatched through this dispatcher. -- When the event queue dispatches the event, the Ada bean identified by the method action -- represented by <b>Action</b> is created and initialized by evaluating and setting the -- parameters defined in <b>Params</b>. The action method is then invoked. -- ------------------------------ overriding procedure Add_Action (Manager : in out Action_Dispatcher; Action : in EL.Expressions.Method_Expression; Params : in EL.Beans.Param_Vectors.Vector) is Item : Event_Action; begin Item.Action := Action; Item.Properties := Params; Manager.Actions.Append (Item); end Add_Action; -- ------------------------------ -- Create a new dispatcher associated with the application. -- ------------------------------ function Create_Dispatcher (Application : in AWA.Applications.Application_Access) return Dispatcher_Access is Result : constant Dispatcher_Access := new Action_Dispatcher '(Dispatcher with Application => Application, others => <>); begin return Result.all'Access; end Create_Dispatcher; end AWA.Events.Dispatchers.Actions;
----------------------------------------------------------------------- -- awa-events-dispatchers-actions -- Event dispatcher to Ada bean actions -- Copyright (C) 2012, 2015, 2017, 2018 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Strings.Unbounded; with Ada.Exceptions; with Util.Beans.Objects; with Util.Beans.Basic; with Util.Log.Loggers; with EL.Contexts; with EL.Contexts.TLS; with EL.Variables; with EL.Variables.Default; with ASF.Beans; with ASF.Requests; with ASF.Sessions; with AWA.Events.Action_Method; package body AWA.Events.Dispatchers.Actions is use Ada.Strings.Unbounded; use Util.Log; Log : constant Loggers.Logger := Loggers.Create ("AWA.Events.Dispatchers.Actions"); -- ------------------------------ -- Dispatch the event identified by <b>Event</b>. -- The event actions which are associated with the event are executed synchronously. -- ------------------------------ overriding procedure Dispatch (Manager : in Action_Dispatcher; Event : in Module_Event'Class) is use Util.Beans.Objects; -- Dispatch the event to the event action identified by <b>Action</b>. procedure Dispatch_One (Action : in Event_Action); type Event_Bean is new Util.Beans.Basic.Readonly_Bean with null record; overriding function Get_Value (From : in Event_Bean; Name : in String) return Util.Beans.Objects.Object; -- ------------------------------ -- Get the value identified by the name. -- If the name cannot be found, the method should return the Null object. -- ------------------------------ overriding function Get_Value (From : in Event_Bean; Name : in String) return Util.Beans.Objects.Object is pragma Unreferenced (From); begin return Event.Get_Value (Name); end Get_Value; Variables : aliased EL.Variables.Default.Default_Variable_Mapper; -- ------------------------------ -- Default Resolver -- ------------------------------ type Event_ELResolver is limited new EL.Contexts.ELResolver with record Request : ASF.Requests.Request_Access; Application : AWA.Applications.Application_Access; end record; overriding function Get_Value (Resolver : Event_ELResolver; Context : EL.Contexts.ELContext'Class; Base : access Util.Beans.Basic.Readonly_Bean'Class; Name : Unbounded_String) return Util.Beans.Objects.Object; overriding procedure Set_Value (Resolver : in out Event_ELResolver; Context : in EL.Contexts.ELContext'Class; Base : access Util.Beans.Basic.Bean'Class; Name : in Unbounded_String; Value : in Util.Beans.Objects.Object); -- ------------------------------ -- Get the value associated with a base object and a given property. -- ------------------------------ overriding function Get_Value (Resolver : Event_ELResolver; Context : EL.Contexts.ELContext'Class; Base : access Util.Beans.Basic.Readonly_Bean'Class; Name : Unbounded_String) return Util.Beans.Objects.Object is use Util.Beans.Basic; use type ASF.Requests.Request_Access; Result : Object; Bean : Util.Beans.Basic.Readonly_Bean_Access; Scope : ASF.Beans.Scope_Type; Key : constant String := To_String (Name); begin if Base /= null then return Base.Get_Value (Key); end if; if Resolver.Request /= null then Result := Resolver.Request.Get_Attribute (Key); if not Util.Beans.Objects.Is_Null (Result) then return Result; end if; -- If there is a session, look if the attribute is defined there. declare Session : constant ASF.Sessions.Session := Resolver.Request.Get_Session; begin if Session.Is_Valid then Result := Session.Get_Attribute (Key); if not Util.Beans.Objects.Is_Null (Result) then return Result; end if; end if; end; end if; Resolver.Application.Create (Name, Context, Bean, Scope); if Bean = null then return Resolver.Application.Get_Global (Name, Context); end if; Result := To_Object (Bean); if Resolver.Request /= null then Resolver.Request.Set_Attribute (Key, Result); else Variables.Bind (Key, Result); end if; return Result; end Get_Value; -- ------------------------------ -- Set the value associated with a base object and a given property. -- ------------------------------ overriding procedure Set_Value (Resolver : in out Event_ELResolver; Context : in EL.Contexts.ELContext'Class; Base : access Util.Beans.Basic.Bean'Class; Name : in Unbounded_String; Value : in Util.Beans.Objects.Object) is pragma Unreferenced (Context); use type ASF.Requests.Request_Access; Key : constant String := To_String (Name); begin if Base /= null then Base.Set_Value (Name => Key, Value => Value); elsif Resolver.Request /= null then Resolver.Request.Set_Attribute (Name => Key, Value => Value); else Variables.Bind (To_String (Name), Value); end if; end Set_Value; Local_Event : aliased Event_Bean; Resolver : aliased Event_ELResolver; ELContext : aliased EL.Contexts.TLS.TLS_Context; -- ------------------------------ -- Dispatch the event to the event action identified by <b>Action</b>. -- ------------------------------ procedure Dispatch_One (Action : in Event_Action) is use Ada.Exceptions; Method : EL.Expressions.Method_Info; begin Method := Action.Action.Get_Method_Info (Context => ELContext); if Method.Object.all in Util.Beans.Basic.Bean'Class then -- If we have a prepare method and the bean provides a Set_Value method, -- call the preparation method to fill the bean with some values. EL.Beans.Initialize (Util.Beans.Basic.Bean'Class (Method.Object.all), Action.Properties, ELContext); end if; -- Execute the specified method on the bean and give it the event object. AWA.Events.Action_Method.Execute (Method => Method, Param => Event); -- If an exception is raised by the action, do not propagate it: -- o We have to dispatch the event to other actions. -- o The event may be dispatched asynchronously and there is no handler -- that could handle such exception exception when E : others => Log.Error ("Error when executing event action {0}: {1}: {2}", Action.Action.Get_Expression, Exception_Name (E), Exception_Message (E)); end Dispatch_One; Pos : Event_Action_Lists.Cursor := Manager.Actions.First; begin Resolver.Application := Manager.Application; ELContext.Set_Resolver (Resolver'Unchecked_Access); ELContext.Set_Variable_Mapper (Variables'Unchecked_Access); Variables.Bind (Name => "event", Value => To_Object (Local_Event'Unchecked_Access, STATIC)); while Event_Action_Lists.Has_Element (Pos) loop Event_Action_Lists.Query_Element (Pos, Dispatch_One'Access); Event_Action_Lists.Next (Pos); end loop; end Dispatch; -- ------------------------------ -- Add an action invoked when an event is dispatched through this dispatcher. -- When the event queue dispatches the event, the Ada bean identified by the method action -- represented by <b>Action</b> is created and initialized by evaluating and setting the -- parameters defined in <b>Params</b>. The action method is then invoked. -- ------------------------------ overriding procedure Add_Action (Manager : in out Action_Dispatcher; Action : in EL.Expressions.Method_Expression; Params : in EL.Beans.Param_Vectors.Vector) is Item : Event_Action; begin Item.Action := Action; Item.Properties := Params; Manager.Actions.Append (Item); end Add_Action; -- ------------------------------ -- Create a new dispatcher associated with the application. -- ------------------------------ function Create_Dispatcher (Application : in AWA.Applications.Application_Access) return Dispatcher_Access is Result : constant Dispatcher_Access := new Action_Dispatcher '(Dispatcher with Application => Application, others => <>); begin return Result.all'Access; end Create_Dispatcher; end AWA.Events.Dispatchers.Actions;
Remove unused use clause to fix compilation warning
Remove unused use clause to fix compilation warning
Ada
apache-2.0
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
4c377d5fdc2d0321ac328952456b54e0f0c477c6
src/security-auth-oauth.adb
src/security-auth-oauth.adb
----------------------------------------------------------------------- -- security-auth-oauth -- OAuth based authentication -- Copyright (C) 2013 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Log.Loggers; with Security.OAuth.Clients; package body Security.Auth.OAuth is Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("Security.Auth.OAuth"); -- ------------------------------ -- OAuth Manager -- ------------------------------ -- The <b>Manager</b> provides the core operations for the OAuth authorization process. -- Initialize the authentication realm. overriding procedure Initialize (Realm : in out Manager; Params : in Parameters'Class; Provider : in String := PROVIDER_OPENID) is begin Realm.App.Set_Application_Identifier (Params.Get_Parameter (Provider & ".client_id")); Realm.App.Set_Application_Secret (Params.Get_Parameter (Provider & ".secret")); Realm.App.Set_Application_Callback (Params.Get_Parameter (Provider & ".callback_url")); Realm.App.Set_Provider_URI (Params.Get_Parameter (Provider & ".request_url")); Realm.Realm := To_Unbounded_String (Params.Get_Parameter (Provider & ".realm")); Realm.Scope := To_Unbounded_String (Params.Get_Parameter (Provider & ".scope")); end Initialize; -- Discover the OpenID provider that must be used to authenticate the user. -- The <b>Name</b> can be an URL or an alias that identifies the provider. -- A cached OpenID provider can be returned. -- Read the XRDS document from the URI and initialize the OpenID provider end point. -- (See OpenID Section 7.3 Discovery) overriding procedure Discover (Realm : in out Manager; Name : in String; Result : out End_Point) is begin Result.URL := To_Unbounded_String (Name); end Discover; -- Associate the application (relying party) with the OpenID provider. -- The association can be cached. -- (See OpenID Section 8 Establishing Associations) overriding procedure Associate (Realm : in out Manager; OP : in End_Point; Result : out Association) is begin null; end Associate; overriding function Get_Authentication_URL (Realm : in Manager; OP : in End_Point; Assoc : in Association) return String is Result : Unbounded_String := OP.URL; State : constant String := Realm.App.Get_State (To_String (Assoc.Assoc_Handle)); Params : constant String := Realm.App.Get_Auth_Params (State, To_String (Realm.Scope)); begin if Index (Result, "?") > 0 then Append (Result, "&"); else Append (Result, "?"); end if; Append (Result, Params); Log.Debug ("Params = {0}", Params); return To_String (Result); end Get_Authentication_URL; -- Verify the authentication result overriding procedure Verify (Realm : in out Manager; Assoc : in Association; Request : in Parameters'Class; Result : out Authentication) is State : constant String := Request.Get_Parameter (Security.OAuth.State); Code : constant String := Request.Get_Parameter (Security.OAuth.Code); Error : constant String := Request.Get_Parameter (Security.OAuth.Error_Description); begin if Error'Length /= 0 then Set_Result (Result, CANCEL, "Authentication refused: " & Error); return; end if; -- First, verify that the state parameter matches our internal state. if not Realm.App.Is_Valid_State (To_String (Assoc.Assoc_Handle), State) then Set_Result (Result, INVALID_SIGNATURE, "invalid OAuth state parameter"); return; end if; -- Get the access token from the authorization code. declare use type Security.OAuth.Clients.Access_Token_Access; Acc : constant Security.OAuth.Clients.Access_Token_Access := Realm.App.Request_Access_Token (Code); begin if Acc = null then Set_Result (Result, INVALID_SIGNATURE, "cannot change the code to an access_token"); return; end if; -- Last step, verify the access token and get the user identity. Manager'Class (Realm).Verify_Access_Token (Assoc, Request, Acc, Result); end; end Verify; end Security.Auth.OAuth;
----------------------------------------------------------------------- -- security-auth-oauth -- OAuth based authentication -- Copyright (C) 2013 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Log.Loggers; with Security.OAuth.Clients; package body Security.Auth.OAuth is Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("Security.Auth.OAuth"); -- ------------------------------ -- OAuth Manager -- ------------------------------ -- The <b>Manager</b> provides the core operations for the OAuth authorization process. -- ------------------------------ -- Initialize the authentication realm. -- ------------------------------ overriding procedure Initialize (Realm : in out Manager; Params : in Parameters'Class; Provider : in String := PROVIDER_OPENID) is begin Realm.App.Set_Application_Identifier (Params.Get_Parameter (Provider & ".client_id")); Realm.App.Set_Application_Secret (Params.Get_Parameter (Provider & ".secret")); Realm.App.Set_Application_Callback (Params.Get_Parameter (Provider & ".callback_url")); Realm.App.Set_Provider_URI (Params.Get_Parameter (Provider & ".request_url")); Realm.Realm := To_Unbounded_String (Params.Get_Parameter (Provider & ".realm")); Realm.Scope := To_Unbounded_String (Params.Get_Parameter (Provider & ".scope")); end Initialize; -- ------------------------------ -- Discover the OpenID provider that must be used to authenticate the user. -- The <b>Name</b> can be an URL or an alias that identifies the provider. -- A cached OpenID provider can be returned. -- Read the XRDS document from the URI and initialize the OpenID provider end point. -- (See OpenID Section 7.3 Discovery) -- ------------------------------ overriding procedure Discover (Realm : in out Manager; Name : in String; Result : out End_Point) is begin Result.URL := To_Unbounded_String (Name); end Discover; -- ------------------------------ -- Associate the application (relying party) with the OpenID provider. -- The association can be cached. -- (See OpenID Section 8 Establishing Associations) -- ------------------------------ overriding procedure Associate (Realm : in out Manager; OP : in End_Point; Result : out Association) is begin null; end Associate; -- ------------------------------ -- Get the authentication URL to which the user must be redirected for authentication -- by the authentication server. -- ------------------------------ overriding function Get_Authentication_URL (Realm : in Manager; OP : in End_Point; Assoc : in Association) return String is Result : Unbounded_String := OP.URL; State : constant String := Realm.App.Get_State (To_String (Assoc.Assoc_Handle)); Params : constant String := Realm.App.Get_Auth_Params (State, To_String (Realm.Scope)); begin if Index (Result, "?") > 0 then Append (Result, "&"); else Append (Result, "?"); end if; Append (Result, Params); Log.Debug ("Params = {0}", Params); return To_String (Result); end Get_Authentication_URL; -- ------------------------------ -- Verify the authentication result -- ------------------------------ overriding procedure Verify (Realm : in out Manager; Assoc : in Association; Request : in Parameters'Class; Result : out Authentication) is State : constant String := Request.Get_Parameter (Security.OAuth.State); Code : constant String := Request.Get_Parameter (Security.OAuth.Code); Error : constant String := Request.Get_Parameter (Security.OAuth.Error_Description); begin if Error'Length /= 0 then Set_Result (Result, CANCEL, "Authentication refused: " & Error); return; end if; -- First, verify that the state parameter matches our internal state. if not Realm.App.Is_Valid_State (To_String (Assoc.Assoc_Handle), State) then Set_Result (Result, INVALID_SIGNATURE, "invalid OAuth state parameter"); return; end if; -- Get the access token from the authorization code. declare use type Security.OAuth.Clients.Access_Token_Access; Acc : constant Security.OAuth.Clients.Access_Token_Access := Realm.App.Request_Access_Token (Code); begin if Acc = null then Set_Result (Result, INVALID_SIGNATURE, "cannot change the code to an access_token"); return; end if; -- Last step, verify the access token and get the user identity. Manager'Class (Realm).Verify_Access_Token (Assoc, Request, Acc, Result); end; end Verify; end Security.Auth.OAuth;
Add some comments
Add some comments
Ada
apache-2.0
stcarrez/ada-security
d89106a9c902980f47224dbf1291f1b9b2eb045b
awa/src/awa-commands.ads
awa/src/awa-commands.ads
----------------------------------------------------------------------- -- awa-commands -- AWA commands for server or admin tool -- Copyright (C) 2019, 2020 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Finalization; with Util.Commands; with AWA.Applications; with Ada.Exceptions; private with Keystore.Passwords; private with Keystore.Passwords.GPG; private with Util.Commands.Consoles.Text; private with ASF.Applications; private with AWA.Applications.Factory; private with Keystore.Properties; private with Keystore.Files; private with Keystore.Passwords.Keys; private with GNAT.Command_Line; private with GNAT.Strings; package AWA.Commands is Error : exception; FILL_CONFIG : constant String := "fill-mode"; GPG_CRYPT_CONFIG : constant String := "gpg-encrypt"; GPG_DECRYPT_CONFIG : constant String := "gpg-decrypt"; GPG_LIST_CONFIG : constant String := "gpg-list-keys"; subtype Argument_List is Util.Commands.Argument_List; type Context_Type is limited new Ada.Finalization.Limited_Controlled with private; overriding procedure Initialize (Context : in out Context_Type); overriding procedure Finalize (Context : in out Context_Type); -- Returns True if a keystore is used by the configuration and must be unlocked. function Use_Keystore (Context : in Context_Type) return Boolean; -- Open the keystore file using the password password. procedure Open_Keystore (Context : in out Context_Type); -- Get the keystore file path. function Get_Keystore_Path (Context : in out Context_Type) return String; -- Configure the application by loading its configuration file and merging it with -- the keystore file if there is one. procedure Configure (Application : in out AWA.Applications.Application'Class; Name : in String; Context : in out Context_Type); procedure Print (Context : in out Context_Type; Ex : in Ada.Exceptions.Exception_Occurrence); private function "-" (Message : in String) return String is (Message); procedure Load_Configuration (Context : in out Context_Type; Path : in String); package GC renames GNAT.Command_Line; type Field_Number is range 1 .. 256; type Notice_Type is (N_USAGE, N_INFO, N_ERROR); package Consoles is new Util.Commands.Consoles (Field_Type => Field_Number, Notice_Type => Notice_Type); package Text_Consoles is new Consoles.Text; subtype Justify_Type is Consoles.Justify_Type; type Context_Type is limited new Ada.Finalization.Limited_Controlled with record Console : Text_Consoles.Console_Type; Wallet : aliased Keystore.Files.Wallet_File; Info : Keystore.Wallet_Info; Config : Keystore.Wallet_Config := Keystore.Secure_Config; Secure_Config : Keystore.Properties.Manager; App_Config : ASF.Applications.Config; File_Config : ASF.Applications.Config; Factory : AWA.Applications.Factory.Application_Factory; Provider : Keystore.Passwords.Provider_Access; Key_Provider : Keystore.Passwords.Keys.Key_Provider_Access; Slot : Keystore.Key_Slot; Version : aliased Boolean := False; Verbose : aliased Boolean := False; Debug : aliased Boolean := False; Dump : aliased Boolean := False; Zero : aliased Boolean := False; Config_File : aliased GNAT.Strings.String_Access; Wallet_File : aliased GNAT.Strings.String_Access; Data_Path : aliased GNAT.Strings.String_Access; Wallet_Key_File : aliased GNAT.Strings.String_Access; Password_File : aliased GNAT.Strings.String_Access; Password_Env : aliased GNAT.Strings.String_Access; Unsafe_Password : aliased GNAT.Strings.String_Access; Password_Socket : aliased GNAT.Strings.String_Access; Password_Command : aliased GNAT.Strings.String_Access; Password_Askpass : aliased Boolean := False; No_Password_Opt : Boolean := False; Command_Config : GC.Command_Line_Configuration; First_Arg : Positive := 1; GPG : Keystore.Passwords.GPG.Context_Type; end record; procedure Setup_Password_Provider (Context : in out Context_Type); procedure Setup_Key_Provider (Context : in out Context_Type); -- Setup the command before parsing the arguments and executing it. procedure Setup_Command (Config : in out GC.Command_Line_Configuration; Context : in out Context_Type); function Sys_Daemon (No_Chdir : in Integer; No_Close : in Integer) return Integer with Import => True, Convention => C, Link_Name => "daemon"; pragma Weak_External (Sys_Daemon); end AWA.Commands;
----------------------------------------------------------------------- -- awa-commands -- AWA commands for server or admin tool -- Copyright (C) 2019, 2020 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Finalization; with Util.Commands; with AWA.Applications; with Ada.Exceptions; private with Keystore.Passwords; private with Keystore.Passwords.GPG; private with Util.Commands.Consoles.Text; private with ASF.Applications; private with AWA.Applications.Factory; private with Keystore.Properties; private with Keystore.Files; private with Keystore.Passwords.Keys; private with GNAT.Command_Line; private with GNAT.Strings; package AWA.Commands is Error : exception; FILL_CONFIG : constant String := "fill-mode"; GPG_CRYPT_CONFIG : constant String := "gpg-encrypt"; GPG_DECRYPT_CONFIG : constant String := "gpg-decrypt"; GPG_LIST_CONFIG : constant String := "gpg-list-keys"; subtype Argument_List is Util.Commands.Argument_List; type Context_Type is limited new Ada.Finalization.Limited_Controlled with private; overriding procedure Initialize (Context : in out Context_Type); overriding procedure Finalize (Context : in out Context_Type); -- Returns True if a keystore is used by the configuration and must be unlocked. function Use_Keystore (Context : in Context_Type) return Boolean; -- Open the keystore file using the password password. procedure Open_Keystore (Context : in out Context_Type); -- Get the keystore file path. function Get_Keystore_Path (Context : in out Context_Type) return String; -- Configure the application by loading its configuration file and merging it with -- the keystore file if there is one. procedure Configure (Application : in out AWA.Applications.Application'Class; Name : in String; Context : in out Context_Type); procedure Print (Context : in out Context_Type; Ex : in Ada.Exceptions.Exception_Occurrence); -- Configure the logs. procedure Configure_Logs (Root : in String; Debug : in Boolean; Dump : in Boolean; Verbose : in Boolean); private function "-" (Message : in String) return String is (Message); procedure Load_Configuration (Context : in out Context_Type; Path : in String); package GC renames GNAT.Command_Line; type Field_Number is range 1 .. 256; type Notice_Type is (N_USAGE, N_INFO, N_ERROR); package Consoles is new Util.Commands.Consoles (Field_Type => Field_Number, Notice_Type => Notice_Type); package Text_Consoles is new Consoles.Text; subtype Justify_Type is Consoles.Justify_Type; type Context_Type is limited new Ada.Finalization.Limited_Controlled with record Console : Text_Consoles.Console_Type; Wallet : aliased Keystore.Files.Wallet_File; Info : Keystore.Wallet_Info; Config : Keystore.Wallet_Config := Keystore.Secure_Config; Secure_Config : Keystore.Properties.Manager; App_Config : ASF.Applications.Config; File_Config : ASF.Applications.Config; Factory : AWA.Applications.Factory.Application_Factory; Provider : Keystore.Passwords.Provider_Access; Key_Provider : Keystore.Passwords.Keys.Key_Provider_Access; Slot : Keystore.Key_Slot; Version : aliased Boolean := False; Verbose : aliased Boolean := False; Debug : aliased Boolean := False; Dump : aliased Boolean := False; Zero : aliased Boolean := False; Config_File : aliased GNAT.Strings.String_Access; Wallet_File : aliased GNAT.Strings.String_Access; Data_Path : aliased GNAT.Strings.String_Access; Wallet_Key_File : aliased GNAT.Strings.String_Access; Password_File : aliased GNAT.Strings.String_Access; Password_Env : aliased GNAT.Strings.String_Access; Unsafe_Password : aliased GNAT.Strings.String_Access; Password_Socket : aliased GNAT.Strings.String_Access; Password_Command : aliased GNAT.Strings.String_Access; Password_Askpass : aliased Boolean := False; No_Password_Opt : Boolean := False; Command_Config : GC.Command_Line_Configuration; First_Arg : Positive := 1; GPG : Keystore.Passwords.GPG.Context_Type; end record; procedure Setup_Password_Provider (Context : in out Context_Type); procedure Setup_Key_Provider (Context : in out Context_Type); -- Setup the command before parsing the arguments and executing it. procedure Setup_Command (Config : in out GC.Command_Line_Configuration; Context : in out Context_Type); function Sys_Daemon (No_Chdir : in Integer; No_Close : in Integer) return Integer with Import => True, Convention => C, Link_Name => "daemon"; pragma Weak_External (Sys_Daemon); end AWA.Commands;
Add Configure_Logs procedure
Add Configure_Logs procedure
Ada
apache-2.0
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
8f215af2d888dc67f3702f7ddc2422570a962854
awa/plugins/awa-blogs/src/awa-blogs-beans.ads
awa/plugins/awa-blogs/src/awa-blogs-beans.ads
----------------------------------------------------------------------- -- awa-blogs-beans -- Beans for blog module -- Copyright (C) 2011, 2012, 2013, 2014, 2015, 2016, 2017 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Strings.Unbounded; with Util.Beans.Basic; with Util.Beans.Objects; with ADO; with ADO.Objects; with AWA.Blogs.Modules; with AWA.Blogs.Models; with AWA.Tags.Beans; with AWA.Counters.Beans; with AWA.Events; with ASF.Rest.Definition; -- == Blog Beans == -- Several bean types are provided to represent and manage the blogs and their posts. -- The blog module registers the bean constructors when it is initialized. -- To use them, one must declare a bean definition in the application XML configuration. package AWA.Blogs.Beans is -- Attributes exposed by <b>Post_Bean</b> BLOG_ID_ATTR : constant String := "blogId"; POST_ID_ATTR : constant String := "id"; POST_UID_ATTR : constant String := "uid"; POST_TITLE_ATTR : constant String := "title"; POST_TEXT_ATTR : constant String := "text"; POST_URI_ATTR : constant String := "uri"; POST_STATUS_ATTR : constant String := "status"; POST_USERNAME_ATTR : constant String := "username"; POST_TAG_ATTR : constant String := "tags"; POST_ALLOW_COMMENTS_ATTR : constant String := "allow_comments"; COUNTER_ATTR : constant String := "counter"; -- ------------------------------ -- Blog Bean -- ------------------------------ -- The <b>Blog_Bean</b> holds the information about the current blog. -- It allows to create the blog as well as update its primary title. type Blog_Bean is new AWA.Blogs.Models.Blog_Bean with record Module : AWA.Blogs.Modules.Blog_Module_Access := null; end record; type Blog_Bean_Access is access all Blog_Bean'Class; -- Get the value identified by the name. overriding function Get_Value (From : in Blog_Bean; Name : in String) return Util.Beans.Objects.Object; -- Set the value identified by the name. overriding procedure Set_Value (From : in out Blog_Bean; Name : in String; Value : in Util.Beans.Objects.Object); -- Create a new blog. overriding procedure Create (Bean : in out Blog_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String); -- Load the blog information. overriding procedure Load (Bean : in out Blog_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String); -- Handle an event to create the blog entry automatically. overriding procedure Create_Default (Bean : in out Blog_Bean; Event : in AWA.Events.Module_Event'Class); -- Create the Blog_Bean bean instance. function Create_Blog_Bean (Module : in AWA.Blogs.Modules.Blog_Module_Access) return Util.Beans.Basic.Readonly_Bean_Access; -- ------------------------------ -- Post Bean -- ------------------------------ -- The <b>Post_Bean</b> is used to create or update a post associated with a blog. type Post_Bean is new AWA.Blogs.Models.Post_Bean with record Module : AWA.Blogs.Modules.Blog_Module_Access := null; Blog_Id : ADO.Identifier := ADO.NO_IDENTIFIER; -- List of tags associated with the post. Tags : aliased AWA.Tags.Beans.Tag_List_Bean; Tags_Bean : Util.Beans.Basic.Readonly_Bean_Access; -- The read post counter associated with the post. Counter : aliased AWA.Counters.Beans.Counter_Bean (Of_Type => ADO.Objects.KEY_INTEGER, Of_Class => Models.POST_TABLE); Counter_Bean : Util.Beans.Basic.Readonly_Bean_Access; end record; type Post_Bean_Access is access all Post_Bean'Class; -- Get the value identified by the name. overriding function Get_Value (From : in Post_Bean; Name : in String) return Util.Beans.Objects.Object; -- Set the value identified by the name. overriding procedure Set_Value (From : in out Post_Bean; Name : in String; Value : in Util.Beans.Objects.Object); -- Load the post. procedure Load_Post (Post : in out Post_Bean; Id : in ADO.Identifier); -- Create or save the post. overriding procedure Save (Bean : in out Post_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String); -- Delete a post. overriding procedure Delete (Bean : in out Post_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String); -- Load the post from the URI for the public display. overriding procedure Load (Bean : in out Post_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String); -- Load the post from the URI for the administrator. overriding procedure Load_Admin (Bean : in out Post_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String); -- Load the post from the URI either with visible comments or with all comments. procedure Load (Bean : in out Post_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String; Publish_Only : in Boolean); -- Create the Post_Bean bean instance. function Create_Post_Bean (Module : in AWA.Blogs.Modules.Blog_Module_Access) return Util.Beans.Basic.Readonly_Bean_Access; procedure Create (Bean : in out Post_Bean; Req : in out ASF.Rest.Request'Class; Reply : in out ASF.Rest.Response'Class); procedure Update (Bean : in out Post_Bean; Req : in out ASF.Rest.Request'Class; Reply : in out ASF.Rest.Response'Class); package Post_API is new ASF.Rest.Definition (Object_Type => Post_Bean, URI => "/blogs/:blog_id/posts"); -- -- package API_Post_Create is -- new Post_API.Definition (Create'Access, ASF.Rest.POST, ""); -- -- package API_Post_Update is -- new Post_API.Definition (Update'Access, ASF.Rest.PUT, ":id"); -- ------------------------------ -- Post List Bean -- ------------------------------ -- The <b>Post_List_Bean</b> gives a list of visible posts to be displayed to users. -- The list can be filtered by a given tag. The list pagination is supported. type Post_List_Bean is new AWA.Blogs.Models.Post_List_Bean with record Posts : aliased AWA.Blogs.Models.Post_Info_List_Bean; Service : Modules.Blog_Module_Access := null; Tags : AWA.Tags.Beans.Entity_Tag_Map; Posts_Bean : AWA.Blogs.Models.Post_Info_List_Bean_Access; -- The read post counter associated with the post. Counter : aliased AWA.Counters.Beans.Counter_Bean (Of_Type => ADO.Objects.KEY_INTEGER, Of_Class => Models.POST_TABLE); Counter_Bean : AWA.Counters.Beans.Counter_Bean_Access; end record; type Post_List_Bean_Access is access all Post_List_Bean'Class; -- Get the value identified by the name. overriding function Get_Value (From : in Post_List_Bean; Name : in String) return Util.Beans.Objects.Object; -- Set the value identified by the name. overriding procedure Set_Value (From : in out Post_List_Bean; Name : in String; Value : in Util.Beans.Objects.Object); overriding procedure Load (From : in out Post_List_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String); -- Load the list of posts. If a tag was set, filter the list of posts with the tag. procedure Load_List (Into : in out Post_List_Bean); -- Create the Post_List_Bean bean instance. function Create_Post_List_Bean (Module : in AWA.Blogs.Modules.Blog_Module_Access) return Util.Beans.Basic.Readonly_Bean_Access; -- Get a select item list which contains a list of post status. function Create_Status_List (Module : in AWA.Blogs.Modules.Blog_Module_Access) return Util.Beans.Basic.Readonly_Bean_Access; type Init_Flag is (INIT_BLOG_LIST, INIT_POST_LIST, INIT_COMMENT_LIST); type Init_Map is array (Init_Flag) of Boolean; -- ------------------------------ -- Admin List Bean -- ------------------------------ -- The <b>Blog_Admin_Bean</b> is used for the administration of a blog. It gives the -- list of posts that are created, published or not. type Blog_Admin_Bean is new Util.Beans.Basic.Bean with record Module : AWA.Blogs.Modules.Blog_Module_Access := null; -- The blog identifier. Blog_Id : ADO.Identifier := ADO.NO_IDENTIFIER; -- List of blogs. Blog_List : aliased AWA.Blogs.Models.Blog_Info_List_Bean; Blog_List_Bean : AWA.Blogs.Models.Blog_Info_List_Bean_Access; -- List of posts. Post_List : aliased AWA.Blogs.Models.Admin_Post_Info_List_Bean; Post_List_Bean : AWA.Blogs.Models.Admin_Post_Info_List_Bean_Access; -- List of comments. Comment_List : aliased AWA.Blogs.Models.Comment_Info_List_Bean; Comment_List_Bean : AWA.Blogs.Models.Comment_Info_List_Bean_Access; -- Initialization flags. Init_Flags : aliased Init_Map := (others => False); Flags : access Init_Map; end record; type Blog_Admin_Bean_Access is access all Blog_Admin_Bean; -- Get the blog identifier. function Get_Blog_Id (List : in Blog_Admin_Bean) return ADO.Identifier; -- Load the posts associated with the current blog. procedure Load_Posts (List : in Blog_Admin_Bean); -- Load the comments associated with the current blog. procedure Load_Comments (List : in Blog_Admin_Bean); overriding function Get_Value (List : in Blog_Admin_Bean; Name : in String) return Util.Beans.Objects.Object; -- Set the value identified by the name. overriding procedure Set_Value (From : in out Blog_Admin_Bean; Name : in String; Value : in Util.Beans.Objects.Object); -- Load the list of blogs. procedure Load_Blogs (List : in Blog_Admin_Bean); -- Create the Blog_Admin_Bean bean instance. function Create_Blog_Admin_Bean (Module : in AWA.Blogs.Modules.Blog_Module_Access) return Util.Beans.Basic.Readonly_Bean_Access; -- ------------------------------ -- Blog Statistics Bean -- ------------------------------ -- The <b>Blog_Stat_Bean</b> is used to report various statistics about the blog or some post. type Blog_Stat_Bean is new AWA.Blogs.Models.Stat_List_Bean with record Module : AWA.Blogs.Modules.Blog_Module_Access := null; Stats : aliased AWA.Blogs.Models.Month_Stat_Info_List_Bean; Stats_Bean : AWA.Blogs.Models.Month_Stat_Info_List_Bean_Access; end record; type Blog_Stat_Bean_Access is access all Blog_Stat_Bean; overriding function Get_Value (List : in Blog_Stat_Bean; Name : in String) return Util.Beans.Objects.Object; -- Set the value identified by the name. overriding procedure Set_Value (From : in out Blog_Stat_Bean; Name : in String; Value : in Util.Beans.Objects.Object); -- Load the statistics information. overriding procedure Load (List : in out Blog_Stat_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String); -- Create the Blog_Stat_Bean bean instance. function Create_Blog_Stat_Bean (Module : in AWA.Blogs.Modules.Blog_Module_Access) return Util.Beans.Basic.Readonly_Bean_Access; end AWA.Blogs.Beans;
----------------------------------------------------------------------- -- awa-blogs-beans -- Beans for blog module -- Copyright (C) 2011, 2012, 2013, 2014, 2015, 2016, 2017 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Strings.Unbounded; with Ada.Containers.Indefinite_Hashed_Maps; with Ada.Strings.Wide_Wide_Hash; with Ada.Strings.Wide_Wide_Unbounded; with Util.Beans.Basic; with Util.Beans.Objects; with ADO; with ADO.Objects; with Wiki.Strings; with AWA.Blogs.Modules; with AWA.Blogs.Models; with AWA.Tags.Beans; with AWA.Counters.Beans; with AWA.Events; with AWA.Components.Wikis; with ASF.Rest.Definition; -- == Blog Beans == -- Several bean types are provided to represent and manage the blogs and their posts. -- The blog module registers the bean constructors when it is initialized. -- To use them, one must declare a bean definition in the application XML configuration. package AWA.Blogs.Beans is -- Attributes exposed by <b>Post_Bean</b> BLOG_ID_ATTR : constant String := "blogId"; POST_ID_ATTR : constant String := "id"; POST_UID_ATTR : constant String := "uid"; POST_TITLE_ATTR : constant String := "title"; POST_TEXT_ATTR : constant String := "text"; POST_URI_ATTR : constant String := "uri"; POST_STATUS_ATTR : constant String := "status"; POST_USERNAME_ATTR : constant String := "username"; POST_TAG_ATTR : constant String := "tags"; POST_ALLOW_COMMENTS_ATTR : constant String := "allow_comments"; COUNTER_ATTR : constant String := "counter"; use Ada.Strings.Wide_Wide_Unbounded; package Image_Info_Maps is new Ada.Containers.Indefinite_Hashed_Maps (Key_Type => Wiki.Strings.WString, Element_Type => Models.Image_Info, Hash => Ada.Strings.Wide_Wide_Hash, Equivalent_Keys => "=", "=" => Models."="); type Post_Links_Bean is new AWA.Components.Wikis.Link_Renderer_Bean with record -- The wiki space identifier. Post_Id : ADO.Identifier; Images : Image_Info_Maps.Map; end record; procedure Make_Image_Link (Renderer : in out Post_Links_Bean; Link : in Wiki.Strings.WString; Info : in AWA.Blogs.Models.Image_Info; URI : out Unbounded_Wide_Wide_String; Width : in out Natural; Height : in out Natural); procedure Find_Image_Link (Renderer : in out Post_Links_Bean; Link : in Wiki.Strings.WString; URI : out Unbounded_Wide_Wide_String; Width : in out Natural; Height : in out Natural); -- Get the image link that must be rendered from the wiki image link. overriding procedure Make_Image_Link (Renderer : in out Post_Links_Bean; Link : in Wiki.Strings.WString; URI : out Unbounded_Wide_Wide_String; Width : in out Natural; Height : in out Natural); -- Get the page link that must be rendered from the wiki page link. overriding procedure Make_Page_Link (Renderer : in out Post_Links_Bean; Link : in Wiki.Strings.WString; URI : out Unbounded_Wide_Wide_String; Exists : out Boolean); -- ------------------------------ -- Blog Bean -- ------------------------------ -- The <b>Blog_Bean</b> holds the information about the current blog. -- It allows to create the blog as well as update its primary title. type Blog_Bean is new AWA.Blogs.Models.Blog_Bean with record Module : AWA.Blogs.Modules.Blog_Module_Access := null; end record; type Blog_Bean_Access is access all Blog_Bean'Class; -- Get the value identified by the name. overriding function Get_Value (From : in Blog_Bean; Name : in String) return Util.Beans.Objects.Object; -- Set the value identified by the name. overriding procedure Set_Value (From : in out Blog_Bean; Name : in String; Value : in Util.Beans.Objects.Object); -- Create a new blog. overriding procedure Create (Bean : in out Blog_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String); -- Load the blog information. overriding procedure Load (Bean : in out Blog_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String); -- Handle an event to create the blog entry automatically. overriding procedure Create_Default (Bean : in out Blog_Bean; Event : in AWA.Events.Module_Event'Class); -- Create the Blog_Bean bean instance. function Create_Blog_Bean (Module : in AWA.Blogs.Modules.Blog_Module_Access) return Util.Beans.Basic.Readonly_Bean_Access; -- ------------------------------ -- Post Bean -- ------------------------------ -- The <b>Post_Bean</b> is used to create or update a post associated with a blog. type Post_Bean is new AWA.Blogs.Models.Post_Bean with record Module : AWA.Blogs.Modules.Blog_Module_Access := null; Blog_Id : ADO.Identifier := ADO.NO_IDENTIFIER; -- List of tags associated with the post. Tags : aliased AWA.Tags.Beans.Tag_List_Bean; Tags_Bean : Util.Beans.Basic.Readonly_Bean_Access; -- The post page links. Links : aliased Post_Links_Bean; Links_Bean : Util.Beans.Basic.Readonly_Bean_Access; -- The read post counter associated with the post. Counter : aliased AWA.Counters.Beans.Counter_Bean (Of_Type => ADO.Objects.KEY_INTEGER, Of_Class => Models.POST_TABLE); Counter_Bean : Util.Beans.Basic.Readonly_Bean_Access; end record; type Post_Bean_Access is access all Post_Bean'Class; -- Get the value identified by the name. overriding function Get_Value (From : in Post_Bean; Name : in String) return Util.Beans.Objects.Object; -- Set the value identified by the name. overriding procedure Set_Value (From : in out Post_Bean; Name : in String; Value : in Util.Beans.Objects.Object); -- Load the post. procedure Load_Post (Post : in out Post_Bean; Id : in ADO.Identifier); -- Create or save the post. overriding procedure Save (Bean : in out Post_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String); -- Delete a post. overriding procedure Delete (Bean : in out Post_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String); -- Load the post from the URI for the public display. overriding procedure Load (Bean : in out Post_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String); -- Load the post from the URI for the administrator. overriding procedure Load_Admin (Bean : in out Post_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String); -- Load the post from the URI either with visible comments or with all comments. procedure Load (Bean : in out Post_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String; Publish_Only : in Boolean); -- Create the Post_Bean bean instance. function Create_Post_Bean (Module : in AWA.Blogs.Modules.Blog_Module_Access) return Util.Beans.Basic.Readonly_Bean_Access; procedure Create (Bean : in out Post_Bean; Req : in out ASF.Rest.Request'Class; Reply : in out ASF.Rest.Response'Class); procedure Update (Bean : in out Post_Bean; Req : in out ASF.Rest.Request'Class; Reply : in out ASF.Rest.Response'Class); package Post_API is new ASF.Rest.Definition (Object_Type => Post_Bean, URI => "/blogs/:blog_id/posts"); -- -- package API_Post_Create is -- new Post_API.Definition (Create'Access, ASF.Rest.POST, ""); -- -- package API_Post_Update is -- new Post_API.Definition (Update'Access, ASF.Rest.PUT, ":id"); -- ------------------------------ -- Post List Bean -- ------------------------------ -- The <b>Post_List_Bean</b> gives a list of visible posts to be displayed to users. -- The list can be filtered by a given tag. The list pagination is supported. type Post_List_Bean is new AWA.Blogs.Models.Post_List_Bean with record Posts : aliased AWA.Blogs.Models.Post_Info_List_Bean; Service : Modules.Blog_Module_Access := null; Tags : AWA.Tags.Beans.Entity_Tag_Map; Posts_Bean : AWA.Blogs.Models.Post_Info_List_Bean_Access; -- The post page links. Links : aliased Post_Links_Bean; Links_Bean : access Post_Links_Bean; -- The read post counter associated with the post. Counter : aliased AWA.Counters.Beans.Counter_Bean (Of_Type => ADO.Objects.KEY_INTEGER, Of_Class => Models.POST_TABLE); Counter_Bean : AWA.Counters.Beans.Counter_Bean_Access; end record; type Post_List_Bean_Access is access all Post_List_Bean'Class; -- Get the value identified by the name. overriding function Get_Value (From : in Post_List_Bean; Name : in String) return Util.Beans.Objects.Object; -- Set the value identified by the name. overriding procedure Set_Value (From : in out Post_List_Bean; Name : in String; Value : in Util.Beans.Objects.Object); overriding procedure Load (From : in out Post_List_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String); -- Load the list of posts. If a tag was set, filter the list of posts with the tag. procedure Load_List (Into : in out Post_List_Bean); -- Create the Post_List_Bean bean instance. function Create_Post_List_Bean (Module : in AWA.Blogs.Modules.Blog_Module_Access) return Util.Beans.Basic.Readonly_Bean_Access; -- Get a select item list which contains a list of post status. function Create_Status_List (Module : in AWA.Blogs.Modules.Blog_Module_Access) return Util.Beans.Basic.Readonly_Bean_Access; type Init_Flag is (INIT_BLOG_LIST, INIT_POST_LIST, INIT_COMMENT_LIST); type Init_Map is array (Init_Flag) of Boolean; -- ------------------------------ -- Admin List Bean -- ------------------------------ -- The <b>Blog_Admin_Bean</b> is used for the administration of a blog. It gives the -- list of posts that are created, published or not. type Blog_Admin_Bean is new Util.Beans.Basic.Bean with record Module : AWA.Blogs.Modules.Blog_Module_Access := null; -- The blog identifier. Blog_Id : ADO.Identifier := ADO.NO_IDENTIFIER; -- List of blogs. Blog_List : aliased AWA.Blogs.Models.Blog_Info_List_Bean; Blog_List_Bean : AWA.Blogs.Models.Blog_Info_List_Bean_Access; -- List of posts. Post_List : aliased AWA.Blogs.Models.Admin_Post_Info_List_Bean; Post_List_Bean : AWA.Blogs.Models.Admin_Post_Info_List_Bean_Access; -- List of comments. Comment_List : aliased AWA.Blogs.Models.Comment_Info_List_Bean; Comment_List_Bean : AWA.Blogs.Models.Comment_Info_List_Bean_Access; -- Initialization flags. Init_Flags : aliased Init_Map := (others => False); Flags : access Init_Map; end record; type Blog_Admin_Bean_Access is access all Blog_Admin_Bean; -- Get the blog identifier. function Get_Blog_Id (List : in Blog_Admin_Bean) return ADO.Identifier; -- Load the posts associated with the current blog. procedure Load_Posts (List : in Blog_Admin_Bean); -- Load the comments associated with the current blog. procedure Load_Comments (List : in Blog_Admin_Bean); overriding function Get_Value (List : in Blog_Admin_Bean; Name : in String) return Util.Beans.Objects.Object; -- Set the value identified by the name. overriding procedure Set_Value (From : in out Blog_Admin_Bean; Name : in String; Value : in Util.Beans.Objects.Object); -- Load the list of blogs. procedure Load_Blogs (List : in Blog_Admin_Bean); -- Create the Blog_Admin_Bean bean instance. function Create_Blog_Admin_Bean (Module : in AWA.Blogs.Modules.Blog_Module_Access) return Util.Beans.Basic.Readonly_Bean_Access; -- ------------------------------ -- Blog Statistics Bean -- ------------------------------ -- The <b>Blog_Stat_Bean</b> is used to report various statistics about the blog or some post. type Blog_Stat_Bean is new AWA.Blogs.Models.Stat_List_Bean with record Module : AWA.Blogs.Modules.Blog_Module_Access := null; Stats : aliased AWA.Blogs.Models.Month_Stat_Info_List_Bean; Stats_Bean : AWA.Blogs.Models.Month_Stat_Info_List_Bean_Access; end record; type Blog_Stat_Bean_Access is access all Blog_Stat_Bean; overriding function Get_Value (List : in Blog_Stat_Bean; Name : in String) return Util.Beans.Objects.Object; -- Set the value identified by the name. overriding procedure Set_Value (From : in out Blog_Stat_Bean; Name : in String; Value : in Util.Beans.Objects.Object); -- Load the statistics information. overriding procedure Load (List : in out Blog_Stat_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String); -- Create the Blog_Stat_Bean bean instance. function Create_Blog_Stat_Bean (Module : in AWA.Blogs.Modules.Blog_Module_Access) return Util.Beans.Basic.Readonly_Bean_Access; end AWA.Blogs.Beans;
Declare the Post_Links_Bean type with its operations for image support
Declare the Post_Links_Bean type with its operations for image support
Ada
apache-2.0
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
75464f2b90205d52ba8f4191c412b8ed9637f380
awa/plugins/awa-blogs/regtests/awa-blogs-modules-tests.adb
awa/plugins/awa-blogs/regtests/awa-blogs-modules-tests.adb
----------------------------------------------------------------------- -- awa-blogs-tests -- Unit tests for blogs module -- Copyright (C) 2011, 2012, 2013, 2014, 2015, 2019 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Test_Caller; with ADO; with Security.Contexts; with AWA.Services.Contexts; with AWA.Blogs.Modules; with AWA.Tests.Helpers.Users; package body AWA.Blogs.Modules.Tests is use ADO; package Caller is new Util.Test_Caller (Test, "Blogs.Services"); procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is begin Caller.Add_Test (Suite, "Test AWA.Blogs.Services.Create_Blog", Test_Create_Blog'Access); Caller.Add_Test (Suite, "Test AWA.Blogs.Services.Create_Post", Test_Create_Post'Access); end Add_Tests; -- ------------------------------ -- Test creation of a blog -- ------------------------------ procedure Test_Create_Blog (T : in out Test) is Manager : AWA.Blogs.Modules.Blog_Module_Access; Blog_Id : ADO.Identifier; Sec_Ctx : Security.Contexts.Security_Context; Context : AWA.Services.Contexts.Service_Context; begin AWA.Tests.Helpers.Users.Login (Context, Sec_Ctx, "[email protected]"); Manager := AWA.Blogs.Modules.Get_Blog_Module; Manager.Create_Blog (Title => "My blog", Result => Blog_Id); T.Assert (Blog_Id > 0, "Invalid blog identifier"); end Test_Create_Blog; -- ------------------------------ -- Test creating and updating of a blog post -- ------------------------------ procedure Test_Create_Post (T : in out Test) is Manager : AWA.Blogs.Modules.Blog_Module_Access; Blog_Id : ADO.Identifier; Post_Id : ADO.Identifier; Sec_Ctx : Security.Contexts.Security_Context; Context : AWA.Services.Contexts.Service_Context; begin AWA.Tests.Helpers.Users.Login (Context, Sec_Ctx, "[email protected]"); Manager := AWA.Blogs.Modules.Get_Blog_Module; Manager.Create_Blog (Title => "My blog post", Result => Blog_Id); T.Assert (Blog_Id > 0, "Invalid blog identifier"); for I in 1 .. 5 loop Manager.Create_Post (Blog_Id => Blog_Id, Title => "Testing blog title", URI => "testing-blog-title", Text => "The blog content", Comment => False, Status => AWA.Blogs.Models.POST_DRAFT, Result => Post_Id); T.Assert (Post_Id > 0, "Invalid post identifier"); Manager.Update_Post (Post_Id => Post_Id, Title => "New blog post title", URI => "testing-blog-title", Text => "The new post content", Publish_Date => ADO.Nullable_Time '(Is_Null => True, others => <>), Comment => True, Status => AWA.Blogs.Models.POST_DRAFT); -- Keep the last post in the database. exit when I = 5; Manager.Delete_Post (Post_Id => Post_Id); -- Verify that a Not_Found exception is raised if the post was deleted. begin Manager.Update_Post (Post_Id => Post_Id, Title => "Something", Text => "Content", URI => "testing-blog-title", Publish_Date => ADO.Nullable_Time '(Is_Null => True, others => <>), Comment => True, Status => AWA.Blogs.Models.POST_DRAFT); T.Assert (False, "Exception Not_Found was not raised"); exception when Not_Found => null; end; -- Verify that a Not_Found exception is raised if the post was deleted. begin Manager.Delete_Post (Post_Id => Post_Id); T.Assert (False, "Exception Not_Found was not raised"); exception when Not_Found => null; end; end loop; end Test_Create_Post; end AWA.Blogs.Modules.Tests;
----------------------------------------------------------------------- -- awa-blogs-tests -- Unit tests for blogs module -- Copyright (C) 2011, 2012, 2013, 2014, 2015, 2019 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Test_Caller; with ADO; with Security.Contexts; with AWA.Services.Contexts; with AWA.Blogs.Modules; with AWA.Tests.Helpers.Users; package body AWA.Blogs.Modules.Tests is use ADO; package Caller is new Util.Test_Caller (Test, "Blogs.Services"); procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is begin Caller.Add_Test (Suite, "Test AWA.Blogs.Services.Create_Blog", Test_Create_Blog'Access); Caller.Add_Test (Suite, "Test AWA.Blogs.Services.Create_Post", Test_Create_Post'Access); end Add_Tests; -- ------------------------------ -- Test creation of a blog -- ------------------------------ procedure Test_Create_Blog (T : in out Test) is Manager : AWA.Blogs.Modules.Blog_Module_Access; Blog_Id : ADO.Identifier; Sec_Ctx : Security.Contexts.Security_Context; Context : AWA.Services.Contexts.Service_Context; begin AWA.Tests.Helpers.Users.Login (Context, Sec_Ctx, "[email protected]"); Manager := AWA.Blogs.Modules.Get_Blog_Module; Manager.Create_Blog (Title => "My blog", Result => Blog_Id); T.Assert (Blog_Id > 0, "Invalid blog identifier"); end Test_Create_Blog; -- ------------------------------ -- Test creating and updating of a blog post -- ------------------------------ procedure Test_Create_Post (T : in out Test) is Manager : AWA.Blogs.Modules.Blog_Module_Access; Blog_Id : ADO.Identifier; Post_Id : ADO.Identifier; Sec_Ctx : Security.Contexts.Security_Context; Context : AWA.Services.Contexts.Service_Context; begin AWA.Tests.Helpers.Users.Login (Context, Sec_Ctx, "[email protected]"); Manager := AWA.Blogs.Modules.Get_Blog_Module; Manager.Create_Blog (Title => "My blog post", Result => Blog_Id); T.Assert (Blog_Id > 0, "Invalid blog identifier"); for I in 1 .. 5 loop Manager.Create_Post (Blog_Id => Blog_Id, Title => "Testing blog title", URI => "testing-blog-title", Text => "The blog content", Summary => "Summary", Format => AWA.Blogs.Models.FORMAT_DOTCLEAR, Comment => False, Status => AWA.Blogs.Models.POST_DRAFT, Result => Post_Id); T.Assert (Post_Id > 0, "Invalid post identifier"); Manager.Update_Post (Post_Id => Post_Id, Title => "New blog post title", URI => "testing-blog-title", Text => "The new post content", Summary => "New summary", Format => AWA.Blogs.Models.FORMAT_DOTCLEAR, Publish_Date => ADO.Nullable_Time '(Is_Null => True, others => <>), Comment => True, Status => AWA.Blogs.Models.POST_DRAFT); -- Keep the last post in the database. exit when I = 5; Manager.Delete_Post (Post_Id => Post_Id); -- Verify that a Not_Found exception is raised if the post was deleted. begin Manager.Update_Post (Post_Id => Post_Id, Title => "Something", Text => "Content", Summary => "Summary", Format => AWA.Blogs.Models.FORMAT_DOTCLEAR, URI => "testing-blog-title", Publish_Date => ADO.Nullable_Time '(Is_Null => True, others => <>), Comment => True, Status => AWA.Blogs.Models.POST_DRAFT); T.Assert (False, "Exception Not_Found was not raised"); exception when Not_Found => null; end; -- Verify that a Not_Found exception is raised if the post was deleted. begin Manager.Delete_Post (Post_Id => Post_Id); T.Assert (False, "Exception Not_Found was not raised"); exception when Not_Found => null; end; end loop; end Test_Create_Post; end AWA.Blogs.Modules.Tests;
Update the unit test
Update the unit test
Ada
apache-2.0
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
21a2c5b5a1be798c8149842c1d236792a3c8ba59
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 title in a report. -- ------------------------------ overriding procedure Start_Title (Console : in out Console_Type) is begin null; end Start_Title; -- ------------------------------ -- Finish a new title in a report. -- ------------------------------ procedure End_Title (Console : in out Console_Type) is begin Ada.Text_IO.New_Line; end End_Title; -- ------------------------------ -- Start a new row in a report. -- ------------------------------ overriding procedure Start_Row (Console : in out Console_Type) is 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 use type Ada.Text_IO.Count; Pos : constant Ada.Text_IO.Count := Ada.Text_IO.Count (Console.Cols (Field)); begin if Pos > 1 then Ada.Text_IO.Set_Col (Pos + Ada.Text_IO.Count (Console.Sizes (Field)) - Value'Length); end if; Ada.Text_IO.Put (Value); end Print_Field; -- ------------------------------ -- Print the title for the given field. -- ------------------------------ overriding procedure Print_Title (Console : in out Console_Type; Field : in Field_Type; Title : in String) is use type Ada.Text_IO.Count; Pos : constant Ada.Text_IO.Count := Ada.Text_IO.Count (Console.Cols (Field)); begin if Pos > 1 then Ada.Text_IO.Set_Col (Pos + Ada.Text_IO.Count (Console.Sizes (Field)) - Title'Length); end if; Ada.Text_IO.Put (Title); end Print_Title; -- ------------------------------ -- Start a new title in a report. -- ------------------------------ overriding procedure Start_Title (Console : in out Console_Type) is begin Console.Field_Count := 0; Console.Sizes := (others => 0); Console.Cols := (others => 1); end Start_Title; -- ------------------------------ -- Finish a new title in a report. -- ------------------------------ procedure End_Title (Console : in out Console_Type) is begin Ada.Text_IO.New_Line; end End_Title; -- ------------------------------ -- Start a new row in a report. -- ------------------------------ overriding procedure Start_Row (Console : in out Console_Type) is 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;
Indent the title and field values according to the column position
Indent the title and field values according to the column position
Ada
apache-2.0
stcarrez/mat,stcarrez/mat,stcarrez/mat
713f764e3714c30d02aef6ab41cc118039021691
awa/plugins/awa-wikis/regtests/awa-wikis-tests.adb
awa/plugins/awa-wikis/regtests/awa-wikis-tests.adb
----------------------------------------------------------------------- -- awa-wikis-tests -- Unit tests for wikis module -- 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 Util.Test_Caller; with Util.Strings; with Servlet.Streams; with ASF.Requests.Mockup; with ASF.Responses.Mockup; with ASF.Tests; with AWA.Tests.Helpers.Users; package body AWA.Wikis.Tests is use Ada.Strings.Unbounded; use AWA.Tests; package Caller is new Util.Test_Caller (Test, "Wikis.Beans"); procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is begin Caller.Add_Test (Suite, "Test AWA.Wikis.Beans.Load_List (Anonymous)", Test_Anonymous_Access'Access); Caller.Add_Test (Suite, "Test AWA.Wikis.Beans.Save", Test_Create_Wiki'Access); Caller.Add_Test (Suite, "Test AWA.Wikis.Beans.Load (missing)", Test_Missing_Page'Access); end Add_Tests; -- ------------------------------ -- Get some access on the wiki as anonymous users. -- ------------------------------ procedure Verify_Anonymous (T : in out Test; Page : in String; Title : in String) is pragma Unreferenced (Title); function Get_Link (Title : in String) return String; Wiki : constant String := To_String (T.Wiki_Ident); Request : ASF.Requests.Mockup.Request; Reply : ASF.Responses.Mockup.Response; function Get_Link (Title : in String) return String is Stream : Servlet.Streams.Print_Stream := Reply.Get_Output_Stream; Content : Ada.Strings.Unbounded.Unbounded_String; begin Reply.Read_Content (Content); Stream.Write (Content); return AWA.Tests.Helpers.Extract_Link (To_String (Content), Title); end Get_Link; begin ASF.Tests.Do_Get (Request, Reply, "/wikis/list/" & Wiki & "/recent", "wiki-list-recent.html"); ASF.Tests.Assert_Contains (T, "List of pages", Reply, "Wiki list recent page is invalid"); ASF.Tests.Do_Get (Request, Reply, "/wikis/tags/" & Wiki, "wiki-list-tagged.html"); ASF.Tests.Assert_Contains (T, "List of pages", Reply, "Wiki tag page is invalid"); if Page'Length > 0 then ASF.Tests.Do_Get (Request, Reply, "/wikis/view/" & Wiki & "/" & Page, "wiki-page-" & Page & ".html"); ASF.Tests.Assert_Contains (T, "The wiki page content", Reply, "Wiki page " & Page & " is invalid"); declare Info : constant String := Get_Link ("Info"); History : constant String := Get_Link ("History"); begin Util.Tests.Assert_Matches (T, "/asfunit/wikis/info/[0-9]+/[0-9]+$", Info, "Invalid wiki info link in the response"); Util.Tests.Assert_Matches (T, "/asfunit/wikis/history/[0-9]+/[0-9]+$", History, "Invalid wiki history link in the response"); -- Get the information page. ASF.Tests.Do_Get (Request, Reply, Info (Info'First + 8 .. Info'Last), "wiki-info-" & Page & ".html"); ASF.Tests.Assert_Contains (T, "wiki-word-list", Reply, "Wiki info page " & Page & " is invalid"); -- Get the history page. ASF.Tests.Do_Get (Request, Reply, History (History'First + 8 .. History'Last), "wiki-history-" & Page & ".html"); ASF.Tests.Assert_Contains (T, "wiki-page-version", Reply, "Wiki history page " & Page & " is invalid"); end; end if; end Verify_Anonymous; -- ------------------------------ -- Verify that the wiki lists contain the given page. -- ------------------------------ procedure Verify_List_Contains (T : in out Test; Page : in String) is Wiki : constant String := To_String (T.Wiki_Ident); Request : ASF.Requests.Mockup.Request; Reply : ASF.Responses.Mockup.Response; begin ASF.Tests.Do_Get (Request, Reply, "/wikis/list/" & Wiki & "/recent", "wiki-list-recent.html"); ASF.Tests.Assert_Contains (T, "List of pages", Reply, "Wiki list recent page is invalid"); ASF.Tests.Assert_Contains (T, "/wikis/view/" & To_String (T.Wiki_Ident) & "/" & Page, Reply, "Wiki list recent page does not reference the page"); ASF.Tests.Do_Get (Request, Reply, "/wikis/list/" & Wiki & "/popular", "wiki-list-popular.html"); ASF.Tests.Assert_Contains (T, "List of pages", Reply, "Wiki list popular page is invalid"); ASF.Tests.Assert_Contains (T, "/wikis/view/" & To_String (T.Wiki_Ident) & "/" & Page, Reply, "Wiki list popular page does not reference the page"); ASF.Tests.Do_Get (Request, Reply, "/wikis/list/" & Wiki & "/name", "wiki-list-name.html"); ASF.Tests.Assert_Contains (T, "List of pages", Reply, "Wiki list name page is invalid"); ASF.Tests.Assert_Contains (T, "/wikis/view/" & To_String (T.Wiki_Ident) & "/" & Page, Reply, "Wiki list name page does not reference the page"); ASF.Tests.Do_Get (Request, Reply, "/wikis/list/" & Wiki & "/name/grid", "wiki-list-name-grid.html"); ASF.Tests.Assert_Contains (T, "List of pages", Reply, "Wiki list name/grid page is invalid"); ASF.Tests.Assert_Contains (T, "/wikis/view/" & To_String (T.Wiki_Ident) & "/" & Page, Reply, "Wiki list name/grid page does not reference the page"); end Verify_List_Contains; -- ------------------------------ -- Test access to the blog as anonymous user. -- ------------------------------ procedure Test_Anonymous_Access (T : in out Test) is begin T.Verify_Anonymous ("", ""); end Test_Anonymous_Access; -- ------------------------------ -- Test creation of blog by simulating web requests. -- ------------------------------ procedure Test_Create_Wiki (T : in out Test) is procedure Create_Page (Name : in String; Title : in String); Request : ASF.Requests.Mockup.Request; Reply : ASF.Responses.Mockup.Response; procedure Create_Page (Name : in String; Title : in String) is begin Request.Set_Parameter ("page-wiki-id", To_String (T.Wiki_Ident)); Request.Set_Parameter ("post", "1"); Request.Set_Parameter ("page-title", Title); Request.Set_Parameter ("text", "# Main title" & ASCII.LF & "* The wiki page content." & ASCII.LF & "* Second item." & ASCII.LF); Request.Set_Parameter ("name", Name); Request.Set_Parameter ("comment", "Created wiki page " & Name); Request.Set_Parameter ("save", "1"); Request.Set_Parameter ("page-is-public", "1"); Request.Set_Parameter ("wiki-format", "FORMAT_MARKDOWN"); ASF.Tests.Do_Post (Request, Reply, "/wikis/create.html", "create-wiki.html"); T.Page_Ident := Helpers.Extract_Redirect (Reply, "/asfunit/wikis/view/" & To_String (T.Wiki_Ident) & "/"); Util.Tests.Assert_Equals (T, Name, To_String (T.Page_Ident), "Invalid redirect after wiki page creation"); -- Remove the 'wikiPage' bean from the request so that we get a new instance -- for the next call. Request.Remove_Attribute ("wikiPage"); end Create_Page; begin AWA.Tests.Helpers.Users.Login ("[email protected]", Request); Request.Set_Parameter ("title", "The Wiki Space Title"); Request.Set_Parameter ("post", "1"); Request.Set_Parameter ("create", "1"); ASF.Tests.Do_Post (Request, Reply, "/wikis/setup.html", "setup-wiki.html"); T.Assert (Reply.Get_Status = ASF.Responses.SC_MOVED_TEMPORARILY, "Invalid response after wiki space creation"); declare Ident : constant String := Helpers.Extract_Redirect (Reply, "/asfunit/wikis/list/"); Pos : constant Natural := Util.Strings.Index (Ident, '/'); begin Util.Tests.Assert_Matches (T, "^[0-9]+/recent/grid$", Ident, "Invalid wiki space identifier in the response"); T.Wiki_Ident := To_Unbounded_String (Ident (Ident'First .. Pos - 1)); end; Create_Page ("WikiPageTestName", "Wiki page title1"); T.Verify_List_Contains (To_String (T.Page_Ident)); Create_Page ("WikiSecondPageName", "Wiki page title2"); T.Verify_List_Contains (To_String (T.Page_Ident)); Create_Page ("WikiThirdPageName", "Wiki page title3"); T.Verify_Anonymous ("WikiPageTestName", "Wiki page title1"); T.Verify_Anonymous ("WikiSecondPageName", "Wiki page title2"); T.Verify_Anonymous ("WikiThirdPageName", "Wiki page title3"); end Test_Create_Wiki; -- ------------------------------ -- Test getting a wiki page which does not exist. -- ------------------------------ procedure Test_Missing_Page (T : in out Test) is Wiki : constant String := To_String (T.Wiki_Ident); Request : ASF.Requests.Mockup.Request; Reply : ASF.Responses.Mockup.Response; begin ASF.Tests.Do_Get (Request, Reply, "/wikis/view/" & Wiki & "/MissingPage", "wiki-page-missing.html"); ASF.Tests.Assert_Matches (T, ".title.Wiki page does not exist./title.", Reply, "Wiki page 'MissingPage' is invalid", ASF.Responses.SC_NOT_FOUND); ASF.Tests.Assert_Matches (T, ".h2.MissingPage./h2.", Reply, "Wiki page 'MissingPage' header is invalid", ASF.Responses.SC_NOT_FOUND); end Test_Missing_Page; end AWA.Wikis.Tests;
----------------------------------------------------------------------- -- awa-wikis-tests -- Unit tests for wikis module -- Copyright (C) 2018, 2019, 2020 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Test_Caller; with Util.Strings; with ADO; with Servlet.Streams; with ASF.Requests.Mockup; with ASF.Responses.Mockup; with ASF.Tests; with AWA.Tests.Helpers.Users; with AWA.Storages.Beans; with AWA.Storages.Models; with AWA.Storages.Services; with AWA.Storages.Modules; with AWA.Services.Contexts; with Security.Contexts; package body AWA.Wikis.Tests is use Ada.Strings.Unbounded; use AWA.Tests; use type AWA.Storages.Services.Storage_Service_Access; package Caller is new Util.Test_Caller (Test, "Wikis.Beans"); procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is begin Caller.Add_Test (Suite, "Test AWA.Wikis.Beans.Load_List (Anonymous)", Test_Anonymous_Access'Access); Caller.Add_Test (Suite, "Test AWA.Wikis.Beans.Save", Test_Create_Wiki'Access); Caller.Add_Test (Suite, "Test AWA.Wikis.Beans.Load (missing)", Test_Missing_Page'Access); Caller.Add_Test (Suite, "Test AWA.Wikis.Beans.Load (image)", Test_Page_With_Image'Access); end Add_Tests; -- ------------------------------ -- Setup an image for the wiki page. -- ------------------------------ procedure Make_Wiki_Image (T : in out Test) is Sec_Ctx : Security.Contexts.Security_Context; Context : AWA.Services.Contexts.Service_Context; Folder : AWA.Storages.Beans.Folder_Bean; Store : AWA.Storages.Models.Storage_Ref; Mgr : AWA.Storages.Services.Storage_Service_Access; Outcome : Ada.Strings.Unbounded.Unbounded_String; Path : constant String := Util.Tests.Get_Path ("regtests/files/images/Ada-Lovelace.jpg"); Wiki : constant String := To_String (T.Wiki_Ident); begin AWA.Tests.Helpers.Users.Login (Context, Sec_Ctx, "[email protected]"); Mgr := AWA.Storages.Modules.Get_Storage_Manager; T.Assert (Mgr /= null, "Null storage manager"); -- Make a storage folder. Folder.Module := AWA.Storages.Modules.Get_Storage_Module; Folder.Set_Name ("Images"); Folder.Save (Outcome); Store.Set_Folder (Folder); Store.Set_Is_Public (True); Store.Set_Mime_Type ("image/jpg"); Store.Set_Name ("Ada Lovelace"); Mgr.Save (Store, Path, AWA.Storages.Models.FILE); declare Request : ASF.Requests.Mockup.Request; Reply : ASF.Responses.Mockup.Response; Id : constant String := ADO.Identifier'Image (Store.Get_Id); begin T.Image_Ident := To_Unbounded_String (Id (Id'First + 1 .. Id'Last)); AWA.Tests.Helpers.Users.Login ("[email protected]", Request); ASF.Tests.Do_Get (Request, Reply, "/wikis/images/" & Wiki & "/" & Id (Id'First + 1 .. Id'Last) & "/original/Ada-Lovelace.jpg", "wiki-image-get-Ada-Lovelace.jpg"); ASF.Tests.Assert_Header (T, "Content-Type", "image/jpg", Reply); Util.Tests.Assert_Equals (T, Servlet.Responses.SC_OK, Reply.Get_Status, "Invalid response for image"); end; end Make_Wiki_Image; -- ------------------------------ -- Get some access on the wiki as anonymous users. -- ------------------------------ procedure Verify_Anonymous (T : in out Test; Page : in String; Title : in String) is pragma Unreferenced (Title); function Get_Link (Title : in String) return String; Wiki : constant String := To_String (T.Wiki_Ident); Request : ASF.Requests.Mockup.Request; Reply : ASF.Responses.Mockup.Response; function Get_Link (Title : in String) return String is Stream : Servlet.Streams.Print_Stream := Reply.Get_Output_Stream; Content : Ada.Strings.Unbounded.Unbounded_String; begin Reply.Read_Content (Content); Stream.Write (Content); return AWA.Tests.Helpers.Extract_Link (To_String (Content), Title); end Get_Link; begin ASF.Tests.Do_Get (Request, Reply, "/wikis/list/" & Wiki & "/recent", "wiki-list-recent.html"); ASF.Tests.Assert_Contains (T, "List of pages", Reply, "Wiki list recent page is invalid"); ASF.Tests.Do_Get (Request, Reply, "/wikis/tags/" & Wiki, "wiki-list-tagged.html"); ASF.Tests.Assert_Contains (T, "List of pages", Reply, "Wiki tag page is invalid"); if Page'Length > 0 then ASF.Tests.Do_Get (Request, Reply, "/wikis/view/" & Wiki & "/" & Page, "wiki-page-" & Page & ".html"); ASF.Tests.Assert_Contains (T, "The wiki page content", Reply, "Wiki page " & Page & " is invalid"); declare Info : constant String := Get_Link ("Info"); History : constant String := Get_Link ("History"); begin Util.Tests.Assert_Matches (T, "/asfunit/wikis/info/[0-9]+/[0-9]+$", Info, "Invalid wiki info link in the response"); Util.Tests.Assert_Matches (T, "/asfunit/wikis/history/[0-9]+/[0-9]+$", History, "Invalid wiki history link in the response"); -- Get the information page. ASF.Tests.Do_Get (Request, Reply, Info (Info'First + 8 .. Info'Last), "wiki-info-" & Page & ".html"); ASF.Tests.Assert_Contains (T, "wiki-word-list", Reply, "Wiki info page " & Page & " is invalid"); -- Get the history page. ASF.Tests.Do_Get (Request, Reply, History (History'First + 8 .. History'Last), "wiki-history-" & Page & ".html"); ASF.Tests.Assert_Contains (T, "wiki-page-version", Reply, "Wiki history page " & Page & " is invalid"); end; end if; end Verify_Anonymous; -- ------------------------------ -- Verify that the wiki lists contain the given page. -- ------------------------------ procedure Verify_List_Contains (T : in out Test; Page : in String) is Wiki : constant String := To_String (T.Wiki_Ident); Request : ASF.Requests.Mockup.Request; Reply : ASF.Responses.Mockup.Response; begin ASF.Tests.Do_Get (Request, Reply, "/wikis/list/" & Wiki & "/recent", "wiki-list-recent.html"); ASF.Tests.Assert_Contains (T, "List of pages", Reply, "Wiki list recent page is invalid"); ASF.Tests.Assert_Contains (T, "/wikis/view/" & To_String (T.Wiki_Ident) & "/" & Page, Reply, "Wiki list recent page does not reference the page"); ASF.Tests.Do_Get (Request, Reply, "/wikis/list/" & Wiki & "/popular", "wiki-list-popular.html"); ASF.Tests.Assert_Contains (T, "List of pages", Reply, "Wiki list popular page is invalid"); ASF.Tests.Assert_Contains (T, "/wikis/view/" & To_String (T.Wiki_Ident) & "/" & Page, Reply, "Wiki list popular page does not reference the page"); ASF.Tests.Do_Get (Request, Reply, "/wikis/list/" & Wiki & "/name", "wiki-list-name.html"); ASF.Tests.Assert_Contains (T, "List of pages", Reply, "Wiki list name page is invalid"); ASF.Tests.Assert_Contains (T, "/wikis/view/" & To_String (T.Wiki_Ident) & "/" & Page, Reply, "Wiki list name page does not reference the page"); ASF.Tests.Do_Get (Request, Reply, "/wikis/list/" & Wiki & "/name/grid", "wiki-list-name-grid.html"); ASF.Tests.Assert_Contains (T, "List of pages", Reply, "Wiki list name/grid page is invalid"); ASF.Tests.Assert_Contains (T, "/wikis/view/" & To_String (T.Wiki_Ident) & "/" & Page, Reply, "Wiki list name/grid page does not reference the page"); end Verify_List_Contains; -- ------------------------------ -- Test access to the blog as anonymous user. -- ------------------------------ procedure Test_Anonymous_Access (T : in out Test) is begin T.Verify_Anonymous ("", ""); end Test_Anonymous_Access; -- ------------------------------ -- Create a wiki page. -- ------------------------------ procedure Create_Page (T : in out Test; Request : in out ASF.Requests.Mockup.Request; Reply : in out ASF.Responses.Mockup.Response; Name : in String; Title : in String) is begin Request.Set_Parameter ("page-wiki-id", To_String (T.Wiki_Ident)); Request.Set_Parameter ("post", "1"); Request.Set_Parameter ("page-title", Title); Request.Set_Parameter ("text", "# Main title" & ASCII.LF & "* The wiki page content." & ASCII.LF & "* Second item." & ASCII.LF & ASCII.LF & "![Ada Lovelace](Images/Ada-Lovelace.jpg)"); Request.Set_Parameter ("name", Name); Request.Set_Parameter ("comment", "Created wiki page " & Name); Request.Set_Parameter ("save", "1"); Request.Set_Parameter ("page-is-public", "1"); Request.Set_Parameter ("wiki-format", "FORMAT_MARKDOWN"); ASF.Tests.Do_Post (Request, Reply, "/wikis/create.html", "create-wiki.html"); T.Page_Ident := Helpers.Extract_Redirect (Reply, "/asfunit/wikis/view/" & To_String (T.Wiki_Ident) & "/"); Util.Tests.Assert_Equals (T, Name, To_String (T.Page_Ident), "Invalid redirect after wiki page creation"); -- Remove the 'wikiPage' bean from the request so that we get a new instance -- for the next call. Request.Remove_Attribute ("wikiPage"); end Create_Page; -- ------------------------------ -- Test creation of blog by simulating web requests. -- ------------------------------ procedure Test_Create_Wiki (T : in out Test) is Request : ASF.Requests.Mockup.Request; Reply : ASF.Responses.Mockup.Response; begin AWA.Tests.Helpers.Users.Login ("[email protected]", Request); Request.Set_Parameter ("title", "The Wiki Space Title"); Request.Set_Parameter ("post", "1"); Request.Set_Parameter ("create", "1"); ASF.Tests.Do_Post (Request, Reply, "/wikis/setup.html", "setup-wiki.html"); T.Assert (Reply.Get_Status = ASF.Responses.SC_MOVED_TEMPORARILY, "Invalid response after wiki space creation"); declare Ident : constant String := Helpers.Extract_Redirect (Reply, "/asfunit/wikis/list/"); Pos : constant Natural := Util.Strings.Index (Ident, '/'); begin Util.Tests.Assert_Matches (T, "^[0-9]+/recent/grid$", Ident, "Invalid wiki space identifier in the response"); T.Wiki_Ident := To_Unbounded_String (Ident (Ident'First .. Pos - 1)); end; T.Create_Page (Request, Reply, "WikiPageTestName", "Wiki page title1"); T.Verify_List_Contains (To_String (T.Page_Ident)); T.Create_Page (Request, Reply, "WikiSecondPageName", "Wiki page title2"); T.Verify_List_Contains (To_String (T.Page_Ident)); T.Create_Page (Request, Reply, "WikiThirdPageName", "Wiki page title3"); T.Verify_Anonymous ("WikiPageTestName", "Wiki page title1"); T.Verify_Anonymous ("WikiSecondPageName", "Wiki page title2"); T.Verify_Anonymous ("WikiThirdPageName", "Wiki page title3"); end Test_Create_Wiki; -- ------------------------------ -- Test getting a wiki page which does not exist. -- ------------------------------ procedure Test_Missing_Page (T : in out Test) is Wiki : constant String := To_String (T.Wiki_Ident); Request : ASF.Requests.Mockup.Request; Reply : ASF.Responses.Mockup.Response; begin ASF.Tests.Do_Get (Request, Reply, "/wikis/view/" & Wiki & "/MissingPage", "wiki-page-missing.html"); ASF.Tests.Assert_Matches (T, ".title.Wiki page does not exist./title.", Reply, "Wiki page 'MissingPage' is invalid", ASF.Responses.SC_NOT_FOUND); ASF.Tests.Assert_Matches (T, ".h2.MissingPage./h2.", Reply, "Wiki page 'MissingPage' header is invalid", ASF.Responses.SC_NOT_FOUND); end Test_Missing_Page; -- ------------------------------ -- Test creation of wiki page with an image. -- ------------------------------ procedure Test_Page_With_Image (T : in out Test) is Request : ASF.Requests.Mockup.Request; Reply : ASF.Responses.Mockup.Response; Wiki : constant String := To_String (T.Wiki_Ident); begin AWA.Tests.Helpers.Users.Login ("[email protected]", Request); T.Make_Wiki_Image; T.Create_Page (Request, Reply, "WikiImageTest", "Wiki image title3"); ASF.Tests.Do_Get (Request, Reply, "/wikis/view/" & Wiki & "/WikiImageTest", "wiki-image-test.html"); ASF.Tests.Assert_Matches (T, "<img src=./wikis/images/[0-9]*/[0-9]*" & "/default/Ada-Lovelace.jpg. alt=.Ada Lovelace.></img>", Reply, "Wiki page missing image link", ASF.Responses.SC_OK); end Test_Page_With_Image; end AWA.Wikis.Tests;
Add Test_Page_With_Image, Make_Wiki_Image to test including images in a wiki
Add Test_Page_With_Image, Make_Wiki_Image to test including images in a wiki
Ada
apache-2.0
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
e1a8170bb6de1cbfb9a0dad3e56e372c0f08a2b1
src/asf-views-nodes.adb
src/asf-views-nodes.adb
----------------------------------------------------------------------- -- asf-views-nodes -- Facelet node tree representation -- 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 ASF.Contexts.Writer; with ASF.Components.Core; with Ada.Text_IO; with Ada.Unchecked_Deallocation; package body ASF.Views.Nodes is use EL.Expressions; procedure Free is new Ada.Unchecked_Deallocation (Tag_Node'Class, Tag_Node_Access); procedure Free is new Ada.Unchecked_Deallocation (Tag_Attribute_Array, Tag_Attribute_Array_Access); procedure Free is new Ada.Unchecked_Deallocation (EL.Expressions.Expression'Class, EL.Expressions.Expression_Access); -- ------------------------------ -- Attribute of a node. -- ------------------------------ -- ------------------------------ -- Get the attribute name. -- ------------------------------ function Get_Name (Attribute : Tag_Attribute) return Unbounded_String is begin return Attribute.Name; end Get_Name; -- ------------------------------ -- Get the attribute literal value. -- ------------------------------ function Get_Value (Attribute : Tag_Attribute) return Unbounded_String is begin return Attribute.Value; end Get_Value; -- ------------------------------ -- Get the attribute value. If the attribute is an EL expression -- evaluate that expression in the context of the given UI component. -- ------------------------------ function Get_Value (Attribute : Tag_Attribute; UI : UIComponent'Class) return EL.Objects.Object is begin return EL.Objects.Null_Object; end Get_Value; -- ------------------------------ -- Get the attribute value. If the attribute is an EL expression -- evaluate that expression in the context of the given UI component. -- ------------------------------ function Get_Value (Attribute : Tag_Attribute; Context : Faces_Context'Class) return EL.Objects.Object is begin if Attribute.Binding /= null then return Attribute.Binding.Get_Value (Context.Get_ELContext.all); else return EL.Objects.To_Object (Attribute.Value); end if; end Get_Value; function Get_Value (Attribute : Tag_Attribute; Context : Facelet_Context'Class) return EL.Objects.Object is begin if Attribute.Binding /= null then return Attribute.Binding.Get_Value (Context.Get_ELContext.all); else return EL.Objects.To_Object (Attribute.Value); end if; end Get_Value; -- ------------------------------ -- Find the tag attribute having the given name. -- Returns an access to the attribute cell within the array or null -- if the no attribute matches the name. -- ------------------------------ function Find_Attribute (Attributes : Tag_Attribute_Array_Access; Name : String) return Tag_Attribute_Access is begin for I in Attributes'Range loop declare Attr : constant Tag_Attribute_Access := Attributes (I)'Access; begin if Attr.Name = Name then return Attr; end if; end; end loop; return null; end Find_Attribute; -- ------------------------------ -- XHTML node -- ------------------------------ -- ------------------------------ -- Get the node name. -- ------------------------------ function Get_Name (Node : Tag_Node) return Unbounded_String is begin return Node.Name; end Get_Name; -- ------------------------------ -- Get the node attribute with the given name. -- Returns null if the node does not have such attribute. -- ------------------------------ function Get_Attribute (Node : Tag_Node; Name : String) return Tag_Attribute_Access is begin if Node.Attributes = null then return null; end if; return Find_Attribute (Node.Attributes, Name); end Get_Attribute; -- ------------------------------ -- Append a child tag node. -- ------------------------------ procedure Append_Tag (Node : in Tag_Node_Access; Child : in Tag_Node_Access) is begin if Node.First_Child = null then Node.First_Child := Child; else Node.Last_Child.Next := Child; end if; Node.Last_Child := Child; Child.Parent := Node; Child.Next := null; end Append_Tag; -- ------------------------------ -- Freeze the tag node tree and perform any initialization steps -- necessary to build the components efficiently. After this call -- the tag node tree should not be modified and it represents a read-only -- tree. -- ------------------------------ procedure Freeze (Node : access Tag_Node) is begin null; end Freeze; -- ------------------------------ -- Delete the node and its children freeing the memory as necessary -- ------------------------------ procedure Delete (Node : access Tag_Node) is Child : Tag_Node_Access := Node.First_Child; Next : Tag_Node_Access; begin while Child /= null loop Next := Child.Next; Child.Delete; Free (Child); Child := Next; end loop; if Node.Attributes /= null then for I in Node.Attributes'Range loop declare Expr : EL.Expressions.Expression_Access := Node.Attributes (I).Binding; begin Free (Expr); end; end loop; Free (Node.Attributes); end if; end Delete; -- ------------------------------ -- Build the component tree from the tag node and attach it as -- the last child of the given parent. Calls recursively the -- method to create children. -- ------------------------------ procedure Build_Components (Node : access Tag_Node; Parent : in UIComponent_Access; Context : in out Facelet_Context'Class) is UI : UIComponent_Access; begin UI := Node.Factory.all; Append (Parent, UI, Node); Node.Build_Children (UI, Context); end Build_Components; procedure Build_Children (Node : access Tag_Node; Parent : in UIComponent_Access; Context : in out Facelet_Context'Class) is Child : Tag_Node_Access; begin Child := Node.First_Child; while Child /= null loop Child.Build_Components (Parent, Context); Child := Child.Next; end loop; end Build_Children; overriding procedure Build_Components (Node : access Text_Tag_Node; Parent : in UIComponent_Access; Context : in out Facelet_Context'Class) is UI : UIComponent_Access := ASF.Components.Core.Create_UIText (Parent, Node.all'Access); begin null; end Build_Components; -- ------------------------------ -- Encode the content represented by this text node. -- The expressions are evaluated if necessary. -- ------------------------------ procedure Encode_All (Node : Text_Tag_Node; Context : in Faces_Context'Class) is Writer : constant ASF.Contexts.Writer.ResponseWriter_Access := Context.Get_Response_Writer; Content : access constant Tag_Content := Node.Content'Access; begin loop Writer.Write (Content.Text); declare Value : constant EL.Objects.Object := Content.Expr.Get_Value (Context.Get_ELContext.all); begin if not EL.Objects.Is_Null (Value) then Writer.Write_Text (Value); end if; end; Content := Content.Next; exit when Content = null; end loop; end Encode_All; function First (Node : in Tag_Node_Access) return Cursor is Result : Cursor; begin Result.Node := Node.First_Child; return Result; end First; function Has_Element (C : Cursor) return Boolean is begin return C.Node /= null; end Has_Element; function Element (Position : Cursor) return Tag_Node_Access is begin return Position.Node; end Element; procedure Next (Position : in out Cursor) is begin Position.Node := Position.Node.Next; end Next; -- Create the text Tag function Create_Component_Node (Name : Unbounded_String; Parent : Tag_Node_Access; Attributes : Tag_Attribute_Array_Access) return Tag_Node_Access is Node : constant Tag_Node_Access := new Tag_Node; begin Node.Name := Name; Node.Parent := Parent; Node.Attributes := Attributes; return Node.all'Access; end Create_Component_Node; end ASF.Views.Nodes;
----------------------------------------------------------------------- -- asf-views-nodes -- Facelet node tree representation -- 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 ASF.Contexts.Writer; with Ada.Unchecked_Deallocation; package body ASF.Views.Nodes is use EL.Expressions; procedure Free is new Ada.Unchecked_Deallocation (Tag_Node'Class, Tag_Node_Access); procedure Free is new Ada.Unchecked_Deallocation (Tag_Attribute_Array, Tag_Attribute_Array_Access); procedure Free is new Ada.Unchecked_Deallocation (EL.Expressions.Expression'Class, EL.Expressions.Expression_Access); -- ------------------------------ -- Attribute of a node. -- ------------------------------ -- ------------------------------ -- Get the attribute name. -- ------------------------------ function Get_Name (Attribute : Tag_Attribute) return Unbounded_String is begin return Attribute.Name; end Get_Name; -- ------------------------------ -- Get the attribute literal value. -- ------------------------------ function Get_Value (Attribute : Tag_Attribute) return Unbounded_String is begin return Attribute.Value; end Get_Value; -- ------------------------------ -- Get the attribute value. If the attribute is an EL expression -- evaluate that expression in the context of the given UI component. -- ------------------------------ function Get_Value (Attribute : Tag_Attribute; UI : UIComponent'Class) return EL.Objects.Object is begin if Attribute.Binding /= null then return Attribute.Binding.Get_Value (UI.Get_Context.Get_ELContext.all); else return EL.Objects.To_Object (Attribute.Value); end if; end Get_Value; -- ------------------------------ -- Get the attribute value. If the attribute is an EL expression -- evaluate that expression in the context of the given UI component. -- ------------------------------ function Get_Value (Attribute : Tag_Attribute; Context : Faces_Context'Class) return EL.Objects.Object is begin if Attribute.Binding /= null then return Attribute.Binding.Get_Value (Context.Get_ELContext.all); else return EL.Objects.To_Object (Attribute.Value); end if; end Get_Value; function Get_Value (Attribute : Tag_Attribute; Context : Facelet_Context'Class) return EL.Objects.Object is begin if Attribute.Binding /= null then return Attribute.Binding.Get_Value (Context.Get_ELContext.all); else return EL.Objects.To_Object (Attribute.Value); end if; end Get_Value; -- ------------------------------ -- Find the tag attribute having the given name. -- Returns an access to the attribute cell within the array or null -- if the no attribute matches the name. -- ------------------------------ function Find_Attribute (Attributes : Tag_Attribute_Array_Access; Name : String) return Tag_Attribute_Access is begin for I in Attributes'Range loop declare Attr : constant Tag_Attribute_Access := Attributes (I)'Access; begin if Attr.Name = Name then return Attr; end if; end; end loop; return null; end Find_Attribute; -- ------------------------------ -- XHTML node -- ------------------------------ -- ------------------------------ -- Get the node name. -- ------------------------------ function Get_Name (Node : Tag_Node) return Unbounded_String is begin return Node.Name; end Get_Name; -- ------------------------------ -- Get the node attribute with the given name. -- Returns null if the node does not have such attribute. -- ------------------------------ function Get_Attribute (Node : Tag_Node; Name : String) return Tag_Attribute_Access is begin if Node.Attributes = null then return null; end if; return Find_Attribute (Node.Attributes, Name); end Get_Attribute; -- ------------------------------ -- Append a child tag node. -- ------------------------------ procedure Append_Tag (Node : in Tag_Node_Access; Child : in Tag_Node_Access) is begin if Node.First_Child = null then Node.First_Child := Child; else Node.Last_Child.Next := Child; end if; Node.Last_Child := Child; Child.Parent := Node; Child.Next := null; end Append_Tag; -- ------------------------------ -- Freeze the tag node tree and perform any initialization steps -- necessary to build the components efficiently. After this call -- the tag node tree should not be modified and it represents a read-only -- tree. -- ------------------------------ procedure Freeze (Node : access Tag_Node) is begin null; end Freeze; -- ------------------------------ -- Delete the node and its children freeing the memory as necessary -- ------------------------------ procedure Delete (Node : access Tag_Node) is Child : Tag_Node_Access := Node.First_Child; Next : Tag_Node_Access; begin while Child /= null loop Next := Child.Next; Child.Delete; Free (Child); Child := Next; end loop; if Node.Attributes /= null then for I in Node.Attributes'Range loop declare Expr : EL.Expressions.Expression_Access := Node.Attributes (I).Binding; begin Free (Expr); end; end loop; Free (Node.Attributes); end if; end Delete; -- ------------------------------ -- Build the component tree from the tag node and attach it as -- the last child of the given parent. Calls recursively the -- method to create children. -- ------------------------------ procedure Build_Components (Node : access Tag_Node; Parent : in UIComponent_Access; Context : in out Facelet_Context'Class) is UI : UIComponent_Access; begin UI := Node.Factory.all; Append (Parent, UI, Node); Node.Build_Children (UI, Context); end Build_Components; procedure Build_Children (Node : access Tag_Node; Parent : in UIComponent_Access; Context : in out Facelet_Context'Class) is Child : Tag_Node_Access; begin Child := Node.First_Child; while Child /= null loop Child.Build_Components (Parent, Context); Child := Child.Next; end loop; end Build_Children; overriding procedure Build_Components (Node : access Text_Tag_Node; Parent : in UIComponent_Access; Context : in out Facelet_Context'Class) is -- UI : UIComponent_Access := ASF.Components.Core.Create_UIText (Parent, Node.all'Access); begin null; end Build_Components; -- ------------------------------ -- Encode the content represented by this text node. -- The expressions are evaluated if necessary. -- ------------------------------ procedure Encode_All (Node : Text_Tag_Node; Context : in Faces_Context'Class) is Writer : constant ASF.Contexts.Writer.ResponseWriter_Access := Context.Get_Response_Writer; Content : access constant Tag_Content := Node.Content'Access; begin loop Writer.Write (Content.Text); declare Value : constant EL.Objects.Object := Content.Expr.Get_Value (Context.Get_ELContext.all); begin if not EL.Objects.Is_Null (Value) then Writer.Write_Text (Value); end if; end; Content := Content.Next; exit when Content = null; end loop; end Encode_All; function First (Node : in Tag_Node_Access) return Cursor is Result : Cursor; begin Result.Node := Node.First_Child; return Result; end First; function Has_Element (C : Cursor) return Boolean is begin return C.Node /= null; end Has_Element; function Element (Position : Cursor) return Tag_Node_Access is begin return Position.Node; end Element; procedure Next (Position : in out Cursor) is begin Position.Node := Position.Node.Next; end Next; -- Create the text Tag function Create_Component_Node (Name : Unbounded_String; Parent : Tag_Node_Access; Attributes : Tag_Attribute_Array_Access) return Tag_Node_Access is Node : constant Tag_Node_Access := new Tag_Node; begin Node.Name := Name; Node.Parent := Parent; Node.Attributes := Attributes; return Node.all'Access; end Create_Component_Node; end ASF.Views.Nodes;
Implement Tag_Attribute.Get_Value
Implement Tag_Attribute.Get_Value
Ada
apache-2.0
stcarrez/ada-asf,stcarrez/ada-asf,stcarrez/ada-asf
6b9126e6a75110ae3ed0f40b21d92fff6e168a22
mat/src/memory/mat-memory-targets.adb
mat/src/memory/mat-memory-targets.adb
----------------------------------------------------------------------- -- Memory Events - Definition and Analysis of memory events -- Copyright (C) 2014 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Log.Loggers; with MAT.Memory.Readers; package body MAT.Memory.Targets is -- The logger Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("MAT.Memory.Targets"); -- ------------------------------ -- Initialize the target memory object to manage the memory slots, the stack frames -- and setup the reader to analyze the memory events. -- ------------------------------ procedure Initialize (Memory : in out Target_Memory; Reader : in out MAT.Readers.Manager_Base'Class) is Memory_Reader : constant MAT.Memory.Readers.Memory_Reader_Access := new MAT.Memory.Readers.Memory_Servant; begin Memory.Reader := Memory_Reader.all'Access; Memory_Reader.Data := Memory'Unrestricted_Access; Memory.Frames := Frames.Create_Root; MAT.Memory.Readers.Register (Reader, Memory_Reader); end Initialize; -- ------------------------------ -- Take into account a malloc probe. The memory slot [Addr .. Slot.Size] is inserted -- in the used slots map. The freed slots that intersect the malloc'ed region are -- removed from the freed map. -- ------------------------------ procedure Probe_Malloc (Memory : in out Target_Memory; Addr : in MAT.Types.Target_Addr; Slot : in Allocation) is begin Memory.Memory.Probe_Malloc (Addr, Slot); end Probe_Malloc; -- ------------------------------ -- Take into account a free probe. Add the memory slot in the freed map and remove -- the slot from the used slots map. -- ------------------------------ procedure Probe_Free (Memory : in out Target_Memory; Addr : in MAT.Types.Target_Addr; Slot : in Allocation) is begin Memory.Memory.Probe_Free (Addr, Slot); end Probe_Free; -- ------------------------------ -- Take into account a realloc probe. The old memory slot represented by Old_Addr is -- removed from the used slots maps and the new memory slot [Addr .. Slot.Size] is -- inserted in the used slots map. -- ------------------------------ procedure Probe_Realloc (Memory : in out Target_Memory; Addr : in MAT.Types.Target_Addr; Old_Addr : in MAT.Types.Target_Addr; Slot : in Allocation) is begin Memory.Memory.Probe_Realloc (Addr, Old_Addr, Slot); end Probe_Realloc; -- ------------------------------ -- Collect the information about memory slot sizes allocated by the application. -- ------------------------------ procedure Size_Information (Memory : in Target_Memory; Sizes : in out Size_Info_Map) is Iter : Allocation_Cursor := Memory.Memory_Slots.First; procedure Update_Count (Size : in MAT.Types.Target_Size; Info : in out Size_Info_Type) is begin Info.Count := Info.Count + 1; end Update_Count; procedure Collect (Addr : in MAT.Types.Target_Addr; Slot : in Allocation) is Pos : Size_Info_Cursor := Sizes.Find (Slot.Size); begin if Size_Info_Maps.Has_Element (Pos) then Sizes.Update_Element (Pos, Update_Count'Access); else declare Info : Size_Info_Type; begin Info.Count := 1; Sizes.Insert (Slot.Size, Info); end; end if; end Collect; begin while Allocation_Maps.Has_Element (Iter) loop Allocation_Maps.Query_Element (Iter, Collect'Access); Allocation_Maps.Next (Iter); end loop; end Size_Information; protected body Memory_Allocator is -- ------------------------------ -- Remove the memory region [Addr .. Addr + Size] from the free list. -- ------------------------------ procedure Remove_Free (Addr : in MAT.Types.Target_Addr; Size : in MAT.Types.Target_Size) is Iter : Allocation_Cursor; Last : constant MAT.Types.Target_Addr := Addr + MAT.Types.Target_Addr (Size); Slot : Allocation; begin -- Walk the list of free blocks and remove all the blocks which intersect the region -- [Addr .. Addr + Slot.Size]. We start walking at the first block below and near -- the address. Slots are then removed when they intersect the malloc'ed region. Iter := Freed_Slots.Floor (Addr); while Allocation_Maps.Has_Element (Iter) loop declare Freed_Addr : constant MAT.Types.Target_Addr := Allocation_Maps.Key (Iter); begin exit when Freed_Addr > Last; Slot := Allocation_Maps.Element (Iter); if Freed_Addr + MAT.Types.Target_Addr (Slot.Size) > Addr then Freed_Slots.Delete (Iter); Iter := Freed_Slots.Floor (Addr); else Allocation_Maps.Next (Iter); end if; end; end loop; end Remove_Free; -- ------------------------------ -- Take into account a malloc probe. The memory slot [Addr .. Slot.Size] is inserted -- in the used slots map. The freed slots that intersect the malloc'ed region are -- removed from the freed map. -- ------------------------------ procedure Probe_Malloc (Addr : in MAT.Types.Target_Addr; Slot : in Allocation) is begin Remove_Free (Addr, Slot.Size); Used_Slots.Insert (Addr, Slot); end Probe_Malloc; -- ------------------------------ -- Take into account a free probe. Add the memory slot in the freed map and remove -- the slot from the used slots map. -- ------------------------------ procedure Probe_Free (Addr : in MAT.Types.Target_Addr; Slot : in Allocation) is Item : Allocation; Iter : Allocation_Cursor; begin Iter := Used_Slots.Find (Addr); if Allocation_Maps.Has_Element (Iter) then Item := Allocation_Maps.Element (Iter); MAT.Frames.Release (Item.Frame); Used_Slots.Delete (Iter); Item.Frame := Slot.Frame; Freed_Slots.Insert (Addr, Item); end if; end Probe_Free; -- ------------------------------ -- Take into account a realloc probe. The old memory slot represented by Old_Addr is -- removed from the used slots maps and the new memory slot [Addr .. Slot.Size] is -- inserted in the used slots map. -- ------------------------------ procedure Probe_Realloc (Addr : in MAT.Types.Target_Addr; Old_Addr : in MAT.Types.Target_Addr; Slot : in Allocation) is Old_Slot : Allocation; Pos : Allocation_Cursor; procedure Update_Size (Key : in MAT.Types.Target_Addr; Element : in out Allocation) is begin Element.Size := Slot.Size; MAT.Frames.Release (Element.Frame); Element.Frame := Slot.Frame; end Update_Size; begin if Old_Addr /= 0 then Pos := Used_Slots.Find (Old_Addr); if Allocation_Maps.Has_Element (Pos) then if Addr = Old_Addr then Used_Slots.Update_Element (Pos, Update_Size'Access); else Used_Slots.Delete (Pos); Used_Slots.Insert (Addr, Slot); end if; else Used_Slots.Insert (Addr, Slot); end if; else Used_Slots.Insert (Addr, Slot); end if; Remove_Free (Addr, Slot.Size); end Probe_Realloc; -- ------------------------------ -- Insert in the frame tree the new stack frame represented by <tt>Pc</tt>. -- If the frame is already known, the frame reference counter is incremented. -- The frame represented by <tt>Pc</tt> is returned in <tt>Result</tt>. -- ------------------------------ procedure Create_Frame (Pc : in MAT.Frames.Frame_Table; Result : out MAT.Frames.Frame_Type) is begin MAT.Frames.Insert (Frames, Pc, Result); end Create_Frame; end Memory_Allocator; end MAT.Memory.Targets;
----------------------------------------------------------------------- -- Memory Events - Definition and Analysis of memory events -- Copyright (C) 2014 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Log.Loggers; with MAT.Memory.Readers; package body MAT.Memory.Targets is -- The logger Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("MAT.Memory.Targets"); -- ------------------------------ -- Initialize the target memory object to manage the memory slots, the stack frames -- and setup the reader to analyze the memory events. -- ------------------------------ procedure Initialize (Memory : in out Target_Memory; Reader : in out MAT.Readers.Manager_Base'Class) is Memory_Reader : constant MAT.Memory.Readers.Memory_Reader_Access := new MAT.Memory.Readers.Memory_Servant; begin Memory.Reader := Memory_Reader.all'Access; Memory_Reader.Data := Memory'Unrestricted_Access; Memory.Frames := Frames.Create_Root; MAT.Memory.Readers.Register (Reader, Memory_Reader); end Initialize; -- ------------------------------ -- Take into account a malloc probe. The memory slot [Addr .. Slot.Size] is inserted -- in the used slots map. The freed slots that intersect the malloc'ed region are -- removed from the freed map. -- ------------------------------ procedure Probe_Malloc (Memory : in out Target_Memory; Addr : in MAT.Types.Target_Addr; Slot : in Allocation) is begin Memory.Memory.Probe_Malloc (Addr, Slot); end Probe_Malloc; -- ------------------------------ -- Take into account a free probe. Add the memory slot in the freed map and remove -- the slot from the used slots map. -- ------------------------------ procedure Probe_Free (Memory : in out Target_Memory; Addr : in MAT.Types.Target_Addr; Slot : in Allocation) is begin Memory.Memory.Probe_Free (Addr, Slot); end Probe_Free; -- ------------------------------ -- Take into account a realloc probe. The old memory slot represented by Old_Addr is -- removed from the used slots maps and the new memory slot [Addr .. Slot.Size] is -- inserted in the used slots map. -- ------------------------------ procedure Probe_Realloc (Memory : in out Target_Memory; Addr : in MAT.Types.Target_Addr; Old_Addr : in MAT.Types.Target_Addr; Slot : in Allocation) is begin Memory.Memory.Probe_Realloc (Addr, Old_Addr, Slot); end Probe_Realloc; -- ------------------------------ -- Insert in the frame tree the new stack frame represented by <tt>Pc</tt>. -- If the frame is already known, the frame reference counter is incremented. -- The frame represented by <tt>Pc</tt> is returned in <tt>Result</tt>. -- ------------------------------ procedure Create_Frame (Memory : in out Target_Memory; Pc : in MAT.Frames.Frame_Table; Result : out MAT.Frames.Frame_Type) is begin Memory.Memory.Create_Frame (Pc, Result); end Create_Frame; -- ------------------------------ -- Collect the information about memory slot sizes allocated by the application. -- ------------------------------ procedure Size_Information (Memory : in Target_Memory; Sizes : in out Size_Info_Map) is Iter : Allocation_Cursor := Memory.Memory_Slots.First; procedure Update_Count (Size : in MAT.Types.Target_Size; Info : in out Size_Info_Type) is begin Info.Count := Info.Count + 1; end Update_Count; procedure Collect (Addr : in MAT.Types.Target_Addr; Slot : in Allocation) is Pos : Size_Info_Cursor := Sizes.Find (Slot.Size); begin if Size_Info_Maps.Has_Element (Pos) then Sizes.Update_Element (Pos, Update_Count'Access); else declare Info : Size_Info_Type; begin Info.Count := 1; Sizes.Insert (Slot.Size, Info); end; end if; end Collect; begin while Allocation_Maps.Has_Element (Iter) loop Allocation_Maps.Query_Element (Iter, Collect'Access); Allocation_Maps.Next (Iter); end loop; end Size_Information; protected body Memory_Allocator is -- ------------------------------ -- Remove the memory region [Addr .. Addr + Size] from the free list. -- ------------------------------ procedure Remove_Free (Addr : in MAT.Types.Target_Addr; Size : in MAT.Types.Target_Size) is Iter : Allocation_Cursor; Last : constant MAT.Types.Target_Addr := Addr + MAT.Types.Target_Addr (Size); Slot : Allocation; begin -- Walk the list of free blocks and remove all the blocks which intersect the region -- [Addr .. Addr + Slot.Size]. We start walking at the first block below and near -- the address. Slots are then removed when they intersect the malloc'ed region. Iter := Freed_Slots.Floor (Addr); while Allocation_Maps.Has_Element (Iter) loop declare Freed_Addr : constant MAT.Types.Target_Addr := Allocation_Maps.Key (Iter); begin exit when Freed_Addr > Last; Slot := Allocation_Maps.Element (Iter); if Freed_Addr + MAT.Types.Target_Addr (Slot.Size) > Addr then Freed_Slots.Delete (Iter); Iter := Freed_Slots.Floor (Addr); else Allocation_Maps.Next (Iter); end if; end; end loop; end Remove_Free; -- ------------------------------ -- Take into account a malloc probe. The memory slot [Addr .. Slot.Size] is inserted -- in the used slots map. The freed slots that intersect the malloc'ed region are -- removed from the freed map. -- ------------------------------ procedure Probe_Malloc (Addr : in MAT.Types.Target_Addr; Slot : in Allocation) is begin Remove_Free (Addr, Slot.Size); Used_Slots.Insert (Addr, Slot); end Probe_Malloc; -- ------------------------------ -- Take into account a free probe. Add the memory slot in the freed map and remove -- the slot from the used slots map. -- ------------------------------ procedure Probe_Free (Addr : in MAT.Types.Target_Addr; Slot : in Allocation) is Item : Allocation; Iter : Allocation_Cursor; begin Iter := Used_Slots.Find (Addr); if Allocation_Maps.Has_Element (Iter) then Item := Allocation_Maps.Element (Iter); MAT.Frames.Release (Item.Frame); Used_Slots.Delete (Iter); Item.Frame := Slot.Frame; Freed_Slots.Insert (Addr, Item); end if; end Probe_Free; -- ------------------------------ -- Take into account a realloc probe. The old memory slot represented by Old_Addr is -- removed from the used slots maps and the new memory slot [Addr .. Slot.Size] is -- inserted in the used slots map. -- ------------------------------ procedure Probe_Realloc (Addr : in MAT.Types.Target_Addr; Old_Addr : in MAT.Types.Target_Addr; Slot : in Allocation) is Old_Slot : Allocation; Pos : Allocation_Cursor; procedure Update_Size (Key : in MAT.Types.Target_Addr; Element : in out Allocation) is begin Element.Size := Slot.Size; MAT.Frames.Release (Element.Frame); Element.Frame := Slot.Frame; end Update_Size; begin if Old_Addr /= 0 then Pos := Used_Slots.Find (Old_Addr); if Allocation_Maps.Has_Element (Pos) then if Addr = Old_Addr then Used_Slots.Update_Element (Pos, Update_Size'Access); else Used_Slots.Delete (Pos); Used_Slots.Insert (Addr, Slot); end if; else Used_Slots.Insert (Addr, Slot); end if; else Used_Slots.Insert (Addr, Slot); end if; Remove_Free (Addr, Slot.Size); end Probe_Realloc; -- ------------------------------ -- Insert in the frame tree the new stack frame represented by <tt>Pc</tt>. -- If the frame is already known, the frame reference counter is incremented. -- The frame represented by <tt>Pc</tt> is returned in <tt>Result</tt>. -- ------------------------------ procedure Create_Frame (Pc : in MAT.Frames.Frame_Table; Result : out MAT.Frames.Frame_Type) is begin MAT.Frames.Insert (Frames, Pc, Result); end Create_Frame; end Memory_Allocator; end MAT.Memory.Targets;
Implement the Create_Frame procedure
Implement the Create_Frame procedure
Ada
apache-2.0
stcarrez/mat,stcarrez/mat,stcarrez/mat
84846294f1dfdf3c1a79d2bab14c5f244dc6ae4b
awa/plugins/awa-storages/src/awa-storages-beans.adb
awa/plugins/awa-storages/src/awa-storages-beans.adb
----------------------------------------------------------------------- -- awa-storages-beans -- Storage Ada Beans -- Copyright (C) 2012, 2013, 2016, 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.Containers; with Util.Log.Loggers; with Util.Strings; with ADO.Utils; with ADO.Queries; with ADO.Sessions; with ADO.Objects; with AWA.Permissions; with AWA.Helpers.Requests; with AWA.Services.Contexts; with AWA.Storages.Services; package body AWA.Storages.Beans is use Ada.Strings.Unbounded; use type ADO.Identifier; package ASC renames AWA.Services.Contexts; Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("AWA.Storages.Beans"); -- ------------------------------ -- Get the value identified by the name. -- ------------------------------ overriding function Get_Value (From : in Upload_Bean; Name : in String) return Util.Beans.Objects.Object is begin if Name = "folderId" then return ADO.Utils.To_Object (From.Folder_Id); elsif From.Is_Null then return Util.Beans.Objects.Null_Object; else return AWA.Storages.Models.Storage_Ref (From).Get_Value (Name); end if; end Get_Value; -- ------------------------------ -- Set the value identified by the name. -- ------------------------------ overriding procedure Set_Value (From : in out Upload_Bean; Name : in String; Value : in Util.Beans.Objects.Object) is Manager : constant Services.Storage_Service_Access := From.Module.Get_Storage_Manager; Folder : Models.Storage_Folder_Ref; Found : Boolean; Id : ADO.Identifier; begin if Name = "folderId" then From.Folder_Id := ADO.Utils.To_Identifier (Value); Manager.Load_Folder (Folder, From.Folder_Id); From.Set_Folder (Folder); elsif Name = "id" and then not Util.Beans.Objects.Is_Empty (Value) then Id := ADO.Utils.To_Identifier (Value); if Id /= ADO.NO_IDENTIFIER then Manager.Load_Storage (From, Id); end if; elsif Name = "name" then Folder := Models.Storage_Folder_Ref (From.Get_Folder); Manager.Load_Storage (From, From.Folder_Id, Util.Beans.Objects.To_String (Value), Found); if not Found then From.Set_Name (Util.Beans.Objects.To_String (Value)); end if; From.Set_Folder (Folder); end if; end Set_Value; -- ------------------------------ -- Save the uploaded file in the storage service. -- ------------------------------ procedure Save_Part (Bean : in out Upload_Bean; Part : in ASF.Parts.Part'Class) is Manager : constant Services.Storage_Service_Access := Bean.Module.Get_Storage_Manager; Name : constant String := Bean.Get_Name; begin if Name'Length = 0 then Bean.Set_Name (Part.Get_Name); end if; Bean.Set_Mime_Type (Part.Get_Content_Type); Bean.Set_File_Size (Part.Get_Size); if Part.Get_Size > 100_000 then Manager.Save (Bean, Part, AWA.Storages.Models.FILE); else Manager.Save (Bean, Part, AWA.Storages.Models.DATABASE); end if; exception when AWA.Permissions.NO_PERMISSION => Bean.Error := True; Log.Error ("Saving document is refused by the permission controller"); raise; when E : others => Bean.Error := True; Log.Error ("Exception when saving the document", E); raise; end Save_Part; -- ------------------------------ -- Upload the file. -- ------------------------------ procedure Upload (Bean : in out Upload_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is begin Outcome := To_Unbounded_String (if Bean.Error then "failure" else "success"); end Upload; -- ------------------------------ -- Delete the file. -- ------------------------------ procedure Delete (Bean : in out Upload_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is Manager : constant Services.Storage_Service_Access := Bean.Module.Get_Storage_Manager; begin Manager.Delete (Bean); Outcome := Ada.Strings.Unbounded.To_Unbounded_String ("success"); end Delete; -- ------------------------------ -- Publish the file. -- ------------------------------ overriding procedure Publish (Bean : in out Upload_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is Manager : constant Services.Storage_Service_Access := Bean.Module.Get_Storage_Manager; Id : constant ADO.Identifier := Helpers.Requests.Get_Parameter ("id"); Value : constant Util.Beans.Objects.Object := Helpers.Requests.Get_Parameter ("status"); begin Manager.Publish (Id, Util.Beans.Objects.To_Boolean (Value), Bean); Outcome := Ada.Strings.Unbounded.To_Unbounded_String ("success"); end Publish; -- ------------------------------ -- Create the Upload_Bean bean instance. -- ------------------------------ function Create_Upload_Bean (Module : in AWA.Storages.Modules.Storage_Module_Access) return Util.Beans.Basic.Readonly_Bean_Access is Result : constant Upload_Bean_Access := new Upload_Bean; begin Result.Module := Module; return Result.all'Access; end Create_Upload_Bean; -- ------------------------------ -- Get the value identified by the name. -- ------------------------------ overriding function Get_Value (From : in Folder_Bean; Name : in String) return Util.Beans.Objects.Object is begin if ADO.Objects.Is_Null (From) then return Util.Beans.Objects.Null_Object; else return AWA.Storages.Models.Storage_Folder_Ref (From).Get_Value (Name); end if; end Get_Value; -- ------------------------------ -- Set the value identified by the name. -- ------------------------------ overriding procedure Set_Value (From : in out Folder_Bean; Name : in String; Value : in Util.Beans.Objects.Object) is begin if Name = "name" then From.Set_Name (Util.Beans.Objects.To_String (Value)); end if; end Set_Value; -- ------------------------------ -- Create or save the folder. -- ------------------------------ procedure Save (Bean : in out Folder_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is Manager : constant Services.Storage_Service_Access := Bean.Module.Get_Storage_Manager; begin Manager.Save_Folder (Bean); Outcome := Ada.Strings.Unbounded.To_Unbounded_String ("success"); end Save; -- ------------------------------ -- Load the folder instance. -- ------------------------------ procedure Load_Folder (Storage : in out Storage_List_Bean) is use AWA.Storages.Models; use type Ada.Containers.Count_Type; Manager : constant Services.Storage_Service_Access := Storage.Module.Get_Storage_Manager; begin if Storage.Folder_Id /= ADO.NO_IDENTIFIER then Manager.Load_Folder (Storage.Folder_Bean.all, Storage.Folder_Id); elsif Storage.Folder_List.List.Length > 0 then Manager.Load_Folder (Storage.Folder_Bean.all, Storage.Folder_List.List.Element (1).Id); end if; Storage.Flags (INIT_FOLDER) := True; end Load_Folder; -- ------------------------------ -- Load the list of folders. -- ------------------------------ procedure Load_Folders (Storage : in out Storage_List_Bean) is use AWA.Storages.Models; use AWA.Services; Ctx : constant Contexts.Service_Context_Access := AWA.Services.Contexts.Current; User : constant ADO.Identifier := Ctx.Get_User_Identifier; Session : ADO.Sessions.Session := ASC.Get_Session (Ctx); Query : ADO.Queries.Context; begin Query.Set_Query (AWA.Storages.Models.Query_Storage_Folder_List); Query.Bind_Param ("user_id", User); AWA.Storages.Models.List (Storage.Folder_List_Bean.all, Session, Query); Storage.Flags (INIT_FOLDER_LIST) := True; end Load_Folders; -- ------------------------------ -- Load the list of files associated with the current folder. -- ------------------------------ procedure Load_Files (Storage : in out Storage_List_Bean) is use AWA.Storages.Models; use AWA.Services; Ctx : constant Contexts.Service_Context_Access := AWA.Services.Contexts.Current; User : constant ADO.Identifier := Ctx.Get_User_Identifier; Session : ADO.Sessions.Session := ASC.Get_Session (Ctx); Query : ADO.Queries.Context; begin if not Storage.Init_Flags (INIT_FOLDER) then Load_Folder (Storage); end if; Query.Set_Query (AWA.Storages.Models.Query_Storage_List); Query.Bind_Param ("user_id", User); if Storage.Folder_Bean.Is_Null then Query.Bind_Null_Param ("folder_id"); else Query.Bind_Param ("folder_id", Storage.Folder_Bean.Get_Id); end if; AWA.Storages.Models.List (Storage.Files_List_Bean.all, Session, Query); Storage.Flags (INIT_FILE_LIST) := True; end Load_Files; -- ------------------------------ -- Set the value identified by the name. -- ------------------------------ overriding procedure Set_Value (From : in out Storage_List_Bean; Name : in String; Value : in Util.Beans.Objects.Object) is begin if Name = "folderId" and not Util.Beans.Objects.Is_Empty (Value) then From.Folder_Id := ADO.Utils.To_Identifier (Value); end if; end Set_Value; overriding function Get_Value (List : in Storage_List_Bean; Name : in String) return Util.Beans.Objects.Object is begin if Name = "files" then return Util.Beans.Objects.To_Object (Value => List.Files_List_Bean, Storage => Util.Beans.Objects.STATIC); elsif Name = "folders" then return Util.Beans.Objects.To_Object (Value => List.Folder_List_Bean, Storage => Util.Beans.Objects.STATIC); elsif Name = "folder" then if List.Folder_Bean.Is_Null then return Util.Beans.Objects.Null_Object; end if; return Util.Beans.Objects.To_Object (Value => List.Folder_Bean, Storage => Util.Beans.Objects.STATIC); else return Util.Beans.Objects.Null_Object; end if; end Get_Value; -- ------------------------------ -- Load the files and folder information. -- ------------------------------ overriding procedure Load (List : in out Storage_List_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is pragma Unreferenced (Outcome); begin Storage_List_Bean'Class (List).Load_Folders; Storage_List_Bean'Class (List).Load_Folder; Storage_List_Bean'Class (List).Load_Files; end Load; -- ------------------------------ -- Create the Folder_List_Bean bean instance. -- ------------------------------ function Create_Folder_List_Bean (Module : in AWA.Storages.Modules.Storage_Module_Access) return Util.Beans.Basic.Readonly_Bean_Access is pragma Unreferenced (Module); use AWA.Storages.Models; use AWA.Services; Ctx : constant Contexts.Service_Context_Access := AWA.Services.Contexts.Current; User : constant ADO.Identifier := Ctx.Get_User_Identifier; Object : constant Folder_Info_List_Bean_Access := new Folder_Info_List_Bean; Session : ADO.Sessions.Session := ASC.Get_Session (Ctx); Query : ADO.Queries.Context; begin Query.Set_Query (AWA.Storages.Models.Query_Storage_Folder_List); Query.Bind_Param ("user_id", User); AWA.Storages.Models.List (Object.all, Session, Query); return Object.all'Access; end Create_Folder_List_Bean; -- ------------------------------ -- Create the Storage_List_Bean bean instance. -- ------------------------------ function Create_Storage_List_Bean (Module : in AWA.Storages.Modules.Storage_Module_Access) return Util.Beans.Basic.Readonly_Bean_Access is Object : constant Storage_List_Bean_Access := new Storage_List_Bean; begin Object.Module := Module; Object.Folder_Bean := Object.Folder'Access; Object.Folder_List_Bean := Object.Folder_List'Access; Object.Files_List_Bean := Object.Files_List'Access; Object.Flags := Object.Init_Flags'Access; return Object.all'Access; end Create_Storage_List_Bean; -- ------------------------------ -- Returns true if the given mime type can be displayed by a browser. -- Mime types: application/pdf, text/*, image/* -- ------------------------------ function Is_Browser_Visible (Mime_Type : in String) return Boolean is begin if Mime_Type = "application/pdf" then return True; end if; if Util.Strings.Starts_With (Mime_Type, Prefix => "text/") then return True; end if; if Util.Strings.Starts_With (Mime_Type, Prefix => "image/") then return True; end if; return False; end Is_Browser_Visible; overriding function Get_Value (From : in Storage_Bean; Name : in String) return Util.Beans.Objects.Object is begin if Name = "isBrowserVisible" then return Util.Beans.Objects.To_Object (Is_Browser_Visible (To_String (From.Mime_Type))); else return AWA.Storages.Models.Storage_Bean (From).Get_Value (Name); end if; end Get_Value; overriding procedure Load (Into : in out Storage_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is Ctx : constant ASC.Service_Context_Access := ASC.Current; User : constant ADO.Identifier := Ctx.Get_User_Identifier; Session : ADO.Sessions.Session := ASC.Get_Session (Ctx); Query : ADO.Queries.Context; begin if Into.Id = ADO.NO_IDENTIFIER then Outcome := Ada.Strings.Unbounded.To_Unbounded_String ("not-found"); return; end if; -- Get the image information. Query.Set_Query (AWA.Storages.Models.Query_Storage_Info); Query.Bind_Param (Name => "user_id", Value => User); Query.Bind_Param (Name => "file_id", Value => Into.Id); Into.Load (Session, Query); exception when ADO.Objects.NOT_FOUND => Outcome := Ada.Strings.Unbounded.To_Unbounded_String ("not-found"); end Load; -- ------------------------------ -- Create the Storage_Bean bean instance. -- ------------------------------ function Create_Storage_Bean (Module : in AWA.Storages.Modules.Storage_Module_Access) return Util.Beans.Basic.Readonly_Bean_Access is Object : constant Storage_Bean_Access := new Storage_Bean; begin Object.Module := Module; Object.Id := ADO.NO_IDENTIFIER; return Object.all'Access; end Create_Storage_Bean; end AWA.Storages.Beans;
----------------------------------------------------------------------- -- awa-storages-beans -- Storage Ada Beans -- Copyright (C) 2012, 2013, 2016, 2018, 2019, 2020 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Containers; with Util.Log.Loggers; with Util.Strings; with ADO.Utils; with ADO.Queries; with ADO.Sessions; with ADO.Objects; with AWA.Permissions; with AWA.Helpers.Requests; with AWA.Services.Contexts; with AWA.Storages.Services; package body AWA.Storages.Beans is use Ada.Strings.Unbounded; use type ADO.Identifier; package ASC renames AWA.Services.Contexts; Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("AWA.Storages.Beans"); -- ------------------------------ -- Get the value identified by the name. -- ------------------------------ overriding function Get_Value (From : in Upload_Bean; Name : in String) return Util.Beans.Objects.Object is begin if Name = "folderId" then return ADO.Utils.To_Object (From.Folder_Id); elsif From.Is_Null then return Util.Beans.Objects.Null_Object; else return AWA.Storages.Models.Storage_Ref (From).Get_Value (Name); end if; end Get_Value; -- ------------------------------ -- Set the value identified by the name. -- ------------------------------ overriding procedure Set_Value (From : in out Upload_Bean; Name : in String; Value : in Util.Beans.Objects.Object) is Manager : constant Services.Storage_Service_Access := From.Module.Get_Storage_Manager; Folder : Models.Storage_Folder_Ref; Found : Boolean; Id : ADO.Identifier; begin if Name = "folderId" then From.Folder_Id := ADO.Utils.To_Identifier (Value); Manager.Load_Folder (Folder, From.Folder_Id); From.Set_Folder (Folder); elsif Name = "id" and then not Util.Beans.Objects.Is_Empty (Value) then Id := ADO.Utils.To_Identifier (Value); if Id /= ADO.NO_IDENTIFIER then Manager.Load_Storage (From, Id); end if; elsif Name = "name" then Folder := Models.Storage_Folder_Ref (From.Get_Folder); Manager.Load_Storage (From, From.Folder_Id, Util.Beans.Objects.To_String (Value), Found); if not Found then From.Set_Name (Util.Beans.Objects.To_String (Value)); end if; From.Set_Folder (Folder); end if; end Set_Value; -- ------------------------------ -- Save the uploaded file in the storage service. -- ------------------------------ procedure Save_Part (Bean : in out Upload_Bean; Part : in ASF.Parts.Part'Class) is Manager : constant Services.Storage_Service_Access := Bean.Module.Get_Storage_Manager; Name : constant String := Bean.Get_Name; begin if Name'Length = 0 then Bean.Set_Name (Part.Get_Name); end if; Bean.Set_Mime_Type (Part.Get_Content_Type); Bean.Set_File_Size (Part.Get_Size); Manager.Save (Bean, Part); exception when AWA.Permissions.NO_PERMISSION => Bean.Error := True; Log.Error ("Saving document is refused by the permission controller"); raise; when E : others => Bean.Error := True; Log.Error ("Exception when saving the document", E); raise; end Save_Part; -- ------------------------------ -- Upload the file. -- ------------------------------ procedure Upload (Bean : in out Upload_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is begin Outcome := To_Unbounded_String (if Bean.Error then "failure" else "success"); end Upload; -- ------------------------------ -- Delete the file. -- ------------------------------ procedure Delete (Bean : in out Upload_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is Manager : constant Services.Storage_Service_Access := Bean.Module.Get_Storage_Manager; begin Manager.Delete (Bean); Outcome := Ada.Strings.Unbounded.To_Unbounded_String ("success"); end Delete; -- ------------------------------ -- Publish the file. -- ------------------------------ overriding procedure Publish (Bean : in out Upload_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is Manager : constant Services.Storage_Service_Access := Bean.Module.Get_Storage_Manager; Id : constant ADO.Identifier := Helpers.Requests.Get_Parameter ("id"); Value : constant Util.Beans.Objects.Object := Helpers.Requests.Get_Parameter ("status"); begin Manager.Publish (Id, Util.Beans.Objects.To_Boolean (Value), Bean); Outcome := Ada.Strings.Unbounded.To_Unbounded_String ("success"); end Publish; -- ------------------------------ -- Create the Upload_Bean bean instance. -- ------------------------------ function Create_Upload_Bean (Module : in AWA.Storages.Modules.Storage_Module_Access) return Util.Beans.Basic.Readonly_Bean_Access is Result : constant Upload_Bean_Access := new Upload_Bean; begin Result.Module := Module; return Result.all'Access; end Create_Upload_Bean; -- ------------------------------ -- Get the value identified by the name. -- ------------------------------ overriding function Get_Value (From : in Folder_Bean; Name : in String) return Util.Beans.Objects.Object is begin if ADO.Objects.Is_Null (From) then return Util.Beans.Objects.Null_Object; else return AWA.Storages.Models.Storage_Folder_Ref (From).Get_Value (Name); end if; end Get_Value; -- ------------------------------ -- Set the value identified by the name. -- ------------------------------ overriding procedure Set_Value (From : in out Folder_Bean; Name : in String; Value : in Util.Beans.Objects.Object) is begin if Name = "name" then From.Set_Name (Util.Beans.Objects.To_String (Value)); end if; end Set_Value; -- ------------------------------ -- Create or save the folder. -- ------------------------------ procedure Save (Bean : in out Folder_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is Manager : constant Services.Storage_Service_Access := Bean.Module.Get_Storage_Manager; begin Manager.Save_Folder (Bean); Outcome := Ada.Strings.Unbounded.To_Unbounded_String ("success"); end Save; -- ------------------------------ -- Load the folder instance. -- ------------------------------ procedure Load_Folder (Storage : in out Storage_List_Bean) is use AWA.Storages.Models; use type Ada.Containers.Count_Type; Manager : constant Services.Storage_Service_Access := Storage.Module.Get_Storage_Manager; begin if Storage.Folder_Id /= ADO.NO_IDENTIFIER then Manager.Load_Folder (Storage.Folder_Bean.all, Storage.Folder_Id); elsif Storage.Folder_List.List.Length > 0 then Manager.Load_Folder (Storage.Folder_Bean.all, Storage.Folder_List.List.Element (1).Id); end if; Storage.Flags (INIT_FOLDER) := True; end Load_Folder; -- ------------------------------ -- Load the list of folders. -- ------------------------------ procedure Load_Folders (Storage : in out Storage_List_Bean) is use AWA.Storages.Models; use AWA.Services; Ctx : constant Contexts.Service_Context_Access := AWA.Services.Contexts.Current; User : constant ADO.Identifier := Ctx.Get_User_Identifier; Session : ADO.Sessions.Session := ASC.Get_Session (Ctx); Query : ADO.Queries.Context; begin Query.Set_Query (AWA.Storages.Models.Query_Storage_Folder_List); Query.Bind_Param ("user_id", User); AWA.Storages.Models.List (Storage.Folder_List_Bean.all, Session, Query); Storage.Flags (INIT_FOLDER_LIST) := True; end Load_Folders; -- ------------------------------ -- Load the list of files associated with the current folder. -- ------------------------------ procedure Load_Files (Storage : in out Storage_List_Bean) is use AWA.Storages.Models; use AWA.Services; Ctx : constant Contexts.Service_Context_Access := AWA.Services.Contexts.Current; User : constant ADO.Identifier := Ctx.Get_User_Identifier; Session : ADO.Sessions.Session := ASC.Get_Session (Ctx); Query : ADO.Queries.Context; begin if not Storage.Init_Flags (INIT_FOLDER) then Load_Folder (Storage); end if; Query.Set_Query (AWA.Storages.Models.Query_Storage_List); Query.Bind_Param ("user_id", User); if Storage.Folder_Bean.Is_Null then Query.Bind_Null_Param ("folder_id"); else Query.Bind_Param ("folder_id", Storage.Folder_Bean.Get_Id); end if; AWA.Storages.Models.List (Storage.Files_List_Bean.all, Session, Query); Storage.Flags (INIT_FILE_LIST) := True; end Load_Files; -- ------------------------------ -- Set the value identified by the name. -- ------------------------------ overriding procedure Set_Value (From : in out Storage_List_Bean; Name : in String; Value : in Util.Beans.Objects.Object) is begin if Name = "folderId" and not Util.Beans.Objects.Is_Empty (Value) then From.Folder_Id := ADO.Utils.To_Identifier (Value); end if; end Set_Value; overriding function Get_Value (List : in Storage_List_Bean; Name : in String) return Util.Beans.Objects.Object is begin if Name = "files" then return Util.Beans.Objects.To_Object (Value => List.Files_List_Bean, Storage => Util.Beans.Objects.STATIC); elsif Name = "folders" then return Util.Beans.Objects.To_Object (Value => List.Folder_List_Bean, Storage => Util.Beans.Objects.STATIC); elsif Name = "folder" then if List.Folder_Bean.Is_Null then return Util.Beans.Objects.Null_Object; end if; return Util.Beans.Objects.To_Object (Value => List.Folder_Bean, Storage => Util.Beans.Objects.STATIC); else return Util.Beans.Objects.Null_Object; end if; end Get_Value; -- ------------------------------ -- Load the files and folder information. -- ------------------------------ overriding procedure Load (List : in out Storage_List_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is pragma Unreferenced (Outcome); begin Storage_List_Bean'Class (List).Load_Folders; Storage_List_Bean'Class (List).Load_Folder; Storage_List_Bean'Class (List).Load_Files; end Load; -- ------------------------------ -- Create the Folder_List_Bean bean instance. -- ------------------------------ function Create_Folder_List_Bean (Module : in AWA.Storages.Modules.Storage_Module_Access) return Util.Beans.Basic.Readonly_Bean_Access is pragma Unreferenced (Module); use AWA.Storages.Models; use AWA.Services; Ctx : constant Contexts.Service_Context_Access := AWA.Services.Contexts.Current; User : constant ADO.Identifier := Ctx.Get_User_Identifier; Object : constant Folder_Info_List_Bean_Access := new Folder_Info_List_Bean; Session : ADO.Sessions.Session := ASC.Get_Session (Ctx); Query : ADO.Queries.Context; begin Query.Set_Query (AWA.Storages.Models.Query_Storage_Folder_List); Query.Bind_Param ("user_id", User); AWA.Storages.Models.List (Object.all, Session, Query); return Object.all'Access; end Create_Folder_List_Bean; -- ------------------------------ -- Create the Storage_List_Bean bean instance. -- ------------------------------ function Create_Storage_List_Bean (Module : in AWA.Storages.Modules.Storage_Module_Access) return Util.Beans.Basic.Readonly_Bean_Access is Object : constant Storage_List_Bean_Access := new Storage_List_Bean; begin Object.Module := Module; Object.Folder_Bean := Object.Folder'Access; Object.Folder_List_Bean := Object.Folder_List'Access; Object.Files_List_Bean := Object.Files_List'Access; Object.Flags := Object.Init_Flags'Access; return Object.all'Access; end Create_Storage_List_Bean; -- ------------------------------ -- Returns true if the given mime type can be displayed by a browser. -- Mime types: application/pdf, text/*, image/* -- ------------------------------ function Is_Browser_Visible (Mime_Type : in String) return Boolean is begin if Mime_Type = "application/pdf" then return True; end if; if Util.Strings.Starts_With (Mime_Type, Prefix => "text/") then return True; end if; if Util.Strings.Starts_With (Mime_Type, Prefix => "image/") then return True; end if; return False; end Is_Browser_Visible; overriding function Get_Value (From : in Storage_Bean; Name : in String) return Util.Beans.Objects.Object is begin if Name = "isBrowserVisible" then return Util.Beans.Objects.To_Object (Is_Browser_Visible (To_String (From.Mime_Type))); else return AWA.Storages.Models.Storage_Bean (From).Get_Value (Name); end if; end Get_Value; overriding procedure Load (Into : in out Storage_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is Ctx : constant ASC.Service_Context_Access := ASC.Current; User : constant ADO.Identifier := Ctx.Get_User_Identifier; Session : ADO.Sessions.Session := ASC.Get_Session (Ctx); Query : ADO.Queries.Context; begin if Into.Id = ADO.NO_IDENTIFIER then Outcome := Ada.Strings.Unbounded.To_Unbounded_String ("not-found"); return; end if; -- Get the image information. Query.Set_Query (AWA.Storages.Models.Query_Storage_Info); Query.Bind_Param (Name => "user_id", Value => User); Query.Bind_Param (Name => "file_id", Value => Into.Id); Into.Load (Session, Query); exception when ADO.Objects.NOT_FOUND => Outcome := Ada.Strings.Unbounded.To_Unbounded_String ("not-found"); end Load; -- ------------------------------ -- Create the Storage_Bean bean instance. -- ------------------------------ function Create_Storage_Bean (Module : in AWA.Storages.Modules.Storage_Module_Access) return Util.Beans.Basic.Readonly_Bean_Access is Object : constant Storage_Bean_Access := new Storage_Bean; begin Object.Module := Module; Object.Id := ADO.NO_IDENTIFIER; return Object.all'Access; end Create_Storage_Bean; end AWA.Storages.Beans;
Update the Save procedure to let the storage service choose the storage type
Update the Save procedure to let the storage service choose the storage type
Ada
apache-2.0
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
6e220cb71fc974496863812aeb688e442a69f179
src/wiki.ads
src/wiki.ads
----------------------------------------------------------------------- -- wiki -- Ada Wiki Engine -- Copyright (C) 2015, 2016 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- package Wiki is pragma Preelaborate; -- Defines the possible wiki syntax supported by the parser. type Wiki_Syntax is ( -- Google wiki syntax http://code.google.com/p/support/wiki/WikiSyntax SYNTAX_GOOGLE, -- Creole wiki syntax http://www.wikicreole.org/wiki/Creole1.0 SYNTAX_CREOLE, -- Dotclear syntax http://dotclear.org/documentation/2.0/usage/syntaxes SYNTAX_DOTCLEAR, -- PhpBB syntax http://wiki.phpbb.com/Help:Formatting SYNTAX_PHPBB, -- MediaWiki syntax http://www.mediawiki.org/wiki/Help:Formatting SYNTAX_MEDIA_WIKI, -- Markdown SYNTAX_MARKDOWN, -- A mix of the above SYNTAX_MIX, -- The input is plain possibly incorrect HTML. SYNTAX_HTML); type Format_Type is (BOLD, ITALIC, CODE, SUPERSCRIPT, SUBSCRIPT, STRIKEOUT, PREFORMAT); type Format_Map is array (Format_Type) of Boolean; -- The possible HTML tags as described in HTML5 specification. type Html_Tag is ( -- Section 4.1 The root element ROOT_HTML_TAG, -- Section 4.2 Document metadata HEAD_TAG, TITLE_TAG, BASE_TAG, LINK_TAG, META_TAG, STYLE_TAG, -- Section 4.3 Sections BODY_TAG, ARTICLE_TAG, SECTION_TAG, NAV_TAG, ASIDE_TAG, H1_TAG, H2_TAG, H3_TAG, H4_TAG, H5_TAG, H6_TAG, HEADER_TAG, FOOTER_TAG, ADDRESS_TAG, -- Section 4.4 Grouping content P_TAG, HR_TAG, PRE_TAG, BLOCKQUOTE_TAG, OL_TAG, UL_TAG, LI_TAG, DL_TAG, DT_TAG, DD_TAG, FIGURE_TAG, FIGCAPTION_TAG, DIV_TAG, MAIN_TAG, -- Section 4.5 Text-level semantics A_TAG, EM_TAG, STRONG_TAG, SMALL_TAG, S_TAG, CITE_TAG, Q_TAG, DFN_TAG, ABBR_TAG, DATA_TAG, TIME_TAG, CODE_TAG, VAR_TAG, SAMP_TAG, KBD_TAG, SUB_TAG, SUP_TAG, I_TAG, B_TAG, U_TAG, MARK_TAG, RUBY_TAG, RB_TAG, RT_TAG, RTC_TAG, RP_TAG, BDI_TAG, BDO_TAG, SPAN_TAG, BR_TAG, WBR_TAG, -- Section 4.6 Edits INS_TAG, DEL_TAG, -- Section 4.7 Embedded content IMG_TAG, IFRAME_TAG, EMBED_TAG, OBJECT_TAG, PARAM_TAG, VIDEO_TAG, AUDIO_TAG, SOURCE_TAG, TRACK_TAG, MAP_TAG, AREA_TAG, -- Section 4.9 Tabular data TABLE_TAG, CAPTION_TAG, COLGROUP_TAG, COL_TAG, TBODY_TAG, THEAD_TAG, TFOOT_TAG, TR_TAG, TD_TAG, TH_TAG, -- Section 4.10 Forms FORM_TAG, LABEL_TAG, INPUT_TAG, BUTTON_TAG, SELECT_TAG, DATALIST_TAG, OPTGROUP_TAG, OPTION_TAG, TEXTAREA_TAG, KEYGEN_TAG, OUTPUT_TAG, PROGRESS_TAG, METER_TAG, FIELDSET_TAG, LEGEND_TAG, -- Section 4.11 Scripting SCRIPT_TAG, NOSCRIPT_TAG, TEMPLATE_TAG, CANVAS_TAG, -- Unknown tags UNKNOWN_TAG ); -- Find the tag from the tag name. function Find_Tag (Name : in Wide_Wide_String) return Html_Tag; type String_Access is access constant String; -- Get the HTML tag name. function Get_Tag_Name (Tag : in Html_Tag) return String_Access; type Tag_Boolean_Array is array (Html_Tag) of Boolean; No_End_Tag : constant Tag_Boolean_Array := ( BASE_TAG => True, LINK_TAG => True, META_TAG => True, IMG_TAG => True, HR_TAG => True, BR_TAG => True, WBR_TAG => True, INPUT_TAG => True, KEYGEN_TAG => True, others => False); Tag_Omission : constant Tag_Boolean_Array := ( -- Section 4.4 Grouping content LI_TAG => True, DT_TAG => True, DD_TAG => True, -- Section 4.5 Text-level semantics RB_TAG => True, RT_TAG => True, RTC_TAG => True, RP_TAG => True, -- Section 4.9 Tabular data TH_TAG => True, TD_TAG => True, TR_TAG => True, TBODY_TAG => True, THEAD_TAG => True, TFOOT_TAG => True, OPTGROUP_TAG => True, OPTION_TAG => True, others => False); end Wiki;
----------------------------------------------------------------------- -- wiki -- Ada Wiki Engine -- Copyright (C) 2015, 2016 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- -- == Wiki == -- -- @include wiki-documents.ads -- @include wiki-attributes.ads -- @include wiki-parsers.ads package Wiki is pragma Preelaborate; -- Defines the possible wiki syntax supported by the parser. type Wiki_Syntax is ( -- Google wiki syntax http://code.google.com/p/support/wiki/WikiSyntax SYNTAX_GOOGLE, -- Creole wiki syntax http://www.wikicreole.org/wiki/Creole1.0 SYNTAX_CREOLE, -- Dotclear syntax http://dotclear.org/documentation/2.0/usage/syntaxes SYNTAX_DOTCLEAR, -- PhpBB syntax http://wiki.phpbb.com/Help:Formatting SYNTAX_PHPBB, -- MediaWiki syntax http://www.mediawiki.org/wiki/Help:Formatting SYNTAX_MEDIA_WIKI, -- Markdown SYNTAX_MARKDOWN, -- A mix of the above SYNTAX_MIX, -- The input is plain possibly incorrect HTML. SYNTAX_HTML); -- Defines the possible text formats. type Format_Type is (BOLD, ITALIC, CODE, SUPERSCRIPT, SUBSCRIPT, STRIKEOUT, PREFORMAT); type Format_Map is array (Format_Type) of Boolean; -- The possible HTML tags as described in HTML5 specification. type Html_Tag is ( -- Section 4.1 The root element ROOT_HTML_TAG, -- Section 4.2 Document metadata HEAD_TAG, TITLE_TAG, BASE_TAG, LINK_TAG, META_TAG, STYLE_TAG, -- Section 4.3 Sections BODY_TAG, ARTICLE_TAG, SECTION_TAG, NAV_TAG, ASIDE_TAG, H1_TAG, H2_TAG, H3_TAG, H4_TAG, H5_TAG, H6_TAG, HEADER_TAG, FOOTER_TAG, ADDRESS_TAG, -- Section 4.4 Grouping content P_TAG, HR_TAG, PRE_TAG, BLOCKQUOTE_TAG, OL_TAG, UL_TAG, LI_TAG, DL_TAG, DT_TAG, DD_TAG, FIGURE_TAG, FIGCAPTION_TAG, DIV_TAG, MAIN_TAG, -- Section 4.5 Text-level semantics A_TAG, EM_TAG, STRONG_TAG, SMALL_TAG, S_TAG, CITE_TAG, Q_TAG, DFN_TAG, ABBR_TAG, DATA_TAG, TIME_TAG, CODE_TAG, VAR_TAG, SAMP_TAG, KBD_TAG, SUB_TAG, SUP_TAG, I_TAG, B_TAG, U_TAG, MARK_TAG, RUBY_TAG, RB_TAG, RT_TAG, RTC_TAG, RP_TAG, BDI_TAG, BDO_TAG, SPAN_TAG, BR_TAG, WBR_TAG, -- Section 4.6 Edits INS_TAG, DEL_TAG, -- Section 4.7 Embedded content IMG_TAG, IFRAME_TAG, EMBED_TAG, OBJECT_TAG, PARAM_TAG, VIDEO_TAG, AUDIO_TAG, SOURCE_TAG, TRACK_TAG, MAP_TAG, AREA_TAG, -- Section 4.9 Tabular data TABLE_TAG, CAPTION_TAG, COLGROUP_TAG, COL_TAG, TBODY_TAG, THEAD_TAG, TFOOT_TAG, TR_TAG, TD_TAG, TH_TAG, -- Section 4.10 Forms FORM_TAG, LABEL_TAG, INPUT_TAG, BUTTON_TAG, SELECT_TAG, DATALIST_TAG, OPTGROUP_TAG, OPTION_TAG, TEXTAREA_TAG, KEYGEN_TAG, OUTPUT_TAG, PROGRESS_TAG, METER_TAG, FIELDSET_TAG, LEGEND_TAG, -- Section 4.11 Scripting SCRIPT_TAG, NOSCRIPT_TAG, TEMPLATE_TAG, CANVAS_TAG, -- Unknown tags UNKNOWN_TAG ); -- Find the tag from the tag name. function Find_Tag (Name : in Wide_Wide_String) return Html_Tag; type String_Access is access constant String; -- Get the HTML tag name. function Get_Tag_Name (Tag : in Html_Tag) return String_Access; type Tag_Boolean_Array is array (Html_Tag) of Boolean; No_End_Tag : constant Tag_Boolean_Array := ( BASE_TAG => True, LINK_TAG => True, META_TAG => True, IMG_TAG => True, HR_TAG => True, BR_TAG => True, WBR_TAG => True, INPUT_TAG => True, KEYGEN_TAG => True, others => False); Tag_Omission : constant Tag_Boolean_Array := ( -- Section 4.4 Grouping content LI_TAG => True, DT_TAG => True, DD_TAG => True, -- Section 4.5 Text-level semantics RB_TAG => True, RT_TAG => True, RTC_TAG => True, RP_TAG => True, -- Section 4.9 Tabular data TH_TAG => True, TD_TAG => True, TR_TAG => True, TBODY_TAG => True, THEAD_TAG => True, TFOOT_TAG => True, OPTGROUP_TAG => True, OPTION_TAG => True, others => False); end Wiki;
Add some documentation
Add some documentation
Ada
apache-2.0
stcarrez/ada-wiki,stcarrez/ada-wiki
b18dd5087ebcfb30bf2c74d31b8f1a59b56bd1b8
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; with Wiki.Render.Links; -- == 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 Wiki.Render.Links.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); -- Get the current section number. function Get_Section_Number (Engine : in Html_Renderer; Prefix : in Wiki.Strings.WString; Separator : in Wiki.Strings.WChar) return Wiki.Strings.WString; -- 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 Toc_Number_Array is array (1 .. 6) of Natural; type List_Style_Array is array (1 .. 32) of Boolean; Default_Links : aliased Wiki.Render.Links.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 : Wiki.Render.Links.Link_Renderer_Access := Default_Links'Access; Has_Paragraph : Boolean := False; Need_Paragraph : Boolean := False; Has_Item : Boolean := False; Enable_Render_TOC : Boolean := False; TOC_Rendered : Boolean := False; Current_Level : Natural := 0; List_Styles : List_Style_Array := (others => False); Quote_Level : Natural := 0; Html_Level : Natural := 0; Current_Section : Toc_Number_Array := (others => 0); Section_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; Doc : in Wiki.Documents.Document; 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; with Wiki.Render.Links; -- == HTML Renderer == -- The <tt>Html_Renderer</tt> allows to render a wiki document into an HTML content. -- 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 Wiki.Render.Links.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); -- Get the current section number. function Get_Section_Number (Engine : in Html_Renderer; Prefix : in Wiki.Strings.WString; Separator : in Wiki.Strings.WChar) return Wiki.Strings.WString; -- 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 Toc_Number_Array is array (1 .. 6) of Natural; type List_Style_Array is array (1 .. 32) of Boolean; Default_Links : aliased Wiki.Render.Links.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 : Wiki.Render.Links.Link_Renderer_Access := Default_Links'Access; Has_Paragraph : Boolean := False; Need_Paragraph : Boolean := False; Has_Item : Boolean := False; Enable_Render_TOC : Boolean := False; TOC_Rendered : Boolean := False; Current_Level : Natural := 0; List_Styles : List_Style_Array := (others => False); Quote_Level : Natural := 0; Html_Level : Natural := 0; Current_Section : Toc_Number_Array := (others => 0); Section_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; Doc : in Wiki.Documents.Document; 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;
Fix style and documentation
Fix style and documentation
Ada
apache-2.0
stcarrez/ada-wiki,stcarrez/ada-wiki
d5bb2b64145fe0515c604b808d5385641600160a
src/wiki-render-text.adb
src/wiki-render-text.adb
----------------------------------------------------------------------- -- wiki-render-text -- Wiki Text renderer -- Copyright (C) 2011, 2012, 2013, 2015, 2016, 2018, 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 Wiki.Helpers; with Util.Strings; package body Wiki.Render.Text is -- ------------------------------ -- Set the output writer. -- ------------------------------ procedure Set_Output_Stream (Engine : in out Text_Renderer; Stream : in Streams.Output_Stream_Access) is begin Engine.Output := Stream; end Set_Output_Stream; -- ------------------------------ -- Set the no-newline mode to produce a single line text (disabled by default). -- ------------------------------ procedure Set_No_Newline (Engine : in out Text_Renderer; Enable : in Boolean) is begin Engine.No_Newline := Enable; end Set_No_Newline; -- ------------------------------ -- Emit a new line. -- ------------------------------ procedure New_Line (Document : in out Text_Renderer) is begin if not Document.No_Newline then Document.Output.Write (Wiki.Helpers.LF); end if; Document.Empty_Line := True; end New_Line; -- ------------------------------ -- Add a line break (<br>). -- ------------------------------ procedure Add_Line_Break (Document : in out Text_Renderer) is begin if not Document.No_Newline then Document.Output.Write (Wiki.Helpers.LF); end if; Document.Empty_Line := True; Document.Current_Indent := 0; end Add_Line_Break; -- ------------------------------ -- Render a blockquote (<blockquote>). The level indicates the blockquote nested level. -- The blockquote must be closed at the next header. -- ------------------------------ procedure Render_Blockquote (Engine : in out Text_Renderer; Level : in Natural) is begin Engine.Close_Paragraph; for I in 1 .. Level loop Engine.Output.Write (" "); end loop; end Render_Blockquote; procedure Render_List_Start (Engine : in out Text_Renderer; Tag : in String; Level : in Natural) is begin if not Engine.Empty_Line then Engine.Add_Line_Break; end if; Engine.Need_Paragraph := False; Engine.Open_Paragraph; if not Engine.No_Newline then Engine.Output.Write (Wiki.Helpers.LF); end if; Engine.List_Index := Engine.List_Index + 1; Engine.List_Levels (Engine.List_Index) := Level; Engine.Indent_Level := Engine.Indent_Level + 2; end Render_List_Start; procedure Render_List_End (Engine : in out Text_Renderer; Tag : in String) is begin if not Engine.Empty_Line then Engine.Add_Line_Break; end if; Engine.Need_Paragraph := False; Engine.Open_Paragraph; Engine.List_Index := Engine.List_Index - 1; Engine.Indent_Level := Engine.Indent_Level - 2; end Render_List_End; -- ------------------------------ -- 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_Start (Engine : in out Text_Renderer) is begin if not Engine.Empty_Line then Engine.Add_Line_Break; end if; Engine.Need_Paragraph := False; Engine.Open_Paragraph; if Engine.List_Levels (Engine.List_Index) > 0 then Engine.Render_Paragraph (Strings.To_WString (Util.Strings.Image (Engine.List_Levels (Engine.List_Index)))); Engine.List_Levels (Engine.List_Index) := Engine.List_Levels (Engine.List_Index) + 1; Engine.Render_Paragraph (") "); Engine.Indent_Level := Engine.Indent_Level + 4; else Engine.Render_Paragraph ("- "); Engine.Indent_Level := Engine.Indent_Level + 2; end if; end Render_List_Item_Start; procedure Render_List_Item_End (Engine : in out Text_Renderer) is begin if not Engine.Empty_Line then Engine.Add_Line_Break; end if; Engine.Need_Paragraph := False; Engine.Open_Paragraph; if Engine.List_Levels (Engine.List_Index) > 0 then Engine.Indent_Level := Engine.Indent_Level - 4; else Engine.Indent_Level := Engine.Indent_Level - 2; end if; end Render_List_Item_End; procedure Close_Paragraph (Document : in out Text_Renderer) is begin if Document.Has_Paragraph then Document.Add_Line_Break; end if; Document.Has_Paragraph := False; end Close_Paragraph; procedure Open_Paragraph (Document : in out Text_Renderer) is begin if Document.Need_Paragraph then Document.Has_Paragraph := True; Document.Need_Paragraph := False; end if; end Open_Paragraph; -- ------------------------------ -- Render a link. -- ------------------------------ procedure Render_Link (Engine : in out Text_Renderer; Title : in Wiki.Strings.WString; Attr : in Wiki.Attributes.Attribute_List) is Href : constant Wiki.Strings.WString := Wiki.Attributes.Get_Attribute (Attr, "href"); begin Engine.Open_Paragraph; if Title'Length /= 0 then Engine.Output.Write (Title); end if; if Title /= Href and Href'Length /= 0 then if Title'Length /= 0 then Engine.Output.Write (" ("); end if; Engine.Output.Write (Href); if Title'Length /= 0 then Engine.Output.Write (")"); end if; end if; Engine.Empty_Line := False; end Render_Link; -- ------------------------------ -- Render an image. -- ------------------------------ procedure Render_Image (Engine : in out Text_Renderer; Title : in Wiki.Strings.WString; Attr : in Wiki.Attributes.Attribute_List) is Desc : constant Wiki.Strings.WString := Wiki.Attributes.Get_Attribute (Attr, "longdesc"); begin Engine.Open_Paragraph; if Title'Length > 0 then Engine.Output.Write (Title); end if; if Title'Length > 0 and Desc'Length > 0 then Engine.Output.Write (' '); end if; if Desc'Length > 0 then Engine.Output.Write (Desc); end if; Engine.Empty_Line := False; end Render_Image; -- ------------------------------ -- Render a text block that is pre-formatted. -- ------------------------------ procedure Render_Preformatted (Engine : in out Text_Renderer; Text : in Wiki.Strings.WString; Format : in Wiki.Strings.WString) is pragma Unreferenced (Format); begin Engine.Close_Paragraph; Engine.Output.Write (Text); Engine.Empty_Line := False; end Render_Preformatted; -- ------------------------------ -- Render a text block indenting the text if necessary. -- ------------------------------ procedure Render_Paragraph (Engine : in out Text_Renderer; Text : in Wiki.Strings.WString) is begin for C of Text loop if C = Helpers.LF then Engine.Empty_Line := True; Engine.Current_Indent := 0; Engine.Output.Write (C); else while Engine.Current_Indent < Engine.Indent_Level loop Engine.Output.Write (' '); Engine.Current_Indent := Engine.Current_Indent + 1; end loop; Engine.Output.Write (C); Engine.Empty_Line := False; Engine.Current_Indent := Engine.Current_Indent + 1; Engine.Has_Paragraph := True; end if; end loop; end Render_Paragraph; -- Render the node instance from the document. overriding procedure Render (Engine : in out Text_Renderer; Doc : in Wiki.Documents.Document; Node : in Wiki.Nodes.Node_Type) is use type Wiki.Nodes.Node_List_Access; begin case Node.Kind is when Wiki.Nodes.N_HEADER => Engine.Close_Paragraph; if not Engine.Empty_Line then Engine.Add_Line_Break; end if; Engine.Render (Doc, Node.Content); Engine.Add_Line_Break; when Wiki.Nodes.N_LINE_BREAK => Engine.Add_Line_Break; when Wiki.Nodes.N_HORIZONTAL_RULE => Engine.Close_Paragraph; Engine.Output.Write ("---------------------------------------------------------"); Engine.Add_Line_Break; when Wiki.Nodes.N_PARAGRAPH => Engine.Close_Paragraph; Engine.Need_Paragraph := True; Engine.Add_Line_Break; when Wiki.Nodes.N_NEWLINE => if not Engine.No_Newline then Engine.Output.Write (Wiki.Helpers.LF); else Engine.Output.Write (' '); end if; when Wiki.Nodes.N_INDENT => Engine.Indent_Level := Node.Level; when Wiki.Nodes.N_BLOCKQUOTE => Engine.Render_Blockquote (Node.Level); when Wiki.Nodes.N_LIST_START => Engine.Render_List_Start ("o", 0); when Wiki.Nodes.N_NUM_LIST_START => Engine.Render_List_Start (".", Node.Level); when Wiki.Nodes.N_LIST_END => Engine.Render_List_End (""); when Wiki.Nodes.N_NUM_LIST_END => Engine.Render_List_End (""); when Wiki.Nodes.N_LIST_ITEM => Engine.Render_List_Item_Start; when Wiki.Nodes.N_LIST_ITEM_END => Engine.Render_List_Item_End; when Wiki.Nodes.N_TEXT => Engine.Render_Paragraph (Node.Text); when Wiki.Nodes.N_QUOTE => Engine.Open_Paragraph; Engine.Output.Write (Node.Title); Engine.Empty_Line := False; when Wiki.Nodes.N_LINK => Engine.Render_Link (Node.Title, Node.Link_Attr); when Wiki.Nodes.N_IMAGE => Engine.Render_Image (Node.Title, Node.Link_Attr); when Wiki.Nodes.N_PREFORMAT => Engine.Render_Preformatted (Node.Preformatted, ""); when Wiki.Nodes.N_TAG_START => if Node.Children /= null then if Node.Tag_Start = Wiki.DT_TAG then Engine.Close_Paragraph; Engine.Indent_Level := 0; Engine.Render (Doc, Node.Children); Engine.Close_Paragraph; Engine.Indent_Level := 0; elsif Node.Tag_Start = Wiki.DD_TAG then Engine.Close_Paragraph; Engine.Empty_Line := True; Engine.Indent_Level := 4; Engine.Render (Doc, Node.Children); Engine.Close_Paragraph; Engine.Indent_Level := 0; else Engine.Render (Doc, Node.Children); if Node.Tag_Start = Wiki.DL_TAG then Engine.Close_Paragraph; Engine.New_Line; end if; end if; end if; when others => null; end case; end Render; -- ------------------------------ -- Finish the document after complete wiki text has been parsed. -- ------------------------------ overriding procedure Finish (Engine : in out Text_Renderer; Doc : in Wiki.Documents.Document) is pragma Unreferenced (Doc); begin Engine.Close_Paragraph; end Finish; end Wiki.Render.Text;
----------------------------------------------------------------------- -- wiki-render-text -- Wiki Text renderer -- Copyright (C) 2011, 2012, 2013, 2015, 2016, 2018, 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 Wiki.Helpers; with Util.Strings; package body Wiki.Render.Text is -- ------------------------------ -- Set the output writer. -- ------------------------------ procedure Set_Output_Stream (Engine : in out Text_Renderer; Stream : in Streams.Output_Stream_Access) is begin Engine.Output := Stream; end Set_Output_Stream; -- ------------------------------ -- Set the no-newline mode to produce a single line text (disabled by default). -- ------------------------------ procedure Set_No_Newline (Engine : in out Text_Renderer; Enable : in Boolean) is begin Engine.No_Newline := Enable; end Set_No_Newline; -- ------------------------------ -- Emit a new line. -- ------------------------------ procedure New_Line (Document : in out Text_Renderer) is begin if not Document.No_Newline then Document.Output.Write (Wiki.Helpers.LF); end if; Document.Empty_Line := True; end New_Line; -- ------------------------------ -- Add a line break (<br>). -- ------------------------------ procedure Add_Line_Break (Document : in out Text_Renderer) is begin if not Document.No_Newline then Document.Output.Write (Wiki.Helpers.LF); end if; Document.Empty_Line := True; Document.Current_Indent := 0; end Add_Line_Break; -- ------------------------------ -- Render a blockquote (<blockquote>). The level indicates the blockquote nested level. -- The blockquote must be closed at the next header. -- ------------------------------ procedure Render_Blockquote (Engine : in out Text_Renderer; Level : in Natural) is begin Engine.Close_Paragraph; for I in 1 .. Level loop Engine.Output.Write (" "); end loop; end Render_Blockquote; procedure Render_List_Start (Engine : in out Text_Renderer; Tag : in String; Level : in Natural) is begin if not Engine.Empty_Line then Engine.Add_Line_Break; end if; Engine.Need_Paragraph := False; Engine.Open_Paragraph; if not Engine.No_Newline then Engine.Output.Write (Wiki.Helpers.LF); end if; Engine.List_Index := Engine.List_Index + 1; Engine.List_Levels (Engine.List_Index) := Level; Engine.Indent_Level := Engine.Indent_Level + 2; end Render_List_Start; procedure Render_List_End (Engine : in out Text_Renderer; Tag : in String) is begin if not Engine.Empty_Line then Engine.Add_Line_Break; end if; Engine.Need_Paragraph := False; Engine.Open_Paragraph; Engine.List_Index := Engine.List_Index - 1; Engine.Indent_Level := Engine.Indent_Level - 2; end Render_List_End; -- ------------------------------ -- 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_Start (Engine : in out Text_Renderer) is begin if not Engine.Empty_Line then Engine.Add_Line_Break; end if; Engine.Need_Paragraph := False; Engine.Open_Paragraph; if Engine.List_Levels (Engine.List_Index) > 0 then Engine.Render_Paragraph (Strings.To_WString (Util.Strings.Image (Engine.List_Levels (Engine.List_Index)))); Engine.List_Levels (Engine.List_Index) := Engine.List_Levels (Engine.List_Index) + 1; Engine.Render_Paragraph (") "); Engine.Indent_Level := Engine.Indent_Level + 4; else Engine.Render_Paragraph ("- "); Engine.Indent_Level := Engine.Indent_Level + 2; end if; end Render_List_Item_Start; procedure Render_List_Item_End (Engine : in out Text_Renderer) is begin if not Engine.Empty_Line then Engine.Add_Line_Break; end if; Engine.Need_Paragraph := False; Engine.Open_Paragraph; if Engine.List_Levels (Engine.List_Index) > 0 then Engine.Indent_Level := Engine.Indent_Level - 4; else Engine.Indent_Level := Engine.Indent_Level - 2; end if; end Render_List_Item_End; procedure Close_Paragraph (Document : in out Text_Renderer) is begin if Document.Has_Paragraph then Document.Add_Line_Break; end if; Document.Has_Paragraph := False; end Close_Paragraph; procedure Open_Paragraph (Document : in out Text_Renderer) is begin if Document.Need_Paragraph then Document.Has_Paragraph := True; Document.Need_Paragraph := False; end if; end Open_Paragraph; -- ------------------------------ -- Render a link. -- ------------------------------ procedure Render_Link (Engine : in out Text_Renderer; Title : in Wiki.Strings.WString; Attr : in Wiki.Attributes.Attribute_List) is Href : constant Wiki.Strings.WString := Wiki.Attributes.Get_Attribute (Attr, "href"); begin Engine.Open_Paragraph; if Title'Length /= 0 then Engine.Output.Write (Title); end if; if Title /= Href and Href'Length /= 0 then if Title'Length /= 0 then Engine.Output.Write (" ("); end if; Engine.Output.Write (Href); if Title'Length /= 0 then Engine.Output.Write (")"); end if; end if; Engine.Empty_Line := False; end Render_Link; -- ------------------------------ -- Render an image. -- ------------------------------ procedure Render_Image (Engine : in out Text_Renderer; Title : in Wiki.Strings.WString; Attr : in Wiki.Attributes.Attribute_List) is Desc : constant Wiki.Strings.WString := Wiki.Attributes.Get_Attribute (Attr, "longdesc"); begin Engine.Open_Paragraph; if Title'Length > 0 then Engine.Output.Write (Title); end if; if Title'Length > 0 and Desc'Length > 0 then Engine.Output.Write (' '); end if; if Desc'Length > 0 then Engine.Output.Write (Desc); end if; Engine.Empty_Line := False; end Render_Image; -- ------------------------------ -- Render a text block that is pre-formatted. -- ------------------------------ procedure Render_Preformatted (Engine : in out Text_Renderer; Text : in Wiki.Strings.WString; Format : in Wiki.Strings.WString) is pragma Unreferenced (Format); begin Engine.Close_Paragraph; Engine.Output.Write (Text); Engine.Empty_Line := False; end Render_Preformatted; -- ------------------------------ -- Render a text block indenting the text if necessary. -- ------------------------------ procedure Render_Paragraph (Engine : in out Text_Renderer; Text : in Wiki.Strings.WString) is begin for C of Text loop if C = Helpers.LF then Engine.Empty_Line := True; Engine.Current_Indent := 0; Engine.Output.Write (C); else while Engine.Current_Indent < Engine.Indent_Level loop Engine.Output.Write (' '); Engine.Current_Indent := Engine.Current_Indent + 1; end loop; Engine.Output.Write (C); Engine.Empty_Line := False; Engine.Current_Indent := Engine.Current_Indent + 1; Engine.Has_Paragraph := True; end if; end loop; end Render_Paragraph; -- Render the node instance from the document. overriding procedure Render (Engine : in out Text_Renderer; Doc : in Wiki.Documents.Document; Node : in Wiki.Nodes.Node_Type) is use type Wiki.Nodes.Node_List_Access; begin case Node.Kind is when Wiki.Nodes.N_HEADER => Engine.Close_Paragraph; if not Engine.Empty_Line then Engine.Add_Line_Break; end if; Engine.Render (Doc, Node.Content); Engine.Add_Line_Break; Engine.Has_Paragraph := False; when Wiki.Nodes.N_LINE_BREAK => Engine.Add_Line_Break; when Wiki.Nodes.N_HORIZONTAL_RULE => Engine.Close_Paragraph; Engine.Output.Write ("---------------------------------------------------------"); Engine.Add_Line_Break; when Wiki.Nodes.N_PARAGRAPH => Engine.Close_Paragraph; Engine.Need_Paragraph := True; Engine.Add_Line_Break; when Wiki.Nodes.N_NEWLINE => if not Engine.No_Newline then Engine.Output.Write (Wiki.Helpers.LF); else Engine.Output.Write (' '); end if; when Wiki.Nodes.N_INDENT => Engine.Indent_Level := Node.Level; when Wiki.Nodes.N_BLOCKQUOTE => Engine.Render_Blockquote (Node.Level); when Wiki.Nodes.N_LIST_START => Engine.Render_List_Start ("o", 0); when Wiki.Nodes.N_NUM_LIST_START => Engine.Render_List_Start (".", Node.Level); when Wiki.Nodes.N_LIST_END => Engine.Render_List_End (""); when Wiki.Nodes.N_NUM_LIST_END => Engine.Render_List_End (""); when Wiki.Nodes.N_LIST_ITEM => Engine.Render_List_Item_Start; when Wiki.Nodes.N_LIST_ITEM_END => Engine.Render_List_Item_End; when Wiki.Nodes.N_TEXT => Engine.Render_Paragraph (Node.Text); when Wiki.Nodes.N_QUOTE => Engine.Open_Paragraph; Engine.Output.Write (Node.Title); Engine.Empty_Line := False; when Wiki.Nodes.N_LINK => Engine.Render_Link (Node.Title, Node.Link_Attr); when Wiki.Nodes.N_IMAGE => Engine.Render_Image (Node.Title, Node.Link_Attr); when Wiki.Nodes.N_PREFORMAT => Engine.Render_Preformatted (Node.Preformatted, ""); when Wiki.Nodes.N_TAG_START => if Node.Children /= null then if Node.Tag_Start = Wiki.DT_TAG then Engine.Close_Paragraph; Engine.Indent_Level := 0; Engine.Render (Doc, Node.Children); Engine.Close_Paragraph; Engine.Indent_Level := 0; elsif Node.Tag_Start = Wiki.DD_TAG then Engine.Close_Paragraph; Engine.Empty_Line := True; Engine.Indent_Level := 4; Engine.Render (Doc, Node.Children); Engine.Close_Paragraph; Engine.Indent_Level := 0; else Engine.Render (Doc, Node.Children); if Node.Tag_Start = Wiki.DL_TAG then Engine.Close_Paragraph; Engine.New_Line; end if; end if; end if; when others => null; end case; end Render; -- ------------------------------ -- Finish the document after complete wiki text has been parsed. -- ------------------------------ overriding procedure Finish (Engine : in out Text_Renderer; Doc : in Wiki.Documents.Document) is pragma Unreferenced (Doc); begin Engine.Close_Paragraph; end Finish; end Wiki.Render.Text;
Remove spurious empty line after header
Remove spurious empty line after header
Ada
apache-2.0
stcarrez/ada-wiki,stcarrez/ada-wiki
13c4091ee7256b44674477c60b1fbcd832c56319
src/wiki-render-wiki.ads
src/wiki-render-wiki.ads
----------------------------------------------------------------------- -- wiki-render-wiki -- Wiki to Wiki renderer -- Copyright (C) 2015, 2016, 2020 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Strings.Wide_Wide_Maps; with Ada.Strings.Wide_Wide_Unbounded; with Wiki.Documents; with Wiki.Attributes; with Wiki.Streams; with Wiki.Strings; -- == Wiki Renderer == -- The <tt>Wiki_Renderer</tt> allows to render a wiki document into another wiki content. -- The formatting rules are ignored except for the paragraphs and sections. package Wiki.Render.Wiki is use Standard.Wiki.Attributes; -- ------------------------------ -- Wiki to HTML writer -- ------------------------------ type Wiki_Renderer is new Renderer with private; -- Set the output stream. procedure Set_Output_Stream (Engine : in out Wiki_Renderer; Stream : in Streams.Output_Stream_Access; Format : in Wiki_Syntax); -- Render the node instance from the document. overriding procedure Render (Engine : in out Wiki_Renderer; Doc : in Documents.Document; Node : in Nodes.Node_Type); -- Add a section header in the document. procedure Render_Header (Engine : in out Wiki_Renderer; Header : in Wide_Wide_String; Level : in Positive); -- Add a paragraph (<p>). Close the previous paragraph if any. -- The paragraph must be closed at the next paragraph or next header. procedure Add_Paragraph (Engine : in out Wiki_Renderer); -- Add a blockquote (<blockquote>). The level indicates the blockquote nested level. -- The blockquote must be closed at the next header. procedure Add_Blockquote (Engine : in out Wiki_Renderer; Level : in Natural); -- Add a list item (<li>). Close the previous paragraph and list item if any. -- The list item will be closed at the next list item, next paragraph or next header. procedure Add_List_Item (Engine : in out Wiki_Renderer; Level : in Positive; Ordered : in Boolean); -- Render a link. procedure Render_Link (Engine : in out Wiki_Renderer; Name : in Strings.WString; Attrs : in Attributes.Attribute_List); -- Render an image. procedure Render_Image (Engine : in out Wiki_Renderer; Title : in Strings.WString; Attrs : in Attributes.Attribute_List); -- Render a quote. procedure Render_Quote (Engine : in out Wiki_Renderer; Title : in Strings.WString; Attrs : in Attributes.Attribute_List); -- Add a text block with the given format. procedure Render_Text (Engine : in out Wiki_Renderer; Text : in Wide_Wide_String; Format : in Format_Map); -- Render a text block that is pre-formatted. procedure Render_Preformatted (Engine : in out Wiki_Renderer; Text : in Strings.WString; Format : in Strings.WString); procedure Render_Tag (Engine : in out Wiki_Renderer; Doc : in Documents.Document; Node : in Nodes.Node_Type); -- Finish the document after complete wiki text has been parsed. procedure Finish (Engine : in out Wiki_Renderer; Doc : in Documents.Document); -- Set the text style format. procedure Set_Format (Engine : in out Wiki_Renderer; Format : in Format_Map); private use Ada.Strings.Wide_Wide_Unbounded; type Wide_String_Access is access constant Wide_Wide_String; type Wiki_Tag_Type is (Header_Start, Header_End, Img_Start, Img_End, Link_Start, Link_End, Link_Separator, Quote_Start, Quote_End, Quote_Separator, Preformat_Start, Preformat_End, List_Start, List_Item, List_Ordered_Item, Line_Break, Escape_Rule, Horizontal_Rule, Blockquote_Start, Blockquote_End); type Wiki_Tag_Array is array (Wiki_Tag_Type) of Wide_String_Access; type Wiki_Format_Array is array (Format_Type) of Wide_String_Access; -- Emit a new line. procedure New_Line (Engine : in out Wiki_Renderer; Optional : in Boolean := False); procedure Need_Separator_Line (Engine : in out Wiki_Renderer); procedure Close_Paragraph (Engine : in out Wiki_Renderer); procedure Start_Keep_Content (Engine : in out Wiki_Renderer); type List_Style_Array is array (1 .. 32) of Boolean; EMPTY_TAG : aliased constant Wide_Wide_String := ""; type Wiki_Renderer is new Renderer with record Output : Streams.Output_Stream_Access := null; Syntax : Wiki_Syntax := SYNTAX_CREOLE; Format : Format_Map := (others => False); Tags : Wiki_Tag_Array := (others => EMPTY_TAG'Access); Style_Start_Tags : Wiki_Format_Array := (others => EMPTY_TAG'Access); Style_End_Tags : Wiki_Format_Array := (others => EMPTY_TAG'Access); Escape_Set : Ada.Strings.Wide_Wide_Maps.Wide_Wide_Character_Set; Has_Paragraph : Boolean := False; Has_Item : Boolean := False; Need_Paragraph : Boolean := False; Need_Newline : Boolean := False; Need_Space : Boolean := False; Empty_Line : Boolean := True; Empty_Previous_Line : Boolean := True; Keep_Content : Natural := 0; In_List : Boolean := False; Invert_Header_Level : Boolean := False; Allow_Link_Language : Boolean := False; Link_First : Boolean := False; Html_Blockquote : Boolean := False; Line_Count : Natural := 0; Current_Level : Natural := 0; Quote_Level : Natural := 0; UL_List_Level : Natural := 0; OL_List_Level : Natural := 0; Current_Style : Format_Map := (others => False); Content : Unbounded_Wide_Wide_String; Link_Href : Unbounded_Wide_Wide_String; Link_Title : Unbounded_Wide_Wide_String; Link_Lang : Unbounded_Wide_Wide_String; end record; end Wiki.Render.Wiki;
----------------------------------------------------------------------- -- wiki-render-wiki -- Wiki to Wiki renderer -- Copyright (C) 2015, 2016, 2020 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Strings.Wide_Wide_Maps; with Ada.Strings.Wide_Wide_Unbounded; with Wiki.Documents; with Wiki.Attributes; with Wiki.Streams; with Wiki.Strings; -- == Wiki Renderer == -- The <tt>Wiki_Renderer</tt> allows to render a wiki document into another wiki content. -- The formatting rules are ignored except for the paragraphs and sections. package Wiki.Render.Wiki is use Standard.Wiki.Attributes; -- ------------------------------ -- Wiki to HTML writer -- ------------------------------ type Wiki_Renderer is new Renderer with private; -- Set the output stream. procedure Set_Output_Stream (Engine : in out Wiki_Renderer; Stream : in Streams.Output_Stream_Access; Format : in Wiki_Syntax); -- Render the node instance from the document. overriding procedure Render (Engine : in out Wiki_Renderer; Doc : in Documents.Document; Node : in Nodes.Node_Type); -- Add a section header in the document. procedure Render_Header (Engine : in out Wiki_Renderer; Header : in Wide_Wide_String; Level : in Positive); -- Add a paragraph (<p>). Close the previous paragraph if any. -- The paragraph must be closed at the next paragraph or next header. procedure Add_Paragraph (Engine : in out Wiki_Renderer); -- Add a blockquote (<blockquote>). The level indicates the blockquote nested level. -- The blockquote must be closed at the next header. procedure Add_Blockquote (Engine : in out Wiki_Renderer; Level : in Natural); -- Add a list item (<li>). Close the previous paragraph and list item if any. -- The list item will be closed at the next list item, next paragraph or next header. procedure Add_List_Item (Engine : in out Wiki_Renderer; Level : in Positive; Ordered : in Boolean); -- Render a link. procedure Render_Link (Engine : in out Wiki_Renderer; Name : in Strings.WString; Attrs : in Attributes.Attribute_List); -- Render an image. procedure Render_Image (Engine : in out Wiki_Renderer; Title : in Strings.WString; Attrs : in Attributes.Attribute_List); -- Render a quote. procedure Render_Quote (Engine : in out Wiki_Renderer; Title : in Strings.WString; Attrs : in Attributes.Attribute_List); -- Add a text block with the given format. procedure Render_Text (Engine : in out Wiki_Renderer; Text : in Wide_Wide_String; Format : in Format_Map); -- Render a text block that is pre-formatted. procedure Render_Preformatted (Engine : in out Wiki_Renderer; Text : in Strings.WString; Format : in Strings.WString); procedure Render_Tag (Engine : in out Wiki_Renderer; Doc : in Documents.Document; Node : in Nodes.Node_Type); -- Finish the document after complete wiki text has been parsed. procedure Finish (Engine : in out Wiki_Renderer; Doc : in Documents.Document); -- Set the text style format. procedure Set_Format (Engine : in out Wiki_Renderer; Format : in Format_Map); private use Ada.Strings.Wide_Wide_Unbounded; type Wide_String_Access is access constant Wide_Wide_String; type Wiki_Tag_Type is (Header_Start, Header_End, Img_Start, Img_End, Link_Start, Link_End, Link_Separator, Quote_Start, Quote_End, Quote_Separator, Preformat_Start, Preformat_End, List_Start, List_Item, List_Ordered_Item, Line_Break, Escape_Rule, Horizontal_Rule, Blockquote_Start, Blockquote_End); type Wiki_Tag_Array is array (Wiki_Tag_Type) of Wide_String_Access; type Wiki_Format_Array is array (Format_Type) of Wide_String_Access; procedure Write_Optional_Space (Engine : in out Wiki_Renderer); -- Emit a new line. procedure New_Line (Engine : in out Wiki_Renderer; Optional : in Boolean := False); procedure Need_Separator_Line (Engine : in out Wiki_Renderer); procedure Close_Paragraph (Engine : in out Wiki_Renderer); procedure Start_Keep_Content (Engine : in out Wiki_Renderer); type List_Style_Array is array (1 .. 32) of Boolean; EMPTY_TAG : aliased constant Wide_Wide_String := ""; type Wiki_Renderer is new Renderer with record Output : Streams.Output_Stream_Access := null; Syntax : Wiki_Syntax := SYNTAX_CREOLE; Format : Format_Map := (others => False); Tags : Wiki_Tag_Array := (others => EMPTY_TAG'Access); Style_Start_Tags : Wiki_Format_Array := (others => EMPTY_TAG'Access); Style_End_Tags : Wiki_Format_Array := (others => EMPTY_TAG'Access); Escape_Set : Ada.Strings.Wide_Wide_Maps.Wide_Wide_Character_Set; Has_Paragraph : Boolean := False; Has_Item : Boolean := False; Need_Paragraph : Boolean := False; Need_Newline : Boolean := False; Need_Space : Boolean := False; Empty_Line : Boolean := True; Empty_Previous_Line : Boolean := True; Keep_Content : Natural := 0; In_List : Boolean := False; Invert_Header_Level : Boolean := False; Allow_Link_Language : Boolean := False; Link_First : Boolean := False; Html_Blockquote : Boolean := False; Line_Count : Natural := 0; Current_Level : Natural := 0; Quote_Level : Natural := 0; UL_List_Level : Natural := 0; OL_List_Level : Natural := 0; Current_Style : Format_Map := (others => False); Content : Unbounded_Wide_Wide_String; Link_Href : Unbounded_Wide_Wide_String; Link_Title : Unbounded_Wide_Wide_String; Link_Lang : Unbounded_Wide_Wide_String; end record; end Wiki.Render.Wiki;
Declare the Write_Optional_Space procedure
Declare the Write_Optional_Space procedure
Ada
apache-2.0
stcarrez/ada-wiki,stcarrez/ada-wiki
24d4e767e890b12bb2905657687c24a36c96c242
regtests/util-files-tests.adb
regtests/util-files-tests.adb
----------------------------------------------------------------------- -- files.tests -- Unit tests for files -- 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 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'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); 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; Last := To_Unbounded_String (Dir); end if; 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"); end Test_Iterate_Path; -- ------------------------------ -- Test the Compose_Path operation -- ------------------------------ procedure Test_Compose_Path (T : in out Test) is begin Assert_Equals (T, "/usr/bin;/usr/local/bin;/usr/bin", Compose_Path ("/usr;/usr/local;/usr", "bin"), "Invalid path composition"); end Test_Compose_Path; end Util.Files.Tests;
----------------------------------------------------------------------- -- files.tests -- Unit tests for files -- 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.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'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); 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; Last := To_Unbounded_String (Dir); end if; 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"); end Test_Iterate_Path; -- ------------------------------ -- Test the Compose_Path operation -- ------------------------------ procedure Test_Compose_Path (T : in out Test) is begin Assert_Equals (T, "src/os-none", Compose_Path ("src;regtests", "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; end Util.Files.Tests;
Fix execution of Compose unit test on Windows - Do not execute one test that relies on the availability of /usr/bin directory - Add a compose test that uses the util directory hierarchy.
Fix execution of Compose unit test on Windows - Do not execute one test that relies on the availability of /usr/bin directory - Add a compose test that uses the util directory hierarchy.
Ada
apache-2.0
stcarrez/ada-util,stcarrez/ada-util
f4d75006be620397e07d389684beddd5cee75464
regtests/asf-contexts-faces-tests.adb
regtests/asf-contexts-faces-tests.adb
----------------------------------------------------------------------- -- Faces Context Tests - Unit tests for ASF.Contexts.Faces -- 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.IO_Exceptions; with Util.Test_Caller; package body ASF.Contexts.Faces.Tests is use Util.Tests; package Caller is new Util.Test_Caller (Test, "Contexts.Faces"); procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is begin -- To document what is tested, register the test methods for each -- operation that is tested. Caller.Add_Test (Suite, "Test ASF.Contexts.Faces.Add_Message", Test_Add_Message'Access); Caller.Add_Test (Suite, "Test ASF.Contexts.Faces.Max_Severity", Test_Max_Severity'Access); Caller.Add_Test (Suite, "Test ASF.Contexts.Faces.Get_Message", Test_Get_Messages'Access); Caller.Add_Test (Suite, "Test ASF.Contexts.Faces.Queue_Exception", Test_Queue_Exception'Access); Caller.Add_Test (Suite, "Test ASF.Contexts.Faces.Get_Flash", Test_Flash_Context'Access); end Add_Tests; -- Test the faces message queue. procedure Test_Add_Message (T : in out Test) is Ctx : Faces_Context; begin Ctx.Add_Message (Client_Id => "", Message => "msg1"); Ctx.Add_Message (Client_Id => "", Message => "msg1"); Ctx.Add_Message (Client_Id => "", Message => "msg2"); Ctx.Add_Message (Client_Id => "", Message => "msg3"); Ctx.Add_Message (Client_Id => "info", Message => "msg3", Severity => INFO); Ctx.Add_Message (Client_Id => "warn", Message => "msg3", Severity => WARN); Ctx.Add_Message (Client_Id => "error", Message => "msg3", Severity => ERROR); Ctx.Add_Message (Client_Id => "fatal", Message => "msg3", Severity => FATAL); T.Assert (Ctx.Get_Maximum_Severity = FATAL, "Add message failed"); end Test_Add_Message; procedure Test_Max_Severity (T : in out Test) is Ctx : Faces_Context; begin T.Assert (Ctx.Get_Maximum_Severity = NONE, "Invalid max severity with no message"); Ctx.Add_Message (Client_Id => "info", Message => "msg3", Severity => INFO); T.Assert (Ctx.Get_Maximum_Severity = INFO, "Invalid max severity with info message"); Ctx.Add_Message (Client_Id => "info", Message => "msg3", Severity => WARN); T.Assert (Ctx.Get_Maximum_Severity = WARN, "Invalid max severity with warn message"); Ctx.Add_Message (Client_Id => "info", Message => "msg3", Severity => FATAL); T.Assert (Ctx.Get_Maximum_Severity = FATAL, "Invalid max severity with warn message"); end Test_Max_Severity; procedure Test_Get_Messages (T : in out Test) is Ctx : Faces_Context; begin -- Iterator on an empty message list. declare Iter : constant Vectors.Cursor := Ctx.Get_Messages (Client_Id => ""); begin T.Assert (not Vectors.Has_Element (Iter), "Iterator should indicate no message"); end; Ctx.Add_Message (Client_Id => "info", Message => "msg1", Severity => INFO); declare Iter : constant Vectors.Cursor := Ctx.Get_Messages (Client_Id => "info"); M : Message; begin T.Assert (Vectors.Has_Element (Iter), "Iterator should indicate a message"); M := Vectors.Element (Iter); Assert_Equals (T, "msg1", Get_Summary (M), "Invalid message"); Assert_Equals (T, "msg1", Get_Detail (M), "Invalid details"); T.Assert (INFO = Get_Severity (M), "Invalid severity"); end; end Test_Get_Messages; -- ------------------------------ -- Test adding some exception in the faces context. -- ------------------------------ procedure Test_Queue_Exception (T : in out Test) is procedure Raise_Exception (Depth : in Natural; Excep : in Natural); procedure Check_Exception (Event : in Events.Exceptions.Exception_Event'Class; Remove : out Boolean; Context : in out Faces_Context'Class); Ctx : Faces_Context; Cnt : Natural := 0; procedure Raise_Exception (Depth : in Natural; Excep : in Natural) is begin if Depth > 0 then Raise_Exception (Depth - 1, Excep); end if; case Excep is when 1 => raise Constraint_Error with "except code 1"; when 2 => raise Ada.IO_Exceptions.Name_Error; when others => raise Program_Error with "Testing program error"; end case; end Raise_Exception; procedure Check_Exception (Event : in Events.Exceptions.Exception_Event'Class; Remove : out Boolean; Context : in out Faces_Context'Class) is pragma Unreferenced (Context, Event); begin Cnt := Cnt + 1; Remove := False; end Check_Exception; begin -- Create some exceptions and queue them. for I in 1 .. 3 loop begin Raise_Exception (3, I); exception when E : others => Ctx.Queue_Exception (E); end; end loop; Ctx.Iterate_Exception (Check_Exception'Access); Util.Tests.Assert_Equals (T, 3, Cnt, "3 exception should have been queued"); end Test_Queue_Exception; -- ------------------------------ -- Test the flash instance. -- ------------------------------ procedure Test_Flash_Context (T : in out Test) is use type ASF.Contexts.Faces.Flash_Context_Access; Ctx : Faces_Context; Flash : constant ASF.Contexts.Faces.Flash_Context_Access := Ctx.Get_Flash; begin T.Assert (Flash /= null, "Null flash context returned"); end Test_Flash_Context; end ASF.Contexts.Faces.Tests;
----------------------------------------------------------------------- -- Faces Context Tests - Unit tests for ASF.Contexts.Faces -- 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.IO_Exceptions; with Util.Test_Caller; with ASF.Contexts.Flash; package body ASF.Contexts.Faces.Tests is use Util.Tests; package Caller is new Util.Test_Caller (Test, "Contexts.Faces"); procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is begin -- To document what is tested, register the test methods for each -- operation that is tested. Caller.Add_Test (Suite, "Test ASF.Contexts.Faces.Add_Message", Test_Add_Message'Access); Caller.Add_Test (Suite, "Test ASF.Contexts.Faces.Max_Severity", Test_Max_Severity'Access); Caller.Add_Test (Suite, "Test ASF.Contexts.Faces.Get_Message", Test_Get_Messages'Access); Caller.Add_Test (Suite, "Test ASF.Contexts.Faces.Queue_Exception", Test_Queue_Exception'Access); Caller.Add_Test (Suite, "Test ASF.Contexts.Faces.Get_Flash", Test_Flash_Context'Access); end Add_Tests; -- Test the faces message queue. procedure Test_Add_Message (T : in out Test) is Ctx : Faces_Context; begin Ctx.Add_Message (Client_Id => "", Message => "msg1"); Ctx.Add_Message (Client_Id => "", Message => "msg1"); Ctx.Add_Message (Client_Id => "", Message => "msg2"); Ctx.Add_Message (Client_Id => "", Message => "msg3"); Ctx.Add_Message (Client_Id => "info", Message => "msg3", Severity => INFO); Ctx.Add_Message (Client_Id => "warn", Message => "msg3", Severity => WARN); Ctx.Add_Message (Client_Id => "error", Message => "msg3", Severity => ERROR); Ctx.Add_Message (Client_Id => "fatal", Message => "msg3", Severity => FATAL); T.Assert (Ctx.Get_Maximum_Severity = FATAL, "Add message failed"); end Test_Add_Message; procedure Test_Max_Severity (T : in out Test) is Ctx : Faces_Context; begin T.Assert (Ctx.Get_Maximum_Severity = NONE, "Invalid max severity with no message"); Ctx.Add_Message (Client_Id => "info", Message => "msg3", Severity => INFO); T.Assert (Ctx.Get_Maximum_Severity = INFO, "Invalid max severity with info message"); Ctx.Add_Message (Client_Id => "info", Message => "msg3", Severity => WARN); T.Assert (Ctx.Get_Maximum_Severity = WARN, "Invalid max severity with warn message"); Ctx.Add_Message (Client_Id => "info", Message => "msg3", Severity => FATAL); T.Assert (Ctx.Get_Maximum_Severity = FATAL, "Invalid max severity with warn message"); end Test_Max_Severity; procedure Test_Get_Messages (T : in out Test) is Ctx : Faces_Context; begin -- Iterator on an empty message list. declare Iter : constant Vectors.Cursor := Ctx.Get_Messages (Client_Id => ""); begin T.Assert (not Vectors.Has_Element (Iter), "Iterator should indicate no message"); end; Ctx.Add_Message (Client_Id => "info", Message => "msg1", Severity => INFO); declare Iter : constant Vectors.Cursor := Ctx.Get_Messages (Client_Id => "info"); M : Message; begin T.Assert (Vectors.Has_Element (Iter), "Iterator should indicate a message"); M := Vectors.Element (Iter); Assert_Equals (T, "msg1", Get_Summary (M), "Invalid message"); Assert_Equals (T, "msg1", Get_Detail (M), "Invalid details"); T.Assert (INFO = Get_Severity (M), "Invalid severity"); end; end Test_Get_Messages; -- ------------------------------ -- Test adding some exception in the faces context. -- ------------------------------ procedure Test_Queue_Exception (T : in out Test) is procedure Raise_Exception (Depth : in Natural; Excep : in Natural); procedure Check_Exception (Event : in Events.Exceptions.Exception_Event'Class; Remove : out Boolean; Context : in out Faces_Context'Class); Ctx : Faces_Context; Cnt : Natural := 0; procedure Raise_Exception (Depth : in Natural; Excep : in Natural) is begin if Depth > 0 then Raise_Exception (Depth - 1, Excep); end if; case Excep is when 1 => raise Constraint_Error with "except code 1"; when 2 => raise Ada.IO_Exceptions.Name_Error; when others => raise Program_Error with "Testing program error"; end case; end Raise_Exception; procedure Check_Exception (Event : in Events.Exceptions.Exception_Event'Class; Remove : out Boolean; Context : in out Faces_Context'Class) is pragma Unreferenced (Context, Event); begin Cnt := Cnt + 1; Remove := False; end Check_Exception; begin -- Create some exceptions and queue them. for I in 1 .. 3 loop begin Raise_Exception (3, I); exception when E : others => Ctx.Queue_Exception (E); end; end loop; Ctx.Iterate_Exception (Check_Exception'Access); Util.Tests.Assert_Equals (T, 3, Cnt, "3 exception should have been queued"); end Test_Queue_Exception; -- ------------------------------ -- Test the flash instance. -- ------------------------------ procedure Test_Flash_Context (T : in out Test) is use type ASF.Contexts.Faces.Flash_Context_Access; Ctx : Faces_Context; Flash : aliased ASF.Contexts.Flash.Flash_Context; begin Ctx.Set_Flash (Flash'Unchecked_Access); T.Assert (Ctx.Get_Flash /= null, "Null flash context returned"); end Test_Flash_Context; end ASF.Contexts.Faces.Tests;
Fix flash unit test
Fix flash unit test
Ada
apache-2.0
stcarrez/ada-asf,stcarrez/ada-asf,stcarrez/ada-asf
b84ccef5d02388ec1c5595d12ae5a936d409a027
src/security-oauth-clients.ads
src/security-oauth-clients.ads
----------------------------------------------------------------------- -- security-oauth -- OAuth Security -- Copyright (C) 2012, 2013, 2016, 2017, 2018 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Strings.Unbounded; -- The <b>Security.OAuth.Clients</b> package implements the client OAuth 2.0 authorization. -- -- Note: OAuth 1.0 could be implemented but since it's being deprecated it's not worth doing it. package Security.OAuth.Clients is -- ------------------------------ -- Access Token -- ------------------------------ -- Access tokens are credentials used to access protected resources. -- The access token is represented as a <b>Principal</b>. This is an opaque -- value for an application. type Access_Token (Len : Natural) is new Security.Principal with private; type Access_Token_Access is access all Access_Token'Class; -- Get the principal name. This is the OAuth access token. function Get_Name (From : in Access_Token) return String; type OpenID_Token (Len, Id_Len, Refresh_Len : Natural) is new Access_Token with private; type OpenID_Token_Access is access all OpenID_Token'Class; -- Get the id_token that was returned by the authentication process. function Get_Id_Token (From : in OpenID_Token) return String; -- Generate a random nonce with at last the number of random bits. -- The number of bits is rounded up to a multiple of 32. -- The random bits are then converted to base64url in the returned string. function Create_Nonce (Bits : in Positive := 256) return String; type Grant_Type is new Security.Principal with private; -- Get the principal name. This is the OAuth access token. function Get_Name (From : in Grant_Type) return String; -- Get the Authorization header to be used for accessing a protected resource. -- (See RFC 6749 7. Accessing Protected Resources) function Get_Authorization (From : in Grant_Type) return String; -- ------------------------------ -- Application -- ------------------------------ -- The <b>Application</b> holds the necessary information to let a user -- grant access to its protected resources on the resource server. It contains -- information that allows the OAuth authorization server to identify the -- application (client id and secret key). type Application is new Security.OAuth.Application with private; -- Set the OAuth authorization server URI that the application must use -- to exchange the OAuth code into an access token. procedure Set_Provider_URI (App : in out Application; URI : in String); -- OAuth 2.0 Section 4.1.1 Authorization Request -- Build a unique opaque value used to prevent cross-site request forgery. -- The <b>Nonce</b> parameters is an optional but recommended unique value -- used only once. The state value will be returned back by the OAuth provider. -- This protects the <tt>client_id</tt> and <tt>redirect_uri</tt> parameters. function Get_State (App : in Application; Nonce : in String) return String; -- Get the authenticate parameters to build the URI to redirect the user to -- the OAuth authorization form. function Get_Auth_Params (App : in Application; State : in String; Scope : in String := "") return String; -- OAuth 2.0 Section 4.1.2 Authorization Response -- Verify that the <b>State</b> opaque value was created by the <b>Get_State</b> -- operation with the given client and redirect URL. function Is_Valid_State (App : in Application; Nonce : in String; State : in String) return Boolean; -- OAuth 2.0 Section 4.1.3. Access Token Request -- Section 4.1.4. Access Token Response -- Exchange the OAuth code into an access token. function Request_Access_Token (App : in Application; Code : in String) return Access_Token_Access; -- Get a request token with username and password. -- RFC 6749: 4.3. Resource Owner Password Credentials Grant procedure Request_Token (App : in Application; Username : in String; Password : in String; Scope : in String; Token : in out Grant_Type'Class); -- Create the access token function Create_Access_Token (App : in Application; Token : in String; Refresh : in String; Id_Token : in String; Expires : in Natural) return Access_Token_Access; private type Access_Token (Len : Natural) is new Security.Principal with record Access_Id : String (1 .. Len); end record; type OpenID_Token (Len, Id_Len, Refresh_Len : Natural) is new Access_Token (Len) with record Id_Token : String (1 .. Id_Len); Refresh_Token : String (1 .. Refresh_Len); end record; type Application is new Security.OAuth.Application with record Request_URI : Ada.Strings.Unbounded.Unbounded_String; end record; type Grant_Type is new Security.Principal with record Access_Token : Ada.Strings.Unbounded.Unbounded_String; Refresh_Token : Ada.Strings.Unbounded.Unbounded_String; Id_Token : Ada.Strings.Unbounded.Unbounded_String; end record; end Security.OAuth.Clients;
----------------------------------------------------------------------- -- security-oauth -- OAuth Security -- Copyright (C) 2012, 2013, 2016, 2017, 2018 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Strings.Unbounded; -- The <b>Security.OAuth.Clients</b> package implements the client OAuth 2.0 authorization. -- -- Note: OAuth 1.0 could be implemented but since it's being deprecated it's not worth doing it. package Security.OAuth.Clients is -- ------------------------------ -- Access Token -- ------------------------------ -- Access tokens are credentials used to access protected resources. -- The access token is represented as a <b>Principal</b>. This is an opaque -- value for an application. type Access_Token (Len : Natural) is new Security.Principal with private; type Access_Token_Access is access all Access_Token'Class; -- Get the principal name. This is the OAuth access token. function Get_Name (From : in Access_Token) return String; type OpenID_Token (Len, Id_Len, Refresh_Len : Natural) is new Access_Token with private; type OpenID_Token_Access is access all OpenID_Token'Class; -- Get the id_token that was returned by the authentication process. function Get_Id_Token (From : in OpenID_Token) return String; -- Generate a random nonce with at last the number of random bits. -- The number of bits is rounded up to a multiple of 32. -- The random bits are then converted to base64url in the returned string. function Create_Nonce (Bits : in Positive := 256) return String; type Grant_Type is new Security.Principal with private; -- Get the principal name. This is the OAuth access token. function Get_Name (From : in Grant_Type) return String; -- Get the Authorization header to be used for accessing a protected resource. -- (See RFC 6749 7. Accessing Protected Resources) function Get_Authorization (From : in Grant_Type) return String; -- ------------------------------ -- Application -- ------------------------------ -- The <b>Application</b> holds the necessary information to let a user -- grant access to its protected resources on the resource server. It contains -- information that allows the OAuth authorization server to identify the -- application (client id and secret key). type Application is new Security.OAuth.Application with private; -- Set the OAuth authorization server URI that the application must use -- to exchange the OAuth code into an access token. procedure Set_Provider_URI (App : in out Application; URI : in String); -- OAuth 2.0 Section 4.1.1 Authorization Request -- Build a unique opaque value used to prevent cross-site request forgery. -- The <b>Nonce</b> parameters is an optional but recommended unique value -- used only once. The state value will be returned back by the OAuth provider. -- This protects the <tt>client_id</tt> and <tt>redirect_uri</tt> parameters. function Get_State (App : in Application; Nonce : in String) return String; -- Get the authenticate parameters to build the URI to redirect the user to -- the OAuth authorization form. function Get_Auth_Params (App : in Application; State : in String; Scope : in String := "") return String; -- OAuth 2.0 Section 4.1.2 Authorization Response -- Verify that the <b>State</b> opaque value was created by the <b>Get_State</b> -- operation with the given client and redirect URL. function Is_Valid_State (App : in Application; Nonce : in String; State : in String) return Boolean; -- OAuth 2.0 Section 4.1.3. Access Token Request -- Section 4.1.4. Access Token Response -- Exchange the OAuth code into an access token. function Request_Access_Token (App : in Application; Code : in String) return Access_Token_Access; -- Get a request token with username and password. -- RFC 6749: 4.3. Resource Owner Password Credentials Grant procedure Request_Token (App : in Application; Username : in String; Password : in String; Scope : in String; Token : in out Grant_Type'Class); -- Refresh the access token. -- RFC 6749: 6. Refreshing an Access Token procedure Refresh_Token (App : in Application; Scope : in String; Token : in out Grant_Type'Class); -- Create the access token function Create_Access_Token (App : in Application; Token : in String; Refresh : in String; Id_Token : in String; Expires : in Natural) return Access_Token_Access; private type Access_Token (Len : Natural) is new Security.Principal with record Access_Id : String (1 .. Len); end record; type OpenID_Token (Len, Id_Len, Refresh_Len : Natural) is new Access_Token (Len) with record Id_Token : String (1 .. Id_Len); Refresh_Token : String (1 .. Refresh_Len); end record; type Application is new Security.OAuth.Application with record Request_URI : Ada.Strings.Unbounded.Unbounded_String; end record; type Grant_Type is new Security.Principal with record Access_Token : Ada.Strings.Unbounded.Unbounded_String; Refresh_Token : Ada.Strings.Unbounded.Unbounded_String; Id_Token : Ada.Strings.Unbounded.Unbounded_String; end record; end Security.OAuth.Clients;
Declare the Refresh_Token procedure
Declare the Refresh_Token procedure
Ada
apache-2.0
stcarrez/ada-security
2aa9e5ee491828ff25628ba1cd4699240ef1e06b
mat/src/mat-consoles.adb
mat/src/mat-consoles.adb
----------------------------------------------------------------------- -- mat-consoles - Console interface -- Copyright (C) 2014 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- package body MAT.Consoles is -- ------------------------------ -- Print the title for the given field and setup the associated field size. -- ------------------------------ procedure Print_Title (Console : in out Console_Type; Field : in Field_Type; Title : in String; Length : in Positive) is begin Console.Sizes (Field) := Length; if Console.Field_Count >= 1 then Console.Cols (Field) := Console.Cols (Console.Fields (Console.Field_Count)) + Console.Sizes (Console.Fields (Console.Field_Count)); else Console.Cols (Field) := 1; end if; Console.Field_Count := Console.Field_Count + 1; Console.Fields (Console.Field_Count) := Field; Console_Type'Class (Console).Print_Title (Field, Title); end Print_Title; -- ------------------------------ -- Format the address and print it for the given field. -- ------------------------------ procedure Print_Field (Console : in out Console_Type; Field : in Field_Type; Addr : in MAT.Types.Target_Addr) is Value : constant String := MAT.Types.Hex_Image (Addr); begin Console_Type'Class (Console).Print_Field (Field, Value); end Print_Field; -- ------------------------------ -- Format the size and print it for the given field. -- ------------------------------ procedure Print_Size (Console : in out Console_Type; Field : in Field_Type; Size : in MAT.Types.Target_Size) is Value : constant String := MAT.Types.Target_Size'Image (Size); begin Console_Type'Class (Console).Print_Field (Field, Value); end Print_Size; -- ------------------------------ -- Format the thread information and print it for the given field. -- ------------------------------ procedure Print_Thread (Console : in out Console_Type; Field : in Field_Type; Thread : in MAT.Types.Target_Thread_Ref) is Value : constant String := MAT.Types.Target_Thread_Ref'Image (Thread); begin Console_Type'Class (Console).Print_Field (Field, Value); end Print_Thread; -- ------------------------------ -- Format the time tick as a duration and print it for the given field. -- ------------------------------ procedure Print_Duration (Console : in out Console_Type; Field : in Field_Type; Duration : in MAT.Types.Target_Tick_Ref) is Value : constant String := MAT.Types.Tick_Image (Duration); begin Console_Type'Class (Console).Print_Field (Field, Value); end Print_Duration; -- ------------------------------ -- Format the integer and print it for the given field. -- ------------------------------ procedure Print_Field (Console : in out Console_Type; Field : in Field_Type; Value : in Integer; Justify : in Justify_Type := J_LEFT) is Val : constant String := Integer'Image (Value); begin Console_Type'Class (Console).Print_Field (Field, Val, Justify); end Print_Field; -- ------------------------------ -- Format the integer and print it for the given field. -- ------------------------------ procedure Print_Field (Console : in out Console_Type; Field : in Field_Type; Value : in Ada.Strings.Unbounded.Unbounded_String; Justify : in Justify_Type := J_LEFT) is Item : String := Ada.Strings.Unbounded.To_String (Value); Size : constant Natural := Console.Sizes (Field); begin if Size <= Item'Length then Item (Item'Last - Size + 2 .. Item'Last - Size + 4) := "..."; Console_Type'Class (Console).Print_Field (Field, Item (Item'Last - Size + 2 .. Item'Last)); else Console_Type'Class (Console).Print_Field (Field, Item, Justify); end if; end Print_Field; end MAT.Consoles;
----------------------------------------------------------------------- -- mat-consoles - Console interface -- Copyright (C) 2014 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- package body MAT.Consoles is -- ------------------------------ -- Print the title for the given field and setup the associated field size. -- ------------------------------ procedure Print_Title (Console : in out Console_Type; Field : in Field_Type; Title : in String; Length : in Positive) is begin Console.Sizes (Field) := Length; if Console.Field_Count >= 1 then Console.Cols (Field) := Console.Cols (Console.Fields (Console.Field_Count)) + Console.Sizes (Console.Fields (Console.Field_Count)); else Console.Cols (Field) := 1; end if; Console.Field_Count := Console.Field_Count + 1; Console.Fields (Console.Field_Count) := Field; Console_Type'Class (Console).Print_Title (Field, Title); end Print_Title; -- ------------------------------ -- Format the address and print it for the given field. -- ------------------------------ procedure Print_Field (Console : in out Console_Type; Field : in Field_Type; Addr : in MAT.Types.Target_Addr) is Value : constant String := MAT.Types.Hex_Image (Addr); begin Console_Type'Class (Console).Print_Field (Field, Value); end Print_Field; -- ------------------------------ -- Format the address range and print it for the given field. -- ------------------------------ procedure Print_Field (Console : in out Console_Type; Field : in Field_Type; From : in MAT.Types.Target_Addr; To : in MAT.Types.Target_Addr) is From_Value : constant String := MAT.Types.Hex_Image (From); To_Value : constant String := MAT.Types.Hex_Image (To); begin Console_Type'Class (Console).Print_Field (Field, From_Value & "-" & To_Value); end Print_Field; -- ------------------------------ -- Format the size and print it for the given field. -- ------------------------------ procedure Print_Size (Console : in out Console_Type; Field : in Field_Type; Size : in MAT.Types.Target_Size) is Value : constant String := MAT.Types.Target_Size'Image (Size); begin Console_Type'Class (Console).Print_Field (Field, Value); end Print_Size; -- ------------------------------ -- Format the thread information and print it for the given field. -- ------------------------------ procedure Print_Thread (Console : in out Console_Type; Field : in Field_Type; Thread : in MAT.Types.Target_Thread_Ref) is Value : constant String := MAT.Types.Target_Thread_Ref'Image (Thread); begin Console_Type'Class (Console).Print_Field (Field, Value); end Print_Thread; -- ------------------------------ -- Format the time tick as a duration and print it for the given field. -- ------------------------------ procedure Print_Duration (Console : in out Console_Type; Field : in Field_Type; Duration : in MAT.Types.Target_Tick_Ref) is Value : constant String := MAT.Types.Tick_Image (Duration); begin Console_Type'Class (Console).Print_Field (Field, Value); end Print_Duration; -- ------------------------------ -- Format the integer and print it for the given field. -- ------------------------------ procedure Print_Field (Console : in out Console_Type; Field : in Field_Type; Value : in Integer; Justify : in Justify_Type := J_LEFT) is Val : constant String := Integer'Image (Value); begin Console_Type'Class (Console).Print_Field (Field, Val, Justify); end Print_Field; -- ------------------------------ -- Format the integer and print it for the given field. -- ------------------------------ procedure Print_Field (Console : in out Console_Type; Field : in Field_Type; Value : in Ada.Strings.Unbounded.Unbounded_String; Justify : in Justify_Type := J_LEFT) is Item : String := Ada.Strings.Unbounded.To_String (Value); Size : constant Natural := Console.Sizes (Field); begin if Size <= Item'Length then Item (Item'Last - Size + 2 .. Item'Last - Size + 4) := "..."; Console_Type'Class (Console).Print_Field (Field, Item (Item'Last - Size + 2 .. Item'Last)); else Console_Type'Class (Console).Print_Field (Field, Item, Justify); end if; end Print_Field; end MAT.Consoles;
Implement the Print_Field with a range of address
Implement the Print_Field with a range of address
Ada
apache-2.0
stcarrez/mat,stcarrez/mat,stcarrez/mat
7083d31730ab183fc52dc6023ce6332e9dfb5287
boards/native/src/native-filesystem.adb
boards/native/src/native-filesystem.adb
with Ada.Directories; with Ada.Unchecked_Deallocation; package body Native.Filesystem is -- ??? There are a bunch of 'Unrestricted_Access here because the -- HAL.Filesystem API embeds implicit references to filesystems. It -- woudl be good to make these references explicit at some point to -- avoid kludges. function "+" (S : Ada.Strings.Unbounded.Unbounded_String) return String renames Ada.Strings.Unbounded.To_String; function "+" (S : String) return Ada.Strings.Unbounded.Unbounded_String renames Ada.Strings.Unbounded.To_Unbounded_String; procedure Destroy is new Ada.Unchecked_Deallocation (Native_File_Handle, Native_File_Handle_Ref); procedure Destroy is new Ada.Unchecked_Deallocation (Native_Directory_Handle, Native_Directory_Handle_Ref); function "<" (Left, Right : Directory_Data_Entry) return Boolean is (Ada.Strings.Unbounded."<" (Left.Name, Right.Name)); package Directory_Data_Sorting is new Directory_Data_Vectors.Generic_Sorting; -- Most of the time, standard operations give us no reliable way to -- determine specifically what triggered a failure, so use the following -- error code as a "generic" one. Generic_Error : constant Status_Kind := Input_Output_Error; function Absolute_Path (This : Native_FS_Driver; Relative_Path : Pathname) return Pathname is (if Relative_Path = "" then +This.Root_Dir else Join (+This.Root_Dir, Relative_Path, True)); ---------------- -- Get_Handle -- ---------------- function Get_Handle (FS : in out Native_FS_Driver) return Native_File_Handle_Ref is Result : Native_File_Handle_Ref := FS.Free_File_Handles; begin if Result = null then Result := new Native_File_Handle' (FS => FS'Unrestricted_Access, others => <>); else FS.Free_File_Handles := Result.Next; end if; return Result; end Get_Handle; ---------------- -- Get_Handle -- ---------------- function Get_Handle (FS : in out Native_FS_Driver) return Native_Directory_Handle_Ref is Result : Native_Directory_Handle_Ref := FS.Free_Dir_Handles; begin if Result = null then Result := new Native_Directory_Handle' (FS => FS'Unrestricted_Access, others => <>); else FS.Free_Dir_Handles := Result.Next; end if; return Result; end Get_Handle; --------------------- -- Add_Free_Handle -- --------------------- procedure Add_Free_Handle (FS : in out Native_FS_Driver; Handle : in out Native_File_Handle_Ref) is begin Handle.Next := FS.Free_File_Handles; FS.Free_File_Handles := Handle; Handle := null; end Add_Free_Handle; --------------------- -- Add_Free_Handle -- --------------------- procedure Add_Free_Handle (FS : in out Native_FS_Driver; Handle : in out Native_Directory_Handle_Ref) is begin Handle.Next := FS.Free_Dir_Handles; FS.Free_Dir_Handles := Handle; Handle := null; end Add_Free_Handle; ------------- -- Destroy -- ------------- procedure Destroy (This : in out Native_FS_Driver_Ref) is procedure Destroy is new Ada.Unchecked_Deallocation (Native_FS_Driver, Native_FS_Driver_Ref); begin -- Free all handles while This.Free_File_Handles /= null loop declare H : constant Native_File_Handle_Ref := This.Free_File_Handles.Next; begin Destroy (This.Free_File_Handles); This.Free_File_Handles := H; end; end loop; while This.Free_Dir_Handles /= null loop declare H : constant Native_Directory_Handle_Ref := This.Free_Dir_Handles.Next; begin Destroy (This.Free_Dir_Handles); This.Free_Dir_Handles := H; end; end loop; Destroy (This); end Destroy; ------------ -- Create -- ------------ function Create (FS : out Native_FS_Driver; Root_Dir : Pathname) return Status_Kind is begin declare use type Ada.Directories.File_Kind; begin if Ada.Directories.Kind (Root_Dir) /= Ada.Directories.Directory then return Invalid_Argument; end if; exception when Ada.Directories.Name_Error => return Invalid_Argument; end; FS.Root_Dir := Ada.Strings.Unbounded.To_Unbounded_String (Root_Dir); return Status_Ok; end Create; ----------------- -- Create_Node -- ----------------- overriding function Create_Node (This : in out Native_FS_Driver; Path : Pathname; Kind : File_Kind) return Status_Kind is Abs_Path : constant Pathname := Absolute_Path (This, Path); begin case Kind is when Regular_File => declare File : Byte_IO.File_Type; begin begin Byte_IO.Create (File, Byte_IO.Out_File, Abs_Path); exception when Byte_IO.Status_Error | Byte_IO.Name_Error | Byte_IO.Use_Error => return Generic_Error; end; Byte_IO.Close (File); end; when Directory => begin Ada.Directories.Create_Directory (Abs_Path); exception when Ada.Directories.Name_Error | Ada.Directories.Use_Error => return Generic_Error; end; end case; return Status_Ok; end Create_Node; ---------------------- -- Create_Directory -- ---------------------- overriding function Create_Directory (This : in out Native_FS_Driver; Path : Pathname) return Status_Kind is begin return This.Create_Node (Absolute_Path (This, Path), Directory); end Create_Directory; ------------ -- Unlink -- ------------ overriding function Unlink (This : in out Native_FS_Driver; Path : Pathname) return Status_Kind is begin Ada.Directories.Delete_File (Absolute_Path (This, Path)); return Status_Ok; exception when Ada.Directories.Name_Error | Ada.Directories.Use_Error => return Generic_Error; end Unlink; ---------------------- -- Remove_Directory -- ---------------------- overriding function Remove_Directory (This : in out Native_FS_Driver; Path : Pathname) return Status_Kind is begin Ada.Directories.Delete_Directory (Absolute_Path (This, Path)); return Status_Ok; exception when Ada.Directories.Name_Error | Ada.Directories.Use_Error => return Generic_Error; end Remove_Directory; ------------ -- Rename -- ------------ overriding function Rename (This : in out Native_FS_Driver; Old_Path : Pathname; New_Path : Pathname) return Status_Kind is Old_Abs_Path : constant Pathname := Absolute_Path (This, Old_Path); New_Abs_Path : constant Pathname := Absolute_Path (This, New_Path); begin Ada.Directories.Rename (Old_Abs_Path, New_Abs_Path); return Status_Ok; exception when Ada.Directories.Name_Error | Ada.Directories.Use_Error => return Generic_Error; end Rename; ------------------- -- Truncate_File -- ------------------- overriding function Truncate_File (This : in out Native_FS_Driver; Path : Pathname; Length : IO_Count) return Status_Kind is pragma Unreferenced (This, Path, Length); begin -- ??? Implement this. This is not done at the moment as there seems to -- be no other way using standard Ada packages than do delete the file -- and re-create it. return Generic_Error; end Truncate_File; ---------- -- Open -- ---------- overriding function Open (This : in out Native_FS_Driver; Path : Pathname; Mode : File_Mode; Handle : out File_Handle_Ref) return Status_Kind is Result : Native_File_Handle_Ref := This.Get_Handle; begin begin Byte_IO.Open (File => Result.File, Mode => (case Mode is when Read_Only => Byte_IO.In_File, when Write_Only => Byte_IO.Out_File, when Read_Write => Byte_IO.Inout_File), Name => Absolute_Path (This, Path)); exception when Byte_IO.Status_Error | Byte_IO.Name_Error | Byte_IO.Use_Error => Destroy (Result); return Generic_Error; end; Handle := Result.all'Access; return Status_Ok; end Open; -------------------- -- Open_Directory -- -------------------- overriding function Open_Directory (This : in out Native_FS_Driver; Path : Pathname; Handle : out Directory_Handle_Ref) return Status_Kind is use Ada.Strings.Unbounded; Result : Native_Directory_Handle_Ref := This.Get_Handle; Search : Ada.Directories.Search_Type; begin begin Ada.Directories.Start_Search (Search, Absolute_Path (This, Path), ""); exception when Ada.Directories.Name_Error | Ada.Directories.Use_Error => This.Add_Free_Handle (Result); return Generic_Error; end; Result.Full_Name := +Path; while Ada.Directories.More_Entries (Search) loop declare use type Ada.Directories.File_Kind; E : Ada.Directories.Directory_Entry_Type; Kind : Ada.Directories.File_Kind; Name : Unbounded_String; begin Ada.Directories.Get_Next_Entry (Search, E); Kind := Ada.Directories.Kind (E); Name := +Ada.Directories.Simple_Name (E); -- HAL.Filesystem does not support special files, so just ignores -- them. As for current and parent directories entries, skip them -- for now as this makes tree traversal cumbersome to write. if Kind /= Ada.Directories.Special_File and then +Name /= "." and then +Name /= ".." then Result.Data.Append ((Kind => (case Kind is when Ada.Directories.Ordinary_File => Regular_File, when Ada.Directories.Directory => Directory, when others => raise Program_Error), Name => Name)); end if; end; end loop; Ada.Directories.End_Search (Search); -- Make sure entries are sorted so that we get determinism. This is -- convenient for testing. Directory_Data_Sorting.Sort (Result.Data); Handle := Result.all'Access; return Status_Ok; end Open_Directory; ---------- -- Read -- ---------- overriding function Read (This : in out Native_File_Handle; Data : out Byte_Array) return Status_Kind is begin for B of Data loop Byte_IO.Read (This.File, B); end loop; return Status_Ok; exception when Byte_IO.Mode_Error | Byte_IO.End_Error | Byte_IO.Data_Error => return Generic_Error; end Read; ----------- -- Write -- ----------- overriding function Write (This : in out Native_File_Handle; Data : Byte_Array) return Status_Kind is begin for B of Data loop Byte_IO.Write (This.File, B); end loop; return Status_Ok; exception when Byte_IO.Mode_Error | Byte_IO.Use_Error => return Generic_Error; end Write; ---------- -- Seek -- ---------- overriding function Seek (This : in out Native_File_Handle; Offset : IO_Count) return Status_Kind is begin Byte_IO.Set_Index (This.File, Byte_IO.Positive_Count (Offset)); return Status_Ok; end Seek; ----------- -- Close -- ----------- overriding function Close (This : in out Native_File_Handle) return Status_Kind is This_Ref : Native_File_Handle_Ref := This'Unrestricted_Access; begin begin Byte_IO.Close (This.File); exception when Byte_IO.Status_Error => return Generic_Error; end; This_Ref.FS.Add_Free_Handle (This_Ref); return Status_Ok; end Close; ---------------- -- Read_Entry -- ---------------- overriding function Read_Entry (This : in out Native_Directory_Handle; Entry_Number : Positive; Dir_Entry : out Directory_Entry) return Status_Kind is begin if Entry_Number > This.Data.Last_Index then return No_Such_File_Or_Directory; end if; Dir_Entry := (Entry_Type => This.Data.Element (Entry_Number).Kind); return Status_Ok; end Read_Entry; ---------------- -- Entry_Name -- ---------------- overriding function Entry_Name (This : in out Native_Directory_Handle; Entry_Number : Positive) return Pathname is begin if Entry_Number > This.Data.Last_Index then return ""; end if; return +This.Data.Element (Entry_Number).Name; end Entry_Name; ----------- -- Close -- ----------- overriding function Close (This : in out Native_Directory_Handle) return Status_Kind is This_Ref : Native_Directory_Handle_Ref := This'Unrestricted_Access; begin This.Data.Clear; This_Ref.FS.Add_Free_Handle (This_Ref); return Status_Ok; end Close; ---------- -- Join -- ---------- function Join (Prefix, Suffix : Pathname; Ignore_Absolute_Suffixes : Boolean) return Pathname is use Ada.Strings.Unbounded; package String_Vectors is new Ada.Containers.Vectors (Positive, Unbounded_String); Result : Unbounded_String := +Prefix; Names : String_Vectors.Vector; begin -- First, decompose Suffix into individual names: the following pushes -- the most local directory names first, then the most global ones. For -- instance, "a/b/c" will gives: Name => ("c", "b", "a"). declare Suffix_Acc : Unbounded_String := +Suffix; begin while Length (Suffix_Acc) > 0 loop begin declare Suffix : constant String := +Suffix_Acc; Next_Suffix : constant String := Ada.Directories.Containing_Directory (Suffix); Name : constant String := Ada.Directories.Simple_Name (Suffix); begin -- The following happens when Suffix is "." (the current -- directory). exit when Suffix = Next_Suffix; Names.Append (+Name); Suffix_Acc := +Next_Suffix; end; exception when Ada.Directories.Use_Error => -- Suffix is actually an absolute path. Forget about it and -- process it as a relative one. exit when Ignore_Absolute_Suffixes; return Suffix; end; end loop; end; -- Then, compose them using Ada.Directories.Compose so we have our -- result. for Name of reverse Names loop Result := +Ada.Directories.Compose (+Result, +Name); end loop; return +Result; end Join; end Native.Filesystem;
with Ada.Directories; with Ada.Unchecked_Deallocation; package body Native.Filesystem is -- ??? There are a bunch of 'Unrestricted_Access here because the -- HAL.Filesystem API embeds implicit references to filesystems. It -- woudl be good to make these references explicit at some point to -- avoid kludges. function "+" (S : Ada.Strings.Unbounded.Unbounded_String) return String renames Ada.Strings.Unbounded.To_String; function "+" (S : String) return Ada.Strings.Unbounded.Unbounded_String renames Ada.Strings.Unbounded.To_Unbounded_String; procedure Destroy is new Ada.Unchecked_Deallocation (Native_File_Handle, Native_File_Handle_Ref); procedure Destroy is new Ada.Unchecked_Deallocation (Native_Directory_Handle, Native_Directory_Handle_Ref); function "<" (Left, Right : Directory_Data_Entry) return Boolean is (Ada.Strings.Unbounded."<" (Left.Name, Right.Name)); package Directory_Data_Sorting is new Directory_Data_Vectors.Generic_Sorting; -- Most of the time, standard operations give us no reliable way to -- determine specifically what triggered a failure, so use the following -- error code as a "generic" one. Generic_Error : constant Status_Kind := Input_Output_Error; function Absolute_Path (This : Native_FS_Driver; Relative_Path : Pathname) return Pathname is (if Relative_Path = "" then +This.Root_Dir else Join (+This.Root_Dir, Relative_Path, True)); ---------------- -- Get_Handle -- ---------------- function Get_Handle (FS : in out Native_FS_Driver) return Native_File_Handle_Ref is Result : Native_File_Handle_Ref := FS.Free_File_Handles; begin if Result = null then Result := new Native_File_Handle' (FS => FS'Unrestricted_Access, others => <>); else FS.Free_File_Handles := Result.Next; end if; return Result; end Get_Handle; ---------------- -- Get_Handle -- ---------------- function Get_Handle (FS : in out Native_FS_Driver) return Native_Directory_Handle_Ref is Result : Native_Directory_Handle_Ref := FS.Free_Dir_Handles; begin if Result = null then Result := new Native_Directory_Handle' (FS => FS'Unrestricted_Access, others => <>); else FS.Free_Dir_Handles := Result.Next; end if; return Result; end Get_Handle; --------------------- -- Add_Free_Handle -- --------------------- procedure Add_Free_Handle (FS : in out Native_FS_Driver; Handle : in out Native_File_Handle_Ref) is begin Handle.Next := FS.Free_File_Handles; FS.Free_File_Handles := Handle; Handle := null; end Add_Free_Handle; --------------------- -- Add_Free_Handle -- --------------------- procedure Add_Free_Handle (FS : in out Native_FS_Driver; Handle : in out Native_Directory_Handle_Ref) is begin Handle.Next := FS.Free_Dir_Handles; FS.Free_Dir_Handles := Handle; Handle := null; end Add_Free_Handle; ------------- -- Destroy -- ------------- procedure Destroy (This : in out Native_FS_Driver_Ref) is procedure Destroy is new Ada.Unchecked_Deallocation (Native_FS_Driver, Native_FS_Driver_Ref); begin -- Free all handles while This.Free_File_Handles /= null loop declare H : constant Native_File_Handle_Ref := This.Free_File_Handles.Next; begin Destroy (This.Free_File_Handles); This.Free_File_Handles := H; end; end loop; while This.Free_Dir_Handles /= null loop declare H : constant Native_Directory_Handle_Ref := This.Free_Dir_Handles.Next; begin Destroy (This.Free_Dir_Handles); This.Free_Dir_Handles := H; end; end loop; Destroy (This); end Destroy; ------------ -- Create -- ------------ function Create (FS : out Native_FS_Driver; Root_Dir : Pathname) return Status_Kind is begin declare use type Ada.Directories.File_Kind; begin if Ada.Directories.Kind (Root_Dir) /= Ada.Directories.Directory then return Invalid_Argument; end if; exception when Ada.Directories.Name_Error => return Invalid_Argument; end; FS.Root_Dir := Ada.Strings.Unbounded.To_Unbounded_String (Root_Dir); return Status_Ok; end Create; ----------------- -- Create_Node -- ----------------- overriding function Create_Node (This : in out Native_FS_Driver; Path : Pathname; Kind : File_Kind) return Status_Kind is Abs_Path : constant Pathname := Absolute_Path (This, Path); begin case Kind is when Regular_File => declare File : Byte_IO.File_Type; begin begin Byte_IO.Create (File, Byte_IO.Out_File, Abs_Path); exception when Byte_IO.Status_Error | Byte_IO.Name_Error | Byte_IO.Use_Error => return Generic_Error; end; Byte_IO.Close (File); end; when Directory => begin Ada.Directories.Create_Directory (Abs_Path); exception when Ada.Directories.Name_Error | Ada.Directories.Use_Error => return Generic_Error; end; end case; return Status_Ok; end Create_Node; ---------------------- -- Create_Directory -- ---------------------- overriding function Create_Directory (This : in out Native_FS_Driver; Path : Pathname) return Status_Kind is begin return This.Create_Node (Absolute_Path (This, Path), Directory); end Create_Directory; ------------ -- Unlink -- ------------ overriding function Unlink (This : in out Native_FS_Driver; Path : Pathname) return Status_Kind is begin Ada.Directories.Delete_File (Absolute_Path (This, Path)); return Status_Ok; exception when Ada.Directories.Name_Error | Ada.Directories.Use_Error => return Generic_Error; end Unlink; ---------------------- -- Remove_Directory -- ---------------------- overriding function Remove_Directory (This : in out Native_FS_Driver; Path : Pathname) return Status_Kind is begin Ada.Directories.Delete_Directory (Absolute_Path (This, Path)); return Status_Ok; exception when Ada.Directories.Name_Error | Ada.Directories.Use_Error => return Generic_Error; end Remove_Directory; ------------ -- Rename -- ------------ overriding function Rename (This : in out Native_FS_Driver; Old_Path : Pathname; New_Path : Pathname) return Status_Kind is Old_Abs_Path : constant Pathname := Absolute_Path (This, Old_Path); New_Abs_Path : constant Pathname := Absolute_Path (This, New_Path); begin Ada.Directories.Rename (Old_Abs_Path, New_Abs_Path); return Status_Ok; exception when Ada.Directories.Name_Error | Ada.Directories.Use_Error => return Generic_Error; end Rename; ------------------- -- Truncate_File -- ------------------- overriding function Truncate_File (This : in out Native_FS_Driver; Path : Pathname; Length : IO_Count) return Status_Kind is pragma Unreferenced (This, Path, Length); begin -- ??? Implement this. This is not done at the moment as there seems to -- be no other way using standard Ada packages than do delete the file -- and re-create it. return Generic_Error; end Truncate_File; ---------- -- Open -- ---------- overriding function Open (This : in out Native_FS_Driver; Path : Pathname; Mode : File_Mode; Handle : out File_Handle_Ref) return Status_Kind is Result : Native_File_Handle_Ref := This.Get_Handle; begin begin Byte_IO.Open (File => Result.File, Mode => (case Mode is when Read_Only => Byte_IO.In_File, when Write_Only => Byte_IO.Out_File, when Read_Write => Byte_IO.Inout_File), Name => Absolute_Path (This, Path)); exception when Byte_IO.Status_Error | Byte_IO.Name_Error | Byte_IO.Use_Error => Destroy (Result); return Generic_Error; end; Handle := Result.all'Access; return Status_Ok; end Open; -------------------- -- Open_Directory -- -------------------- overriding function Open_Directory (This : in out Native_FS_Driver; Path : Pathname; Handle : out Directory_Handle_Ref) return Status_Kind is use Ada.Strings.Unbounded; Result : Native_Directory_Handle_Ref := This.Get_Handle; Search : Ada.Directories.Search_Type; begin begin Ada.Directories.Start_Search (Search, Absolute_Path (This, Path), ""); exception when Ada.Directories.Name_Error | Ada.Directories.Use_Error => This.Add_Free_Handle (Result); return Generic_Error; end; Result.Full_Name := +Path; while Ada.Directories.More_Entries (Search) loop declare use type Ada.Directories.File_Kind; E : Ada.Directories.Directory_Entry_Type; Kind : Ada.Directories.File_Kind; Name : Unbounded_String; begin Ada.Directories.Get_Next_Entry (Search, E); Kind := Ada.Directories.Kind (E); Name := +Ada.Directories.Simple_Name (E); -- HAL.Filesystem does not support special files, so just ignores -- them. As for current and parent directories entries, skip them -- for now as this makes tree traversal cumbersome to write. if Kind /= Ada.Directories.Special_File and then +Name /= "." and then +Name /= ".." then Result.Data.Append ((Kind => (case Kind is when Ada.Directories.Ordinary_File => Regular_File, when Ada.Directories.Directory => Directory, when others => raise Program_Error), Name => Name)); end if; end; end loop; Ada.Directories.End_Search (Search); -- Make sure entries are sorted so that we get determinism. This is -- convenient for testing. Directory_Data_Sorting.Sort (Result.Data); Handle := Result.all'Access; return Status_Ok; end Open_Directory; ---------- -- Read -- ---------- overriding function Read (This : in out Native_File_Handle; Data : out Byte_Array) return Status_Kind is begin for B of Data loop Byte_IO.Read (This.File, B); end loop; return Status_Ok; exception when Byte_IO.Mode_Error | Byte_IO.End_Error | Byte_IO.Data_Error => return Generic_Error; end Read; ----------- -- Write -- ----------- overriding function Write (This : in out Native_File_Handle; Data : Byte_Array) return Status_Kind is begin for B of Data loop Byte_IO.Write (This.File, B); end loop; return Status_Ok; exception when Byte_IO.Mode_Error | Byte_IO.Use_Error => return Generic_Error; end Write; ---------- -- Seek -- ---------- overriding function Seek (This : in out Native_File_Handle; Offset : IO_Count) return Status_Kind is begin Byte_IO.Set_Index (This.File, Byte_IO.Positive_Count (Offset + 1)); return Status_Ok; end Seek; ----------- -- Close -- ----------- overriding function Close (This : in out Native_File_Handle) return Status_Kind is This_Ref : Native_File_Handle_Ref := This'Unrestricted_Access; begin begin Byte_IO.Close (This.File); exception when Byte_IO.Status_Error => return Generic_Error; end; This_Ref.FS.Add_Free_Handle (This_Ref); return Status_Ok; end Close; ---------------- -- Read_Entry -- ---------------- overriding function Read_Entry (This : in out Native_Directory_Handle; Entry_Number : Positive; Dir_Entry : out Directory_Entry) return Status_Kind is begin if Entry_Number > This.Data.Last_Index then return No_Such_File_Or_Directory; end if; Dir_Entry := (Entry_Type => This.Data.Element (Entry_Number).Kind); return Status_Ok; end Read_Entry; ---------------- -- Entry_Name -- ---------------- overriding function Entry_Name (This : in out Native_Directory_Handle; Entry_Number : Positive) return Pathname is begin if Entry_Number > This.Data.Last_Index then return ""; end if; return +This.Data.Element (Entry_Number).Name; end Entry_Name; ----------- -- Close -- ----------- overriding function Close (This : in out Native_Directory_Handle) return Status_Kind is This_Ref : Native_Directory_Handle_Ref := This'Unrestricted_Access; begin This.Data.Clear; This_Ref.FS.Add_Free_Handle (This_Ref); return Status_Ok; end Close; ---------- -- Join -- ---------- function Join (Prefix, Suffix : Pathname; Ignore_Absolute_Suffixes : Boolean) return Pathname is use Ada.Strings.Unbounded; package String_Vectors is new Ada.Containers.Vectors (Positive, Unbounded_String); Result : Unbounded_String := +Prefix; Names : String_Vectors.Vector; begin -- First, decompose Suffix into individual names: the following pushes -- the most local directory names first, then the most global ones. For -- instance, "a/b/c" will gives: Name => ("c", "b", "a"). declare Suffix_Acc : Unbounded_String := +Suffix; begin while Length (Suffix_Acc) > 0 loop begin declare Suffix : constant String := +Suffix_Acc; Next_Suffix : constant String := Ada.Directories.Containing_Directory (Suffix); Name : constant String := Ada.Directories.Simple_Name (Suffix); begin -- The following happens when Suffix is "." (the current -- directory). exit when Suffix = Next_Suffix; Names.Append (+Name); Suffix_Acc := +Next_Suffix; end; exception when Ada.Directories.Use_Error => -- Suffix is actually an absolute path. Forget about it and -- process it as a relative one. exit when Ignore_Absolute_Suffixes; return Suffix; end; end loop; end; -- Then, compose them using Ada.Directories.Compose so we have our -- result. for Name of reverse Names loop Result := +Ada.Directories.Compose (+Result, +Name); end loop; return +Result; end Join; end Native.Filesystem;
Fix Seek()
Native.Filesystem: Fix Seek() Byte_IO.Set_Index starts at 1 where HAL.Filesystem starts at 0.
Ada
bsd-3-clause
simonjwright/Ada_Drivers_Library,AdaCore/Ada_Drivers_Library,lambourg/Ada_Drivers_Library,ellamosi/Ada_BMP_Library,Fabien-Chouteau/Ada_Drivers_Library,AdaCore/Ada_Drivers_Library,Fabien-Chouteau/Ada_Drivers_Library,simonjwright/Ada_Drivers_Library
4904a1717de45a395fee63d6e4b42bf84066ddc7
awa/plugins/awa-workspaces/src/awa-workspaces-modules.ads
awa/plugins/awa-workspaces/src/awa-workspaces-modules.ads
----------------------------------------------------------------------- -- awa-workspaces-module -- Module workspaces -- Copyright (C) 2011, 2012, 2017 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with ADO.Sessions; with ASF.Applications; with AWA.Modules; with AWA.Services.Contexts; with AWA.Workspaces.Models; with AWA.Users.Services; with AWA.Users.Models; with AWA.Events; package AWA.Workspaces.Modules is Not_Found : exception; -- The name under which the module is registered. NAME : constant String := "workspaces"; package Invite_User_Event is new AWA.Events.Definition (Name => "invite-user"); -- ------------------------------ -- Module workspaces -- ------------------------------ type Workspace_Module is new AWA.Modules.Module with private; type Workspace_Module_Access is access all Workspace_Module'Class; -- Initialize the workspaces module. overriding procedure Initialize (Plugin : in out Workspace_Module; App : in AWA.Modules.Application_Access; Props : in ASF.Applications.Config); -- Get the current workspace associated with the current user. -- If the user has not workspace, create one. procedure Get_Workspace (Session : in out ADO.Sessions.Master_Session; Context : in AWA.Services.Contexts.Service_Context_Access; Workspace : out AWA.Workspaces.Models.Workspace_Ref); -- Load the invitation from the access key and verify that the key is still valid. procedure Load_Invitation (Module : in Workspace_Module; Key : in String; Invitation : in out AWA.Workspaces.Models.Invitation_Ref'Class; Inviter : in out AWA.Users.Models.User_Ref); -- Accept the invitation identified by the access key. procedure Accept_Invitation (Module : in Workspace_Module; Key : in String); -- Send the invitation to the user. procedure Send_Invitation (Module : in Workspace_Module; Invitation : in out AWA.Workspaces.Models.Invitation_Ref'Class); -- Delete the member from the workspace. Remove the invitation if there is one. procedure Delete_Member (Module : in Workspace_Module; User_Id : in ADO.Identifier; Workspace_Id : in ADO.Identifier); private type Workspace_Module is new AWA.Modules.Module with record User_Manager : AWA.Users.Services.User_Service_Access; end record; end AWA.Workspaces.Modules;
----------------------------------------------------------------------- -- awa-workspaces-module -- Module workspaces -- Copyright (C) 2011, 2012, 2017 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with ADO.Sessions; with ASF.Applications; with AWA.Modules; with AWA.Services.Contexts; with AWA.Workspaces.Models; with AWA.Users.Services; with AWA.Users.Models; with AWA.Events; package AWA.Workspaces.Modules is Not_Found : exception; -- The name under which the module is registered. NAME : constant String := "workspaces"; package Invite_User_Event is new AWA.Events.Definition (Name => "invite-user"); -- ------------------------------ -- Module workspaces -- ------------------------------ type Workspace_Module is new AWA.Modules.Module with private; type Workspace_Module_Access is access all Workspace_Module'Class; -- Initialize the workspaces module. overriding procedure Initialize (Plugin : in out Workspace_Module; App : in AWA.Modules.Application_Access; Props : in ASF.Applications.Config); -- Get the current workspace associated with the current user. -- If the user has not workspace, create one. procedure Get_Workspace (Session : in out ADO.Sessions.Master_Session; Context : in AWA.Services.Contexts.Service_Context_Access; Workspace : out AWA.Workspaces.Models.Workspace_Ref); -- Load the invitation from the access key and verify that the key is still valid. procedure Load_Invitation (Module : in Workspace_Module; Key : in String; Invitation : in out AWA.Workspaces.Models.Invitation_Ref'Class; Inviter : in out AWA.Users.Models.User_Ref); -- Accept the invitation identified by the access key. procedure Accept_Invitation (Module : in Workspace_Module; Key : in String); -- Send the invitation to the user. procedure Send_Invitation (Module : in Workspace_Module; Invitation : in out AWA.Workspaces.Models.Invitation_Ref'Class); -- Delete the member from the workspace. Remove the invitation if there is one. procedure Delete_Member (Module : in Workspace_Module; Member_Id : in ADO.Identifier); private type Workspace_Module is new AWA.Modules.Module with record User_Manager : AWA.Users.Services.User_Service_Access; end record; end AWA.Workspaces.Modules;
Change Delete_Member to use the member id
Change Delete_Member to use the member id
Ada
apache-2.0
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
fbaa2ace35ebf9b70d3b8610ecbb656104fc4907
tools/druss-commands.ads
tools/druss-commands.ads
----------------------------------------------------------------------- -- druss-commands -- Commands available for Druss -- 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.Commands.Drivers; with Util.Commands.Consoles; with Util.Commands.Consoles.Text; with Druss.Gateways; package Druss.Commands is -- The list of fields that are printed on the console. type Field_Type is (F_IP_ADDR, F_BBOX_IP_ADDR, F_WAN_IP, F_ETHERNET, F_INTERNET, F_VOIP, F_HOSTNAME, F_CONNECTION, F_DEVTYPE, F_ACTIVE, F_LINK, F_WIFI, F_WIFI5, F_ACCESS_CONTROL, F_DYNDNS, F_DEVICES, F_UPTIME, F_COUNT, F_BOOL, F_CHANNEL, F_PROTOCOL, F_ENCRYPTION, F_SSID); -- The type of notice that are reported. type Notice_Type is (N_HELP, N_USAGE, N_INFO); -- Make the generic abstract console interface. package Consoles is new Util.Commands.Consoles (Field_Type => Field_Type, Notice_Type => Notice_Type); -- And the text console to write on stdout (a Gtk console could be done someday). package Text_Consoles is new Consoles.Text; type Context_Type is limited record Gateways : Druss.Gateways.Gateway_Vector; Console : Consoles.Console_Access; end record; package Drivers is new Util.Commands.Drivers (Context_Type => Context_Type, Driver_Name => "druss-drivers"); subtype Argument_List is Util.Commands.Argument_List; Driver : Drivers.Driver_Type; procedure Gateway_Command (Command : in Drivers.Command_Type'Class; Args : in Util.Commands.Argument_List'Class; Arg_Pos : in Positive; Process : access procedure (Gateway : in out Gateways.Gateway_Type; Param : in String); Context : in out Context_Type); procedure Initialize; -- Print the bbox API status. procedure Print_Status (Console : in Consoles.Console_Access; Field : in Field_Type; Value : in String); -- Print a ON/OFF status. procedure Print_On_Off (Console : in Consoles.Console_Access; Field : in Field_Type; Value : in String); -- Print a uptime. procedure Print_Uptime (Console : in Consoles.Console_Access; Field : in Field_Type; Value : in String); end Druss.Commands;
----------------------------------------------------------------------- -- druss-commands -- Commands available for Druss -- 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.Commands.Drivers; with Util.Commands.Consoles; with Util.Commands.Consoles.Text; with Druss.Gateways; package Druss.Commands is -- The list of fields that are printed on the console. type Field_Type is (F_IP_ADDR, F_BBOX_IP_ADDR, F_WAN_IP, F_ETHERNET, F_INTERNET, F_VOIP, F_HOSTNAME, F_CONNECTION, F_DEVTYPE, F_ACTIVE, F_LINK, F_WIFI, F_WIFI5, F_ACCESS_CONTROL, F_DYNDNS, F_DEVICES, F_UPTIME, F_COUNT, F_BOOL, F_CHANNEL, F_PROTOCOL, F_ENCRYPTION, F_SSID); -- The type of notice that are reported. type Notice_Type is (N_HELP, N_USAGE, N_INFO); -- Make the generic abstract console interface. package Consoles is new Util.Commands.Consoles (Field_Type => Field_Type, Notice_Type => Notice_Type); -- And the text console to write on stdout (a Gtk console could be done someday). package Text_Consoles is new Consoles.Text; type Context_Type is limited record Gateways : Druss.Gateways.Gateway_Vector; Console : Consoles.Console_Access; end record; package Drivers is new Util.Commands.Drivers (Context_Type => Context_Type, Driver_Name => "druss-drivers"); subtype Argument_List is Util.Commands.Argument_List; Driver : Drivers.Driver_Type; procedure Gateway_Command (Command : in Drivers.Command_Type'Class; Args : in Util.Commands.Argument_List'Class; Arg_Pos : in Positive; Process : access procedure (Gateway : in out Gateways.Gateway_Type; Param : in String); Context : in out Context_Type); procedure Initialize; -- Print the bbox API status. procedure Print_Status (Console : in Consoles.Console_Access; Field : in Field_Type; Value : in String); -- Print a ON/OFF status. procedure Print_On_Off (Console : in Consoles.Console_Access; Field : in Field_Type; Value : in String); -- Print a uptime. procedure Print_Uptime (Console : in Consoles.Console_Access; Field : in Field_Type; Value : in String); -- Print a performance measure in us or ms. procedure Print_Perf (Console : in Consoles.Console_Access; Field : in Field_Type; Value : in String); end Druss.Commands;
Declare the Print_Perf procedure
Declare the Print_Perf procedure
Ada
apache-2.0
stcarrez/bbox-ada-api
dd579e30f700d1950577dd153ee69603fda22434
awa/regtests/awa-mail-modules-tests.ads
awa/regtests/awa-mail-modules-tests.ads
----------------------------------------------------------------------- -- awa-mail-module-tests -- Unit tests for Mail module -- 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.Tests; with AWA.Tests; package AWA.Mail.Modules.Tests is procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite); type Test is new AWA.Tests.Test with null record; -- Create an email message and verify its content. procedure Test_Create_Message (T : in out Test); end AWA.Mail.Modules.Tests;
----------------------------------------------------------------------- -- awa-mail-module-tests -- Unit tests for Mail module -- Copyright (C) 2012, 2017 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Tests; with AWA.Tests; package AWA.Mail.Modules.Tests is procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite); type Test is new AWA.Tests.Test with null record; -- Create an email message with the given template and verify its content. procedure Test_Mail_Message (T : in out Test; Name : in String); -- Create an email message and verify its content. procedure Test_Create_Message (T : in out Test); -- Create an email message with Cc: and verify its content. procedure Test_Cc_Message (T : in out Test); -- Create an email message with Bcc: and verify its content. procedure Test_Bcc_Message (T : in out Test); end AWA.Mail.Modules.Tests;
Add new tests for mail Cc and Bcc
Add new tests for mail Cc and Bcc
Ada
apache-2.0
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
2fb6ea1636d53e7ace84064ccb56bfc4285925e8
posix-file.adb
posix-file.adb
with C_String; with Interfaces.C; package body POSIX.File is -- -- Functions to map between flag sets and discrete types. -- function Open_Access_Mode_To_Integer (Open_Access_Mode : in Open_Access_Mode_t) return Open_Flag_Integer_t is begin return Open_Access_Mode_Map (Open_Access_Mode); end Open_Access_Mode_To_Integer; function Open_Options_To_Integer (Open_Options : in Open_Options_t) return Open_Flag_Integer_t is Return_Options : Open_Flag_Integer_t := 0; begin for Open_Option in Open_Option_t range Open_Option_t'First .. Open_Option_t'Last loop if Open_Options (Open_Option) then Return_Options := Return_Options or Open_Option_Map (Open_Option); end if; --# assert (Open_Option <= Open_Option_t'Last) and --# (Open_Option >= Open_Option_t'First); end loop; return Return_Options; end Open_Options_To_Integer; -- -- Return False if any of the selected flags have been defined as invalid -- on the current platform. -- function Check_Support (Access_Mode : in Open_Access_Mode_t; Options : in Open_Options_t) return Boolean is Any_Unsupported : Boolean := False; begin if Open_Access_Mode_Map (Access_Mode) = Unsupported then Any_Unsupported := True; end if; if not Any_Unsupported then for Option in Open_Option_t range Open_Option_t'First .. Open_Option_t'Last loop if Options (Option) then if Open_Option_Map (Option) = Unsupported then Any_Unsupported := True; end if; end if; end loop; end if; return Any_Unsupported; end Check_Support; -- -- File opening/creation. -- function C_Open_Boundary (File_Name : in String; Flags : in Open_Flag_Integer_t; Mode : in Permissions.Mode_t) return Descriptor_t is --# hide C_Open_Boundary function C_Open (File_Name : in C_String.String_Not_Null_Ptr_t; Flags : in Open_Flag_Integer_t; Mode : in Permissions.Mode_t) return Descriptor_t; pragma Import (C, C_Open, "open"); begin declare C_File_Name_Buffer : aliased Interfaces.C.char_array := Interfaces.C.To_C (File_Name, Append_Nul => True); begin return C_Open (File_Name => C_String.To_C_String (C_File_Name_Buffer'Unchecked_Access), Flags => Flags, Mode => Mode); end; exception -- Do not propagate exceptions. when Storage_Error => Error.Set_Error (Error.Error_Out_Of_Memory); return -1; when others => Error.Set_Error (Error.Error_Unknown); return -1; end C_Open_Boundary; procedure Open (File_Name : in String; Access_Mode : in Open_Access_Mode_t; Options : in Open_Options_t; Non_Blocking : in Boolean; Mode : in Permissions.Mode_t; Descriptor : out Descriptor_t; Error_Value : out Error.Error_t) is C_Flags : Open_Flag_Integer_t; Supported : Boolean; begin Supported := Check_Support (Access_Mode => Access_Mode, Options => Options); -- Access mode and all options supported? if Supported then C_Flags := Open_Access_Mode_To_Integer (Access_Mode) or Open_Options_To_Integer (Options); -- Reject long filename. if File_Name'Last > File_Name_t'Last then Descriptor := -1; Error_Value := Error.Error_Name_Too_Long; else -- Set flags for non-blocking. if Non_Blocking then C_Flags := C_Flags or O_NONBLOCK; end if; -- Call system open() procedure. Descriptor := C_Open_Boundary (File_Name => File_Name, Flags => C_Flags, Mode => Mode); if Descriptor = -1 then Error_Value := Error.Get_Error; else Error_Value := Error.Error_None; end if; end if; else -- Unsupported options/access mode. Error_Value := Error.Error_Invalid_Argument; Descriptor := -1; end if; end Open; procedure Open_Read_Only (File_Name : in String; Non_Blocking : in Boolean; Descriptor : out Descriptor_t; Error_Value : out Error.Error_t) is Open_Options : constant Open_Options_t := Open_Options_t'(others => False); begin Open (File_Name => File_Name, Access_Mode => Read_Only, Non_Blocking => Non_Blocking, Options => Open_Options, Mode => Permissions.None, Descriptor => Descriptor, Error_Value => Error_Value); end Open_Read_Only; procedure Open_Write_Only (File_Name : in String; Non_Blocking : in Boolean; Descriptor : out Descriptor_t; Error_Value : out Error.Error_t) is Open_Options : constant Open_Options_t := Open_Options_t'(others => False); begin Open (File_Name => File_Name, Access_Mode => Write_Only, Non_Blocking => Non_Blocking, Options => Open_Options, Mode => Permissions.None, Descriptor => Descriptor, Error_Value => Error_Value); end Open_Write_Only; procedure Open_Exclusive (File_Name : in String; Non_Blocking : in Boolean; Mode : in Permissions.Mode_t; Descriptor : out Descriptor_t; Error_Value : out Error.Error_t) is Open_Options : constant Open_Options_t := Open_Options_t'(Create => True, Exclusive => True, others => False); begin Open (File_Name => File_Name, Access_Mode => Write_Only, Non_Blocking => Non_Blocking, Options => Open_Options, Mode => Mode, Descriptor => Descriptor, Error_Value => Error_Value); end Open_Exclusive; procedure Open_Append (File_Name : in String; Non_Blocking : in Boolean; Descriptor : out Descriptor_t; Error_Value : out Error.Error_t) is Open_Options : constant Open_Options_t := Open_Options_t'(Append => True, Create => True, others => False); begin Open (File_Name => File_Name, Access_Mode => Write_Only, Non_Blocking => Non_Blocking, Options => Open_Options, Mode => Permissions.None, Descriptor => Descriptor, Error_Value => Error_Value); end Open_Append; procedure Open_Truncate (File_Name : in String; Non_Blocking : in Boolean; Mode : in Permissions.Mode_t; Descriptor : out Descriptor_t; Error_Value : out Error.Error_t) is Open_Options : constant Open_Options_t := Open_Options_t'(Create => True, Truncate => True, others => False); begin Open (File_Name => File_Name, Access_Mode => Write_Only, Non_Blocking => Non_Blocking, Options => Open_Options, Mode => Mode, Descriptor => Descriptor, Error_Value => Error_Value); end Open_Truncate; procedure Open_Read_Write (File_Name : in String; Non_Blocking : in Boolean; Descriptor : out Descriptor_t; Error_Value : out Error.Error_t) is Open_Options : constant Open_Options_t := Open_Options_t'(others => False); begin Open (File_Name => File_Name, Access_Mode => Read_Write, Non_Blocking => Non_Blocking, Options => Open_Options, Mode => Permissions.None, Descriptor => Descriptor, Error_Value => Error_Value); end Open_Read_Write; procedure Open_Create (File_Name : in String; Non_Blocking : in Boolean; Mode : in Permissions.Mode_t; Descriptor : out Descriptor_t; Error_Value : out Error.Error_t) is Open_Options : constant Open_Options_t := Open_Options_t'(Create => True, others => False); begin Open (File_Name => File_Name, Access_Mode => Write_Only, Non_Blocking => Non_Blocking, Options => Open_Options, Mode => Mode, Descriptor => Descriptor, Error_Value => Error_Value); end Open_Create; -- -- File permissions. -- procedure Change_Descriptor_Mode (Descriptor : in Valid_Descriptor_t; Mode : in Permissions.Mode_t; Error_Value : out Error.Error_t) is Return_Value : Error.Return_Value_t; function C_fchmod (Descriptor : in Valid_Descriptor_t; Mode : in Permissions.Mode_t) return Error.Return_Value_t; pragma Import (C, C_fchmod, "fchmod"); begin Return_Value := C_fchmod (Descriptor => Descriptor, Mode => Mode); case Return_Value is when -1 => Error_Value := Error.Get_Error; when 0 => Error_Value := Error.Error_None; end case; end Change_Descriptor_Mode; procedure Change_Mode (File_Name : in String; Mode : in Permissions.Mode_t; Error_Value : out Error.Error_t) is Descriptor : Descriptor_t; begin Open_Read_Only (File_Name => File_Name, Non_Blocking => False, Descriptor => Descriptor, Error_Value => Error_Value); if Error_Value = Error.Error_None then Change_Descriptor_Mode (Descriptor => Descriptor, Mode => Mode, Error_Value => Error_Value); end if; end Change_Mode; -- -- File ownership. -- procedure Change_Descriptor_Ownership (Descriptor : in Valid_Descriptor_t; Owner : in User_DB.User_ID_t; Group : in User_DB.Group_ID_t; Error_Value : out Error.Error_t) is Return_Value : Error.Return_Value_t; function C_fchown (Descriptor : in Valid_Descriptor_t; Owner : in User_DB.User_ID_t; Group : in User_DB.Group_ID_t) return Error.Return_Value_t; pragma Import (C, C_fchown, "fchown"); begin Return_Value := C_fchown (Descriptor => Descriptor, Owner => Owner, Group => Group); case Return_Value is when -1 => Error_Value := Error.Get_Error; when 0 => Error_Value := Error.Error_None; end case; end Change_Descriptor_Ownership; procedure Change_Ownership (File_Name : in String; Owner : in User_DB.User_ID_t; Group : in User_DB.Group_ID_t; Error_Value : out Error.Error_t) is Descriptor : Descriptor_t; begin Open_Read_Only (File_Name => File_Name, Non_Blocking => False, Descriptor => Descriptor, Error_Value => Error_Value); if Error_Value = Error.Error_None then Change_Descriptor_Ownership (Descriptor => Descriptor, Owner => Owner, Group => Group, Error_Value => Error_Value); end if; end Change_Ownership; -- -- File removal. -- function Unlink_Boundary (File_Name : in String) return Error.Return_Value_t is --# hide Unlink_Boundary function C_Unlink (File_Name : in C_String.String_Not_Null_Ptr_t) return Error.Return_Value_t; pragma Import (C, C_Unlink, "unlink"); begin declare C_File_Name_Buffer : aliased Interfaces.C.char_array := Interfaces.C.To_C (File_Name, Append_Nul => True); begin return C_Unlink (C_String.To_C_String (C_File_Name_Buffer'Unchecked_Access)); end; exception -- Do not propagate exceptions. when Storage_Error => Error.Set_Error (Error.Error_Out_Of_Memory); return -1; when others => Error.Set_Error (Error.Error_Unknown); return -1; end Unlink_Boundary; procedure Unlink (File_Name : in String; Error_Value : out Error.Error_t) is begin case Unlink_Boundary (File_Name) is when 0 => Error_Value := Error.Error_None; when -1 => Error_Value := Error.Get_Error; end case; end Unlink; -- -- File closing. -- procedure Close (Descriptor : in Valid_Descriptor_t; Error_Value : out Error.Error_t) is function C_Close (Descriptor : in Valid_Descriptor_t) return Error.Return_Value_t; pragma Import (C, C_Close, "close"); begin case C_Close (Descriptor) is when 0 => Error_Value := Error.Error_None; when -1 => Error_Value := Error.Get_Error; end case; end Close; end POSIX.File;
with C_String; with Interfaces.C; package body POSIX.File is -- -- Functions to map between flag sets and discrete types. -- function Open_Access_Mode_To_Integer (Open_Access_Mode : in Open_Access_Mode_t) return Open_Flag_Integer_t is begin return Open_Access_Mode_Map (Open_Access_Mode); end Open_Access_Mode_To_Integer; function Open_Options_To_Integer (Open_Options : in Open_Options_t) return Open_Flag_Integer_t is Return_Options : Open_Flag_Integer_t := 0; begin for Open_Option in Open_Option_t range Open_Option_t'First .. Open_Option_t'Last loop if Open_Options (Open_Option) then Return_Options := Return_Options or Open_Option_Map (Open_Option); end if; --# assert (Open_Option <= Open_Option_t'Last) and --# (Open_Option >= Open_Option_t'First); end loop; return Return_Options; end Open_Options_To_Integer; -- -- Return False if any of the selected flags have been defined as invalid -- on the current platform. -- function Check_Support (Access_Mode : in Open_Access_Mode_t; Options : in Open_Options_t) return Boolean is Any_Unsupported : Boolean := False; begin if Open_Access_Mode_Map (Access_Mode) = Unsupported then Any_Unsupported := True; end if; if not Any_Unsupported then for Option in Open_Option_t range Open_Option_t'First .. Open_Option_t'Last loop if Options (Option) then if Open_Option_Map (Option) = Unsupported then Any_Unsupported := True; end if; end if; --# assert (Option <= Open_Option_t'Last) and --# (Option >= Open_Option_t'First); end loop; end if; return Any_Unsupported; end Check_Support; -- -- File opening/creation. -- function C_Open_Boundary (File_Name : in String; Flags : in Open_Flag_Integer_t; Mode : in Permissions.Mode_t) return Descriptor_t is --# hide C_Open_Boundary function C_Open (File_Name : in C_String.String_Not_Null_Ptr_t; Flags : in Open_Flag_Integer_t; Mode : in Permissions.Mode_t) return Descriptor_t; pragma Import (C, C_Open, "open"); begin declare C_File_Name_Buffer : aliased Interfaces.C.char_array := Interfaces.C.To_C (File_Name, Append_Nul => True); begin return C_Open (File_Name => C_String.To_C_String (C_File_Name_Buffer'Unchecked_Access), Flags => Flags, Mode => Mode); end; exception -- Do not propagate exceptions. when Storage_Error => Error.Set_Error (Error.Error_Out_Of_Memory); return -1; when others => Error.Set_Error (Error.Error_Unknown); return -1; end C_Open_Boundary; procedure Open (File_Name : in String; Access_Mode : in Open_Access_Mode_t; Options : in Open_Options_t; Non_Blocking : in Boolean; Mode : in Permissions.Mode_t; Descriptor : out Descriptor_t; Error_Value : out Error.Error_t) is C_Flags : Open_Flag_Integer_t; Supported : Boolean; begin Supported := Check_Support (Access_Mode => Access_Mode, Options => Options); -- Access mode and all options supported? if Supported then C_Flags := Open_Access_Mode_To_Integer (Access_Mode) or Open_Options_To_Integer (Options); -- Reject long filename. if File_Name'Last > File_Name_t'Last then Descriptor := -1; Error_Value := Error.Error_Name_Too_Long; else -- Set flags for non-blocking. if Non_Blocking then C_Flags := C_Flags or O_NONBLOCK; end if; -- Call system open() procedure. Descriptor := C_Open_Boundary (File_Name => File_Name, Flags => C_Flags, Mode => Mode); if Descriptor = -1 then Error_Value := Error.Get_Error; else Error_Value := Error.Error_None; end if; end if; else -- Unsupported options/access mode. Error_Value := Error.Error_Invalid_Argument; Descriptor := -1; end if; end Open; procedure Open_Read_Only (File_Name : in String; Non_Blocking : in Boolean; Descriptor : out Descriptor_t; Error_Value : out Error.Error_t) is Open_Options : constant Open_Options_t := Open_Options_t'(others => False); begin Open (File_Name => File_Name, Access_Mode => Read_Only, Non_Blocking => Non_Blocking, Options => Open_Options, Mode => Permissions.None, Descriptor => Descriptor, Error_Value => Error_Value); end Open_Read_Only; procedure Open_Write_Only (File_Name : in String; Non_Blocking : in Boolean; Descriptor : out Descriptor_t; Error_Value : out Error.Error_t) is Open_Options : constant Open_Options_t := Open_Options_t'(others => False); begin Open (File_Name => File_Name, Access_Mode => Write_Only, Non_Blocking => Non_Blocking, Options => Open_Options, Mode => Permissions.None, Descriptor => Descriptor, Error_Value => Error_Value); end Open_Write_Only; procedure Open_Exclusive (File_Name : in String; Non_Blocking : in Boolean; Mode : in Permissions.Mode_t; Descriptor : out Descriptor_t; Error_Value : out Error.Error_t) is Open_Options : constant Open_Options_t := Open_Options_t'(Create => True, Exclusive => True, others => False); begin Open (File_Name => File_Name, Access_Mode => Write_Only, Non_Blocking => Non_Blocking, Options => Open_Options, Mode => Mode, Descriptor => Descriptor, Error_Value => Error_Value); end Open_Exclusive; procedure Open_Append (File_Name : in String; Non_Blocking : in Boolean; Descriptor : out Descriptor_t; Error_Value : out Error.Error_t) is Open_Options : constant Open_Options_t := Open_Options_t'(Append => True, Create => True, others => False); begin Open (File_Name => File_Name, Access_Mode => Write_Only, Non_Blocking => Non_Blocking, Options => Open_Options, Mode => Permissions.None, Descriptor => Descriptor, Error_Value => Error_Value); end Open_Append; procedure Open_Truncate (File_Name : in String; Non_Blocking : in Boolean; Mode : in Permissions.Mode_t; Descriptor : out Descriptor_t; Error_Value : out Error.Error_t) is Open_Options : constant Open_Options_t := Open_Options_t'(Create => True, Truncate => True, others => False); begin Open (File_Name => File_Name, Access_Mode => Write_Only, Non_Blocking => Non_Blocking, Options => Open_Options, Mode => Mode, Descriptor => Descriptor, Error_Value => Error_Value); end Open_Truncate; procedure Open_Read_Write (File_Name : in String; Non_Blocking : in Boolean; Descriptor : out Descriptor_t; Error_Value : out Error.Error_t) is Open_Options : constant Open_Options_t := Open_Options_t'(others => False); begin Open (File_Name => File_Name, Access_Mode => Read_Write, Non_Blocking => Non_Blocking, Options => Open_Options, Mode => Permissions.None, Descriptor => Descriptor, Error_Value => Error_Value); end Open_Read_Write; procedure Open_Create (File_Name : in String; Non_Blocking : in Boolean; Mode : in Permissions.Mode_t; Descriptor : out Descriptor_t; Error_Value : out Error.Error_t) is Open_Options : constant Open_Options_t := Open_Options_t'(Create => True, others => False); begin Open (File_Name => File_Name, Access_Mode => Write_Only, Non_Blocking => Non_Blocking, Options => Open_Options, Mode => Mode, Descriptor => Descriptor, Error_Value => Error_Value); end Open_Create; -- -- File permissions. -- procedure Change_Descriptor_Mode (Descriptor : in Valid_Descriptor_t; Mode : in Permissions.Mode_t; Error_Value : out Error.Error_t) is Return_Value : Error.Return_Value_t; function C_fchmod (Descriptor : in Valid_Descriptor_t; Mode : in Permissions.Mode_t) return Error.Return_Value_t; pragma Import (C, C_fchmod, "fchmod"); begin Return_Value := C_fchmod (Descriptor => Descriptor, Mode => Mode); case Return_Value is when -1 => Error_Value := Error.Get_Error; when 0 => Error_Value := Error.Error_None; end case; end Change_Descriptor_Mode; procedure Change_Mode (File_Name : in String; Mode : in Permissions.Mode_t; Error_Value : out Error.Error_t) is Descriptor : Descriptor_t; begin Open_Read_Only (File_Name => File_Name, Non_Blocking => False, Descriptor => Descriptor, Error_Value => Error_Value); if Error_Value = Error.Error_None then Change_Descriptor_Mode (Descriptor => Descriptor, Mode => Mode, Error_Value => Error_Value); end if; end Change_Mode; -- -- File ownership. -- procedure Change_Descriptor_Ownership (Descriptor : in Valid_Descriptor_t; Owner : in User_DB.User_ID_t; Group : in User_DB.Group_ID_t; Error_Value : out Error.Error_t) is Return_Value : Error.Return_Value_t; function C_fchown (Descriptor : in Valid_Descriptor_t; Owner : in User_DB.User_ID_t; Group : in User_DB.Group_ID_t) return Error.Return_Value_t; pragma Import (C, C_fchown, "fchown"); begin Return_Value := C_fchown (Descriptor => Descriptor, Owner => Owner, Group => Group); case Return_Value is when -1 => Error_Value := Error.Get_Error; when 0 => Error_Value := Error.Error_None; end case; end Change_Descriptor_Ownership; procedure Change_Ownership (File_Name : in String; Owner : in User_DB.User_ID_t; Group : in User_DB.Group_ID_t; Error_Value : out Error.Error_t) is Descriptor : Descriptor_t; begin Open_Read_Only (File_Name => File_Name, Non_Blocking => False, Descriptor => Descriptor, Error_Value => Error_Value); if Error_Value = Error.Error_None then Change_Descriptor_Ownership (Descriptor => Descriptor, Owner => Owner, Group => Group, Error_Value => Error_Value); end if; end Change_Ownership; -- -- File removal. -- function Unlink_Boundary (File_Name : in String) return Error.Return_Value_t is --# hide Unlink_Boundary function C_Unlink (File_Name : in C_String.String_Not_Null_Ptr_t) return Error.Return_Value_t; pragma Import (C, C_Unlink, "unlink"); begin declare C_File_Name_Buffer : aliased Interfaces.C.char_array := Interfaces.C.To_C (File_Name, Append_Nul => True); begin return C_Unlink (C_String.To_C_String (C_File_Name_Buffer'Unchecked_Access)); end; exception -- Do not propagate exceptions. when Storage_Error => Error.Set_Error (Error.Error_Out_Of_Memory); return -1; when others => Error.Set_Error (Error.Error_Unknown); return -1; end Unlink_Boundary; procedure Unlink (File_Name : in String; Error_Value : out Error.Error_t) is begin case Unlink_Boundary (File_Name) is when 0 => Error_Value := Error.Error_None; when -1 => Error_Value := Error.Get_Error; end case; end Unlink; -- -- File closing. -- procedure Close (Descriptor : in Valid_Descriptor_t; Error_Value : out Error.Error_t) is function C_Close (Descriptor : in Valid_Descriptor_t) return Error.Return_Value_t; pragma Import (C, C_Close, "close"); begin case C_Close (Descriptor) is when 0 => Error_Value := Error.Error_None; when -1 => Error_Value := Error.Get_Error; end case; end Close; end POSIX.File;
Add loop assertion.
Add loop assertion.
Ada
isc
io7m/coreland-posix-ada,io7m/coreland-posix-ada,io7m/coreland-posix-ada
800ff90060a88abd3959376fadef80f04eda0da4
src/atlas-microblog-beans.adb
src/atlas-microblog-beans.adb
----------------------------------------------------------------------- -- atlas-microblog-beans -- Beans for module microblog -- 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 ADO.Sessions; with ADO.Queries; with ASF.Events.Faces.Actions; package body Atlas.Microblog.Beans is -- ------------------------------ -- Example of action method. -- ------------------------------ procedure Post (Bean : in out Microblog_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is begin Bean.Module.Create (Bean.Post); Outcome := Ada.Strings.Unbounded.To_Unbounded_String ("post-response"); end Post; package Action_Binding is new ASF.Events.Faces.Actions.Action_Method.Bind (Bean => Microblog_Bean, Method => Post, Name => "post"); Microblog_Bean_Binding : aliased constant Util.Beans.Methods.Method_Binding_Array := (Action_Binding.Proxy'Access, null); -- ------------------------------ -- Get the value identified by the name. -- ------------------------------ overriding function Get_Value (From : in Microblog_Bean; Name : in String) return Util.Beans.Objects.Object is begin if From.Post.Is_Null then return Util.Beans.Objects.Null_Object; else return From.Post.Get_Value (Name); end if; end Get_Value; -- ------------------------------ -- Set the value identified by the name. -- ------------------------------ overriding procedure Set_Value (From : in out Microblog_Bean; Name : in String; Value : in Util.Beans.Objects.Object) is begin if Name = "message" then From.Post.Set_Message (Util.Beans.Objects.To_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 Microblog_Bean) return Util.Beans.Methods.Method_Binding_Array_Access is pragma Unreferenced (From); begin return Microblog_Bean_Binding'Access; end Get_Method_Bindings; -- ------------------------------ -- Create the Microblog_Bean bean instance. -- ------------------------------ function Create_Microblog_Bean (Module : in Atlas.Microblog.Modules.Microblog_Module_Access) return Util.Beans.Basic.Readonly_Bean_Access is Object : constant Microblog_Bean_Access := new Microblog_Bean; begin Object.Module := Module; return Object.all'Access; end Create_Microblog_Bean; -- ------------------------------ -- Create the a bean to display the list of microblog posts. -- ------------------------------ function Create_List_Bean (Module : in Atlas.Microblog.Modules.Microblog_Module_Access) return Util.Beans.Basic.Readonly_Bean_Access is use Models; Result : constant List_Info_List_Bean_Access := new List_Info_List_Bean; Session : ADO.Sessions.Session := Module.Get_Session; Query : ADO.Queries.Context; begin Query.Set_Query (Atlas.Microblog.Models.Query_List); Atlas.Microblog.Models.List (Result.all, Session, Query); return Result.all'Access; end Create_List_Bean; end Atlas.Microblog.Beans;
----------------------------------------------------------------------- -- atlas-microblog-beans -- Beans for module microblog -- Copyright (C) 2012, 2017 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with ADO.Sessions; with ADO.Queries; with ASF.Events.Faces.Actions; with AWA.Events.Action_Method; package body Atlas.Microblog.Beans is -- ------------------------------ -- Example of action method. -- ------------------------------ procedure Post (Bean : in out Microblog_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is begin Bean.Module.Create (Bean.Post); Outcome := Ada.Strings.Unbounded.To_Unbounded_String ("post-response"); end Post; -- ------------------------------ -- Post a message when some event is received. -- ------------------------------ procedure Post (Bean : in out Microblog_Bean; Event : in AWA.Events.Module_Event'Class) is begin Bean.Module.Create (Bean.Post); end Post; package Action_Binding is new ASF.Events.Faces.Actions.Action_Method.Bind (Bean => Microblog_Bean, Method => Post, Name => "post"); package Event_Action_Binding is new AWA.Events.Action_Method.Bind (Bean => Microblog_Bean, Method => Post, Name => "post_event"); Microblog_Bean_Binding : aliased constant Util.Beans.Methods.Method_Binding_Array := (Action_Binding.Proxy'Access, Event_Action_Binding.Proxy'Access); -- ------------------------------ -- Get the value identified by the name. -- ------------------------------ overriding function Get_Value (From : in Microblog_Bean; Name : in String) return Util.Beans.Objects.Object is begin if From.Post.Is_Null then return Util.Beans.Objects.Null_Object; else return From.Post.Get_Value (Name); end if; end Get_Value; -- ------------------------------ -- Set the value identified by the name. -- ------------------------------ overriding procedure Set_Value (From : in out Microblog_Bean; Name : in String; Value : in Util.Beans.Objects.Object) is begin if Name = "message" then From.Post.Set_Message (Util.Beans.Objects.To_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 Microblog_Bean) return Util.Beans.Methods.Method_Binding_Array_Access is pragma Unreferenced (From); begin return Microblog_Bean_Binding'Access; end Get_Method_Bindings; -- ------------------------------ -- Create the Microblog_Bean bean instance. -- ------------------------------ function Create_Microblog_Bean (Module : in Atlas.Microblog.Modules.Microblog_Module_Access) return Util.Beans.Basic.Readonly_Bean_Access is Object : constant Microblog_Bean_Access := new Microblog_Bean; begin Object.Module := Module; return Object.all'Access; end Create_Microblog_Bean; -- ------------------------------ -- Create the a bean to display the list of microblog posts. -- ------------------------------ function Create_List_Bean (Module : in Atlas.Microblog.Modules.Microblog_Module_Access) return Util.Beans.Basic.Readonly_Bean_Access is use Models; Result : constant List_Info_List_Bean_Access := new List_Info_List_Bean; Session : ADO.Sessions.Session := Module.Get_Session; Query : ADO.Queries.Context; begin Query.Set_Query (Atlas.Microblog.Models.Query_List); Atlas.Microblog.Models.List (Result.all, Session, Query); return Result.all'Access; end Create_List_Bean; end Atlas.Microblog.Beans;
Implement the Post procedure with an event parameter and register the operation as event bean operation
Implement the Post procedure with an event parameter and register the operation as event bean operation
Ada
apache-2.0
stcarrez/atlas
0fd6923873479ec8cf28ffcc0d4a43bfdbe9e54c
src/gen-commands-generate.adb
src/gen-commands-generate.adb
----------------------------------------------------------------------- -- gen-commands-generate -- Generate command for dynamo -- Copyright (C) 2011, 2012, 2015 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with GNAT.Command_Line; with Ada.Directories; with Ada.Text_IO; package body Gen.Commands.Generate is use GNAT.Command_Line; use Ada.Directories; -- ------------------------------ -- Execute the command with the arguments. -- ------------------------------ procedure Execute (Cmd : in Command; Generator : in out Gen.Generator.Handler) is pragma Unreferenced (Cmd); File_Count : Natural := 0; begin Generator.Read_Project ("dynamo.xml", True); Gen.Generator.Read_Mappings (Generator); -- Parse the command line for the --package option. loop case Getopt ("p: ? -package:") is when ASCII.NUL => exit; when '-' => if Full_Switch = "-package" then Generator.Enable_Package_Generation (Parameter); end if; when 'p' => Generator.Enable_Package_Generation (Parameter); when others => null; end case; end loop; -- Read the model files. loop declare Model_File : constant String := Get_Argument; begin exit when Model_File'Length = 0; File_Count := File_Count + 1; if Ada.Directories.Exists (Model_File) and then Ada.Directories.Kind (Model_File) = Ada.Directories.Directory then Gen.Generator.Read_Models (Generator, Model_File); else Gen.Generator.Read_Model (Generator, Model_File, False); end if; end; end loop; if File_Count = 0 then Gen.Generator.Read_Models (Generator, "db"); end if; -- Run the generation. Gen.Generator.Prepare (Generator); Gen.Generator.Generate_All (Generator); Gen.Generator.Finish (Generator); Generator.Save_Project; 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 ("generate: Generate the Ada files for the database model or queries"); Put_Line ("Usage: generate [--package NAME] [MODEL ...]"); New_Line; Put_Line (" Read the XML/XMI model description (Hibernate mapping, query mapping, ...)"); Put_Line (" and generate the Ada model files that correspond to the mapping."); Put_Line (" The --package option allows to generate only the package with the given name."); Put_Line (" The default is to generate all the packages that are recognized."); end Help; end Gen.Commands.Generate;
----------------------------------------------------------------------- -- gen-commands-generate -- Generate command for dynamo -- Copyright (C) 2011, 2012, 2015, 2017 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with GNAT.Command_Line; with Ada.Directories; with Ada.Text_IO; package body Gen.Commands.Generate is use GNAT.Command_Line; use Ada.Directories; -- ------------------------------ -- 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, Args); File_Count : Natural := 0; begin Generator.Read_Project ("dynamo.xml", True); Gen.Generator.Read_Mappings (Generator); -- Parse the command line for the --package option. loop case Getopt ("p: ? -package:") is when ASCII.NUL => exit; when '-' => if Full_Switch = "-package" then Generator.Enable_Package_Generation (Parameter); end if; when 'p' => Generator.Enable_Package_Generation (Parameter); when others => null; end case; end loop; -- Read the model files. loop declare Model_File : constant String := Get_Argument; begin exit when Model_File'Length = 0; File_Count := File_Count + 1; if Ada.Directories.Exists (Model_File) and then Ada.Directories.Kind (Model_File) = Ada.Directories.Directory then Gen.Generator.Read_Models (Generator, Model_File); else Gen.Generator.Read_Model (Generator, Model_File, False); end if; end; end loop; if File_Count = 0 then Gen.Generator.Read_Models (Generator, "db"); end if; -- Run the generation. Gen.Generator.Prepare (Generator); Gen.Generator.Generate_All (Generator); Gen.Generator.Finish (Generator); Generator.Save_Project; 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 ("generate: Generate the Ada files for the database model or queries"); Put_Line ("Usage: generate [--package NAME] [MODEL ...]"); New_Line; Put_Line (" Read the XML/XMI model description (Hibernate mapping, query mapping, ...)"); Put_Line (" and generate the Ada model files that correspond to the mapping."); Put_Line (" The --package option allows to generate only the package with the given name."); Put_Line (" The default is to generate all the packages that are recognized."); end Help; end Gen.Commands.Generate;
Update to use the new command implementation
Update to use the new command implementation
Ada
apache-2.0
stcarrez/dynamo,stcarrez/dynamo,stcarrez/dynamo
1001007792cf8df0d4781725a2c585a6056359ec
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 Pointer is System.Address; 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#; --------------------------------------------------------------------------- --------------------------- -- S U B P R O G R A M S -- --------------------------- --------------------------------------------------------------------------- -- Context Management function Create_Context ( ADevice: in Device; Attr_List: in Pointer ) return Context; Pragma Import (StdCall, Create_Context, "alcCreateContext"); --ALC_API ALCcontext * ALC_APIENTRY alcCreateContext( ALCdevice *device, const ALCint* attrlist ); function Make_Context_Current (AContext: in Context) return Bool; Pragma Import (StdCall, Make_Context_Current, "alcMakeContextCurrent"); --ALC_API ALCboolean ALC_APIENTRY alcMakeContextCurrent( ALCcontext *context ); procedure Process_Context (AContext: in Context); Pragma Import (StdCall, Process_Context, "alcProcessContext"); --ALC_API void ALC_APIENTRY alcProcessContext( ALCcontext *context ); procedure Suspend_Context (AContext: in Context); Pragma Import (StdCall, Suspend_Context, "alcSuspendContext"); --ALC_API void ALC_APIENTRY alcSuspendContext( ALCcontext *context ); procedure Destroy_Context (AContext: in Context); Pragma Import (StdCall, Destroy_Context, "alcDestroyContext"); --ALC_API void ALC_APIENTRY alcDestroyContext( ALCcontext *context ); function Get_Current_Context return Context; Pragma Import (StdCall, Get_Current_Context, "alcGetCurrentContext"); --ALC_API ALCcontext * ALC_APIENTRY alcGetCurrentContext( void ); function Get_Contexts_Device (AContext: in Context) return Device; Pragma Import (StdCall, Get_Contexts_Device, "alcGetContextsDevice"); --ALC_API ALCdevice* ALC_APIENTRY alcGetContextsDevice( ALCcontext *context ); -- Device Management function Open_Device (Device_Name: in String) return Device; Pragma Inline (Open_Device); function Close_Device (ADevice: in Device) return Bool; Pragma Import (StdCall, Close_Device, "alcCloseDevice"); -- Error support. -- Obtain the most recent Context error function Get_Error (ADevice: in Device) return Enum; Pragma Import (StdCall, Get_Error, "alcGetError"); -- Extension support. -- Query for the presence of an extension, and obtain any appropriate -- function pointers and enum values. function Is_Extension_Present ( ADevice: in Device; Ext_Name: in String ) return Bool; Pragma Inline (Is_Extension_Present); function Get_Proc_Address ( ADevice: in Device; Func_Name: in String ) return Pointer; Pragma Inline (Get_Proc_Address); function Get_Enum_Value ( ADevice: in Device; Enum_Name: in String ) return Enum; Pragma Inline (Get_Enum_Value); -- Query functions function Get_String (ADevice: in Device; Param: in Enum) return String; Pragma Inline (Get_String); procedure Get_Integer ( ADevice: in Device; Param: in Enum; Size: in SizeI; Data: in Pointer ); Pragma Import (StdCall, Get_Integer, "alcGetIntegerv"); -- Capture functions function Capture_Open_Device ( Device_Name: in String; Frequency: in UInt; Format: in Enum; Buffer_Size: in SizeI ) return Device; Pragma Inline (Capture_Open_Device); function Capture_Close_Device (ADevice: in Device) return Bool; Pragma Import (StdCall, Capture_Close_Device, "alcCaptureCloseDevice"); procedure Capture_Start (ADevice: in Device); Pragma Import (StdCall, Capture_Start, "alcCaptureStart"); procedure Capture_Stop (ADevice: in Device); Pragma Import (StdCall, Capture_Stop, "alcCaptureStop"); procedure Capture_Samples ( ADevice: in Device; Buffer: in Pointer; Samples: in SizeI ); Pragma Import (StdCall, Capture_Samples, "alcCaptureSamples"); --------------------------------------------------------------------------- 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 Pointer is System.Address; 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#; --------------------------------------------------------------------------- --------------------------- -- S U B P R O G R A M S -- --------------------------- --------------------------------------------------------------------------- -- Context Management function Create_Context ( ADevice: in Device; Attr_List: in Pointer ) return Context; --ALC_API ALCcontext * ALC_APIENTRY alcCreateContext( ALCdevice *device, const ALCint* attrlist ); function Make_Context_Current (AContext: in Context) return Bool; --ALC_API ALCboolean ALC_APIENTRY alcMakeContextCurrent( ALCcontext *context ); procedure Process_Context (AContext: in Context); --ALC_API void ALC_APIENTRY alcProcessContext( ALCcontext *context ); procedure Suspend_Context (AContext: in Context); --ALC_API void ALC_APIENTRY alcSuspendContext( ALCcontext *context ); procedure Destroy_Context (AContext: in Context); --ALC_API void ALC_APIENTRY alcDestroyContext( ALCcontext *context ); function Get_Current_Context return Context; --ALC_API ALCcontext * ALC_APIENTRY alcGetCurrentContext( void ); function Get_Contexts_Device (AContext: in Context) return Device; --ALC_API ALCdevice* ALC_APIENTRY alcGetContextsDevice( ALCcontext *context ); -- Device Management function Open_Device (Device_Name: in String) return Device; Pragma Inline (Open_Device); function Close_Device (ADevice: in Device) return Bool; -- Error support. -- Obtain the most recent Context error function Get_Error (ADevice: in Device) return Enum; -- Extension support. -- Query for the presence of an extension, and obtain any appropriate -- function pointers and enum values. function Is_Extension_Present ( ADevice: in Device; Ext_Name: in String ) return Bool; Pragma Inline (Is_Extension_Present); function Get_Proc_Address ( ADevice: in Device; Func_Name: in String ) return Pointer; Pragma Inline (Get_Proc_Address); function Get_Enum_Value ( ADevice: in Device; Enum_Name: in String ) return Enum; Pragma Inline (Get_Enum_Value); -- Query functions function Get_String (ADevice: in Device; Param: in Enum) return String; Pragma Inline (Get_String); procedure Get_Integer ( ADevice: in Device; Param: in Enum; Size: in SizeI; Data: in Pointer ); -- Capture functions function Capture_Open_Device ( Device_Name: in String; Frequency: in UInt; Format: in Enum; Buffer_Size: in SizeI ) return Device; Pragma Inline (Capture_Open_Device); function Capture_Close_Device (ADevice: in Device) return Bool; procedure Capture_Start (ADevice: in Device); procedure Capture_Stop (ADevice: in Device); procedure Capture_Samples ( ADevice: in Device; Buffer: in Pointer; Samples: in SizeI ); --------------------------------------------------------------------------- private --------------------------------------------------------------------------- ------------------- -- I M P O R T S -- ------------------- --------------------------------------------------------------------------- Pragma Import (StdCall, Create_Context, "alcCreateContext"); Pragma Import (StdCall, Make_Context_Current, "alcMakeContextCurrent"); Pragma Import (StdCall, Process_Context, "alcProcessContext"); Pragma Import (StdCall, Suspend_Context, "alcSuspendContext"); Pragma Import (StdCall, Destroy_Context, "alcDestroyContext"); Pragma Import (StdCall, Get_Current_Context, "alcGetCurrentContext"); Pragma Import (StdCall, Get_Contexts_Device, "alcGetContextsDevice"); Pragma Import (StdCall, Close_Device, "alcCloseDevice"); Pragma Import (StdCall, Get_Error, "alcGetError"); Pragma Import (StdCall, Get_Integer, "alcGetIntegerv"); Pragma Import (StdCall, Capture_Close_Device, "alcCaptureCloseDevice"); Pragma Import (StdCall, Capture_Start, "alcCaptureStart"); Pragma Import (StdCall, Capture_Stop, "alcCaptureStop"); Pragma Import (StdCall, Capture_Samples, "alcCaptureSamples"); --------------------------------------------------------------------------- end Oto.ALC;
Move Imports to private part.
ALC: Move Imports to private part. Signed-off-by: darkestkhan <[email protected]>
Ada
isc
darkestkhan/oto
e03d2f49e269687bf882c58a3c88df0a10d43698
awa/plugins/awa-wikis/src/awa-wikis-previews.adb
awa/plugins/awa-wikis/src/awa-wikis-previews.adb
----------------------------------------------------------------------- -- awa-wikis-previews -- Wiki preview management -- 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.Log.Loggers; package body AWA.Wikis.Previews is Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("AWA.Wikis.Preview"); -- The worker procedure that performs the preview job. procedure Preview_Worker (Job : in out AWA.Jobs.Services.Abstract_Job_Type'Class) is begin null; end Preview_Worker; -- Initialize the wikis module. overriding procedure Initialize (Plugin : in out Preview_Module; App : in AWA.Modules.Application_Access; Props : in ASF.Applications.Config) is begin Log.Info ("Initializing the wiki preview module"); AWA.Modules.Module (Plugin).Initialize (App, Props); Plugin.Add_Listener (AWA.Wikis.Modules.NAME, Plugin'Unchecked_Access); end Initialize; -- The `On_Create` procedure is called by `Notify_Create` to notify the creation of the page. overriding procedure On_Create (Instance : in Preview_Module; Item : in AWA.Wikis.Models.Wiki_Page_Ref'Class) is begin null; end On_Create; -- The `On_Update` procedure is called by `Notify_Update` to notify the update of the page. overriding procedure On_Update (Instance : in Preview_Module; Item : in AWA.Wikis.Models.Wiki_Page_Ref'Class) is begin null; end On_Update; -- The `On_Delete` procedure is called by `Notify_Delete` to notify the deletion of the page. overriding procedure On_Delete (Instance : in Preview_Module; Item : in AWA.Wikis.Models.Wiki_Page_Ref'Class) is begin null; end On_Delete; end AWA.Wikis.Previews;
----------------------------------------------------------------------- -- awa-wikis-previews -- Wiki preview management -- 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.Log.Loggers; with AWA.Jobs.Services; with AWA.Jobs.Modules; package body AWA.Wikis.Previews is Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("AWA.Wikis.Preview"); -- ------------------------------ -- The worker procedure that performs the preview job. -- ------------------------------ procedure Preview_Worker (Job : in out AWA.Jobs.Services.Abstract_Job_Type'Class) is begin null; end Preview_Worker; -- ------------------------------ -- Initialize the wikis module. -- ------------------------------ overriding procedure Initialize (Plugin : in out Preview_Module; App : in AWA.Modules.Application_Access; Props : in ASF.Applications.Config) is begin Log.Info ("Initializing the wiki preview module"); AWA.Modules.Module (Plugin).Initialize (App, Props); Plugin.Add_Listener (AWA.Wikis.Modules.NAME, Plugin'Unchecked_Access); Plugin.Job_Module := AWA.Jobs.Modules.Get_Job_Module; Plugin.Job_Module.Register (Definition => Preview_Job_Definition.Factory); end Initialize; -- ------------------------------ -- Create a preview job and schedule the job to generate a new thumbnail preview for the page. -- ------------------------------ procedure Make_Preview_Job (Plugin : in Preview_Module; Page : in AWA.Wikis.Models.Wiki_Page_Ref'Class) is J : AWA.Jobs.Services.Job_Type; begin J.Set_Parameter ("wiki_space_id", Page.Get_Wiki); J.Set_Parameter ("wiki_page_id", Page); J.Schedule (Preview_Job_Definition.Factory.all); end Make_Preview_Job; -- ------------------------------ -- The `On_Create` procedure is called by `Notify_Create` to notify the creation of the page. -- ------------------------------ overriding procedure On_Create (Instance : in Preview_Module; Item : in AWA.Wikis.Models.Wiki_Page_Ref'Class) is begin null; end On_Create; -- ------------------------------ -- The `On_Update` procedure is called by `Notify_Update` to notify the update of the page. -- ------------------------------ overriding procedure On_Update (Instance : in Preview_Module; Item : in AWA.Wikis.Models.Wiki_Page_Ref'Class) is begin null; end On_Update; -- ------------------------------ -- The `On_Delete` procedure is called by `Notify_Delete` to notify the deletion of the page. -- ------------------------------ overriding procedure On_Delete (Instance : in Preview_Module; Item : in AWA.Wikis.Models.Wiki_Page_Ref'Class) is begin null; end On_Delete; end AWA.Wikis.Previews;
Implement the Make_Preview_Job operation: schedule the preview job for the wiki page
Implement the Make_Preview_Job operation: schedule the preview job for the wiki page
Ada
apache-2.0
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
2bea1c99855ab636d8b84947f4b61d3279f5608e
symbex-lex.adb
symbex-lex.adb
with Ada.Wide_Characters.Unicode; -- GNAT Specific. package body Symbex.Lex is package Unicode renames Ada.Wide_Characters.Unicode; -- -- Private subprograms. -- procedure Set_State (Lexer : in out Lexer_t; State : in State_Stage_t) is begin Lexer.State (State) := True; end Set_State; procedure Unset_State (Lexer : in out Lexer_t; State : in State_Stage_t) is begin Lexer.State (State) := False; end Unset_State; function State_Is_Set (Lexer : in Lexer_t; State : in State_Stage_t) return Boolean is begin return Lexer.State (State); end State_Is_Set; -- -- Return true if internal token buffer contains data. -- function Token_Is_Nonzero_Length (Lexer : in Lexer_t) return Boolean is begin return UBW_Strings.Length (Lexer.Token_Buffer) /= 0; end Token_Is_Nonzero_Length; -- -- Append item to internal token buffer. -- procedure Append_To_Token (Lexer : in out Lexer_t; Item : in Wide_Character) is begin UBW_Strings.Append (Lexer.Token_Buffer, Item); end Append_To_Token; -- -- Finish token in buffer and assign kind Kind. -- procedure Complete_Token (Lexer : in out Lexer_t; Kind : in Token_Kind_t; Token : out Token_t) is begin Token := Token_t' (Is_Valid => True, Line_Number => Lexer.Current_Line, Text => Lexer.Token_Buffer, Kind => Kind); Lexer.Token_Buffer := UBW_Strings.Null_Unbounded_Wide_String; end Complete_Token; -- -- Categorize Item into character class. -- function Categorize_Character (Item : in Wide_Character) return Character_Class_t is Class : Character_Class_t := Ordinary_Text; begin case Item is when '(' => Class := List_Open_Delimiter; when ')' => Class := List_Close_Delimiter; when '"' => Class := String_Delimiter; when ';' => Class := Comment_Delimiter; when '\' => Class := Escape_Character; when others => if Unicode.Is_Line_Terminator (Item) then Class := Line_Break; else if Unicode.Is_Space (Item) then Class := Whitespace; end if; end if; end case; return Class; end Categorize_Character; -- -- Public API. -- function Initialized (Lexer : in Lexer_t) return Boolean is begin return Lexer.Inited; end Initialized; -- -- Initialize the lexer. -- procedure Initialize_Lexer (Lexer : out Lexer_t; Status : out Lexer_Status_t) is begin Lexer := Lexer_t' (Inited => True, Current_Line => Line_Number_t'First, Token_Buffer => UBW_Strings.Null_Unbounded_Wide_String, Input_Buffer => Input_Buffer_t'(others => Wide_Character'Val (0)), State => State_t'(others => False)); Status := Lexer_OK; end Initialize_Lexer; -- -- Retrieve token from input stream. -- procedure Get_Token (Lexer : in out Lexer_t; Token : out Token_t; Status : out Lexer_Status_t) is -- -- Stream characters via Read_Item. -- procedure Fetch_Characters (Lexer : in out Lexer_t; Item : out Wide_Character; Item_Next : out Wide_Character; Status : out Stream_Status_t) is Null_Item : constant Wide_Character := Wide_Character'Val (0); begin if Lexer.Input_Buffer (Next) /= Null_Item then Lexer.Input_Buffer (Current) := Lexer.Input_Buffer (Next); Read_Item (Item => Lexer.Input_Buffer (Next), Status => Status); case Status is when Stream_EOF => Lexer.Input_Buffer (Next) := Null_Item; Status := Stream_OK; when Stream_Error => null; when Stream_OK => null; end case; else Read_Item (Item => Lexer.Input_Buffer (Current), Status => Status); Read_Item (Item => Lexer.Input_Buffer (Next), Status => Status); case Status is when Stream_EOF => Lexer.Input_Buffer (Next) := Null_Item; when Stream_Error => null; when Stream_OK => null; end case; end if; Item := Lexer.Input_Buffer (Current); Item_Next := Lexer.Input_Buffer (Next); end Fetch_Characters; Item : Wide_Character; Item_Next : Wide_Character; Stream_Status : Stream_Status_t; begin -- Default status. Status := Lexer_Needs_More_Data; Token := Invalid_Token; -- Fetch characters from input stream. Fetch_Characters (Lexer => Lexer, Item => Item, Item_Next => Item_Next, Status => Stream_Status); case Stream_Status is when Stream_OK => null; when Stream_Error => Status := Lexer_Error_Stream_Error; return; when Stream_EOF => if State_Is_Set (Lexer, Inside_String) or State_Is_Set (Lexer, Inside_Escape) or State_Is_Set (Lexer, Inside_Comment) then Status := Lexer_Error_Early_EOF; else -- Reached upon EOF with no preceding newline/whitespace. Status := Lexer_OK; -- Have unfinished token? if Token_Is_Nonzero_Length (Lexer) then Complete_Token (Lexer => Lexer, Token => Token, Kind => Token_Symbol); else Append_To_Token (Lexer, 'E'); Complete_Token (Lexer => Lexer, Token => Token, Kind => Token_EOF); end if; end if; return; end case; pragma Assert (Stream_Status = Stream_OK); -- Process character. case Categorize_Character (Item) is when Comment_Delimiter => if State_Is_Set (Lexer, Inside_String) or State_Is_Set (Lexer, Inside_Escape) then Append_To_Token (Lexer, Item); else if not State_Is_Set (Lexer, Inside_Comment) then Set_State (Lexer, Inside_Comment); end if; end if; when Escape_Character => if not State_Is_Set (Lexer, Inside_Comment) then if State_Is_Set (Lexer, Inside_String) then if State_Is_Set (Lexer, Inside_Escape) then Append_To_Token (Lexer, Item); Unset_State (Lexer, Inside_Escape); else Set_State (Lexer, Inside_Escape); end if; end if; end if; when Line_Break => if State_Is_Set (Lexer, Inside_Comment) then Unset_State (Lexer, Inside_Comment); else begin -- Potential overflow. Lexer.Current_Line := Lexer.Current_Line + 1; if State_Is_Set (Lexer, Inside_Escape) then Unset_State (Lexer, Inside_Escape); end if; if State_Is_Set (Lexer, Inside_String) then Append_To_Token (Lexer, Item); else if Token_Is_Nonzero_Length (Lexer) then Status := Lexer_OK; Complete_Token (Lexer => Lexer, Token => Token, Kind => Token_Symbol); end if; end if; exception when Constraint_Error => Status := Lexer_Error_Line_Overflow; Token := Invalid_Token; end; end if; when List_Open_Delimiter => if not State_Is_Set (Lexer, Inside_Comment) then Append_To_Token (Lexer, Item); if not State_Is_Set (Lexer, Inside_String) then Status := Lexer_OK; Complete_Token (Lexer => Lexer, Token => Token, Kind => Token_List_Open); end if; end if; when List_Close_Delimiter => if not State_Is_Set (Lexer, Inside_Comment) then Append_To_Token (Lexer, Item); if not State_Is_Set (Lexer, Inside_String) then Status := Lexer_OK; Complete_Token (Lexer => Lexer, Token => Token, Kind => Token_List_Close); end if; end if; when String_Delimiter => if not State_Is_Set (Lexer, Inside_Comment) then if State_Is_Set (Lexer, Inside_String) then if State_Is_Set (Lexer, Inside_Escape) then Append_To_Token (Lexer, Item); Unset_State (Lexer, Inside_Escape); else Status := Lexer_OK; Complete_Token (Lexer => Lexer, Token => Token, Kind => Token_Quoted_String); Unset_State (Lexer, Inside_String); end if; else Set_State (Lexer, Inside_String); end if; end if; when Whitespace => if not State_Is_Set (Lexer, Inside_Comment) then if State_Is_Set (Lexer, Inside_Escape) then Unset_State (Lexer, Inside_Escape); end if; if State_Is_Set (Lexer, Inside_String) then Append_To_Token (Lexer, Item); else if Token_Is_Nonzero_Length (Lexer) then Status := Lexer_OK; Complete_Token (Lexer => Lexer, Token => Token, Kind => Token_Symbol); end if; end if; end if; when Ordinary_Text => if not State_Is_Set (Lexer, Inside_Comment) then if State_Is_Set (Lexer, Inside_Escape) then Unset_State (Lexer, Inside_Escape); end if; Append_To_Token (Lexer, Item); -- End of token if not inside a string. case Categorize_Character (Item_Next) is when List_Open_Delimiter | List_Close_Delimiter | String_Delimiter => if not State_Is_Set (Lexer, Inside_String) then Status := Lexer_OK; Complete_Token (Lexer => Lexer, Token => Token, Kind => Token_Symbol); end if; when others => null; end case; end if; end case; exception when Storage_Error => Status := Lexer_Error_Out_Of_Memory; Token := Invalid_Token; end Get_Token; end Symbex.Lex;
with Ada.Wide_Characters.Unicode; -- GNAT Specific. -- with Ada.Text_IO; package body Symbex.Lex is package Unicode renames Ada.Wide_Characters.Unicode; -- -- Private subprograms. -- procedure Set_State (Lexer : in out Lexer_t; State : in State_Stage_t) is begin Lexer.State (State) := True; end Set_State; procedure Unset_State (Lexer : in out Lexer_t; State : in State_Stage_t) is begin Lexer.State (State) := False; end Unset_State; function State_Is_Set (Lexer : in Lexer_t; State : in State_Stage_t) return Boolean is begin return Lexer.State (State); end State_Is_Set; -- -- Return true if internal token buffer contains data. -- function Token_Is_Nonzero_Length (Lexer : in Lexer_t) return Boolean is begin -- Ada.Text_IO.Put_Line ("length: " & Natural'Image (UBW_Strings.Length (Lexer.Token_Buffer))); return UBW_Strings.Length (Lexer.Token_Buffer) /= 0; end Token_Is_Nonzero_Length; -- -- Append item to internal token buffer. -- procedure Append_To_Token (Lexer : in out Lexer_t; Item : in Wide_Character) is begin UBW_Strings.Append (Lexer.Token_Buffer, Item); end Append_To_Token; -- -- Finish token in buffer and assign kind Kind. -- procedure Complete_Token (Lexer : in out Lexer_t; Kind : in Token_Kind_t; Token : out Token_t) is begin Token := Token_t' (Is_Valid => True, Line_Number => Lexer.Current_Line, Text => Lexer.Token_Buffer, Kind => Kind); Lexer.Token_Buffer := UBW_Strings.Null_Unbounded_Wide_String; end Complete_Token; -- -- Categorize Item into character class. -- function Categorize_Character (Item : in Wide_Character) return Character_Class_t is Class : Character_Class_t := Ordinary_Text; begin case Item is when '(' => Class := List_Open_Delimiter; when ')' => Class := List_Close_Delimiter; when '"' => Class := String_Delimiter; when ';' => Class := Comment_Delimiter; when '\' => Class := Escape_Character; when others => if Unicode.Is_Line_Terminator (Item) then Class := Line_Break; else if Unicode.Is_Space (Item) then Class := Whitespace; end if; end if; end case; return Class; end Categorize_Character; -- -- Public API. -- function Initialized (Lexer : in Lexer_t) return Boolean is begin return Lexer.Inited; end Initialized; -- -- Initialize the lexer. -- procedure Initialize_Lexer (Lexer : out Lexer_t; Status : out Lexer_Status_t) is begin Lexer := Lexer_t' (Inited => True, Current_Line => Line_Number_t'First, Token_Buffer => UBW_Strings.Null_Unbounded_Wide_String, Input_Buffer => Input_Buffer_t'(others => Wide_Character'Val (0)), State => State_t'(others => False)); Status := Lexer_OK; end Initialize_Lexer; -- -- Retrieve token from input stream. -- procedure Get_Token (Lexer : in out Lexer_t; Token : out Token_t; Status : out Lexer_Status_t) is -- -- Stream characters via Read_Item. -- procedure Fetch_Characters (Lexer : in out Lexer_t; Item : out Wide_Character; Item_Next : out Wide_Character; Status : out Stream_Status_t) is Null_Item : constant Wide_Character := Wide_Character'Val (0); begin if Lexer.Input_Buffer (Next) /= Null_Item then Lexer.Input_Buffer (Current) := Lexer.Input_Buffer (Next); Read_Item (Item => Lexer.Input_Buffer (Next), Status => Status); case Status is when Stream_EOF => Lexer.Input_Buffer (Next) := Null_Item; Status := Stream_OK; when Stream_Error => null; when Stream_OK => null; end case; else Read_Item (Item => Lexer.Input_Buffer (Current), Status => Status); case Status is when Stream_EOF => null; when Stream_Error => null; when Stream_OK => Read_Item (Item => Lexer.Input_Buffer (Next), Status => Status); case Status is when Stream_EOF => Lexer.Input_Buffer (Next) := Null_Item; Status := Stream_OK; when Stream_Error => null; when Stream_OK => null; end case; end case; end if; Item := Lexer.Input_Buffer (Current); Item_Next := Lexer.Input_Buffer (Next); end Fetch_Characters; Item : Wide_Character; Item_Next : Wide_Character; Stream_Status : Stream_Status_t; begin -- Default status. Status := Lexer_Needs_More_Data; Token := Invalid_Token; -- Fetch characters from input stream. Fetch_Characters (Lexer => Lexer, Item => Item, Item_Next => Item_Next, Status => Stream_Status); case Stream_Status is when Stream_OK => null; when Stream_Error => Status := Lexer_Error_Stream_Error; return; when Stream_EOF => if State_Is_Set (Lexer, Inside_String) or State_Is_Set (Lexer, Inside_Escape) then Status := Lexer_Error_Early_EOF; else -- Reached upon EOF with no preceding newline/whitespace. Status := Lexer_OK; -- Have unfinished token? if Token_Is_Nonzero_Length (Lexer) then Complete_Token (Lexer => Lexer, Token => Token, Kind => Token_Symbol); else Append_To_Token (Lexer, 'E'); Complete_Token (Lexer => Lexer, Token => Token, Kind => Token_EOF); end if; end if; return; end case; pragma Assert (Stream_Status = Stream_OK); -- Process character. case Categorize_Character (Item) is when Comment_Delimiter => if State_Is_Set (Lexer, Inside_String) or State_Is_Set (Lexer, Inside_Escape) then Append_To_Token (Lexer, Item); else if not State_Is_Set (Lexer, Inside_Comment) then Set_State (Lexer, Inside_Comment); end if; end if; when Escape_Character => if not State_Is_Set (Lexer, Inside_Comment) then if State_Is_Set (Lexer, Inside_String) then if State_Is_Set (Lexer, Inside_Escape) then Append_To_Token (Lexer, Item); Unset_State (Lexer, Inside_Escape); else Set_State (Lexer, Inside_Escape); end if; end if; end if; when Line_Break => if State_Is_Set (Lexer, Inside_Comment) then Unset_State (Lexer, Inside_Comment); else begin -- Potential overflow. Lexer.Current_Line := Lexer.Current_Line + 1; if State_Is_Set (Lexer, Inside_Escape) then Unset_State (Lexer, Inside_Escape); end if; if State_Is_Set (Lexer, Inside_String) then Append_To_Token (Lexer, Item); else if Token_Is_Nonzero_Length (Lexer) then Status := Lexer_OK; Complete_Token (Lexer => Lexer, Token => Token, Kind => Token_Symbol); end if; end if; exception when Constraint_Error => Status := Lexer_Error_Line_Overflow; Token := Invalid_Token; end; end if; when List_Open_Delimiter => if not State_Is_Set (Lexer, Inside_Comment) then Append_To_Token (Lexer, Item); if not State_Is_Set (Lexer, Inside_String) then Status := Lexer_OK; Complete_Token (Lexer => Lexer, Token => Token, Kind => Token_List_Open); end if; end if; when List_Close_Delimiter => if not State_Is_Set (Lexer, Inside_Comment) then Append_To_Token (Lexer, Item); if not State_Is_Set (Lexer, Inside_String) then Status := Lexer_OK; Complete_Token (Lexer => Lexer, Token => Token, Kind => Token_List_Close); end if; end if; when String_Delimiter => if not State_Is_Set (Lexer, Inside_Comment) then if State_Is_Set (Lexer, Inside_String) then if State_Is_Set (Lexer, Inside_Escape) then Append_To_Token (Lexer, Item); Unset_State (Lexer, Inside_Escape); else Status := Lexer_OK; Complete_Token (Lexer => Lexer, Token => Token, Kind => Token_Quoted_String); Unset_State (Lexer, Inside_String); end if; else Set_State (Lexer, Inside_String); end if; end if; when Whitespace => if not State_Is_Set (Lexer, Inside_Comment) then if State_Is_Set (Lexer, Inside_Escape) then Unset_State (Lexer, Inside_Escape); end if; if State_Is_Set (Lexer, Inside_String) then Append_To_Token (Lexer, Item); else if Token_Is_Nonzero_Length (Lexer) then Status := Lexer_OK; Complete_Token (Lexer => Lexer, Token => Token, Kind => Token_Symbol); end if; end if; end if; when Ordinary_Text => if not State_Is_Set (Lexer, Inside_Comment) then if State_Is_Set (Lexer, Inside_Escape) then Unset_State (Lexer, Inside_Escape); end if; Append_To_Token (Lexer, Item); -- End of token if not inside a string. case Categorize_Character (Item_Next) is when List_Open_Delimiter | List_Close_Delimiter | String_Delimiter => if not State_Is_Set (Lexer, Inside_String) then Status := Lexer_OK; Complete_Token (Lexer => Lexer, Token => Token, Kind => Token_Symbol); end if; when others => null; end case; end if; end case; exception when Storage_Error => Status := Lexer_Error_Out_Of_Memory; Token := Invalid_Token; end Get_Token; end Symbex.Lex;
Fix input stream on edge-case EOF.
Fix input stream on edge-case EOF.
Ada
isc
io7m/coreland-symbex,io7m/coreland-symbex
8d6288eb6bf7d5852660e419606ea3b6cfcfe905
src/gen-generator.ads
src/gen-generator.ads
----------------------------------------------------------------------- -- gen-generator -- Code Generator -- 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 Ada.Text_IO; with Ada.Command_Line; with Ada.Strings.Unbounded; with Ada.Strings.Unbounded.Hash; with Ada.Containers.Hashed_Maps; with Util.Beans.Objects; with Util.Properties; with ASF.Applications.Main; with ASF.Contexts.Faces; with ASF.Servlets; with Gen.Model.Packages; with Gen.Model.Projects; with Gen.Artifacts.Hibernate; with Gen.Artifacts.Query; with Gen.Artifacts.Mappings; with Gen.Artifacts.Distribs; with Gen.Artifacts.XMI; with Gen.Artifacts.Yaml; package Gen.Generator is package UBO renames Util.Beans.Objects; -- A fatal error that prevents the generator to proceed has occurred. Fatal_Error : exception; G_URI : constant String := "http://code.google.com/p/ada-ado/generator"; type Package_Type is (PACKAGE_MODEL, PACKAGE_FORMS); type Mapping_File is record Path : UString; Output : Ada.Text_IO.File_Type; end record; type Handler is new ASF.Applications.Main.Application and Gen.Artifacts.Generator with private; -- Initialize the generator procedure Initialize (H : in out Handler; Config_Dir : in UString; Debug : in Boolean); -- Get the configuration properties. function Get_Properties (H : in Handler) return Util.Properties.Manager; -- Report an error and set the exit status accordingly procedure Error (H : in out Handler; Message : in String; Arg1 : in String; Arg2 : in String := ""); overriding procedure Error (H : in out Handler; Message : in String); -- Report an info message. procedure Info (H : in out Handler; Message : in String; Arg1 : in String := ""; Arg2 : in String := ""; Arg3 : in String := ""); -- Read the XML package file procedure Read_Package (H : in out Handler; File : in String); -- Read the model mapping types and initialize the hibernate artifact. procedure Read_Mappings (H : in out Handler); -- Read the XML model file procedure Read_Model (H : in out Handler; File : in String; Silent : in Boolean); -- Read the model and query files stored in the application directory <b>db</b>. procedure Read_Models (H : in out Handler; Dirname : in String); -- Read the XML project file. When <b>Recursive</b> is set, read the GNAT project -- files used by the main project and load all the <b>dynamo.xml</b> files defined -- by these project. procedure Read_Project (H : in out Handler; File : in String; Recursive : in Boolean := False); -- Prepare the model by checking, verifying and initializing it after it is completely known. procedure Prepare (H : in out Handler); -- Finish the generation. Some artifacts could generate other files that take into -- account files generated previously. procedure Finish (H : in out Handler); -- Tell the generator to activate the generation of the given template name. -- The name is a property name that must be defined in generator.properties to -- indicate the template file. Several artifacts can trigger the generation -- of a given template. The template is generated only once. procedure Add_Generation (H : in out Handler; Name : in String; Mode : in Gen.Artifacts.Iteration_Mode; Mapping : in String); -- Enable the generation of the Ada package given by the name. By default all the Ada -- packages found in the model are generated. When called, this enables the generation -- only for the Ada packages registered here. procedure Enable_Package_Generation (H : in out Handler; Name : in String); -- Save the content generated by the template generator. procedure Save_Content (H : in out Handler; File : in String; Content : in UString); -- Generate the code using the template file procedure Generate (H : in out Handler; Mode : in Gen.Artifacts.Iteration_Mode; File : in String; Save : not null access procedure (H : in out Handler; File : in String; Content : in UString)); -- Generate the code using the template file procedure Generate (H : in out Handler; File : in String; Model : in Gen.Model.Definition_Access; Save : not null access procedure (H : in out Handler; File : in String; Content : in UString)); -- Generate all the code for the templates activated through <b>Add_Generation</b>. procedure Generate_All (H : in out Handler); -- Generate all the code generation files stored in the directory procedure Generate_All (H : in out Handler; Mode : in Gen.Artifacts.Iteration_Mode; Name : in String); -- Set the directory where template files are stored. procedure Set_Template_Directory (H : in out Handler; Path : in UString); -- Set the directory where results files are generated. procedure Set_Result_Directory (H : in out Handler; Path : in String); -- Get the result directory path. function Get_Result_Directory (H : in Handler) return String; -- Get the project plugin directory path. function Get_Plugin_Directory (H : in Handler) return String; -- Get the config directory path. function Get_Config_Directory (H : in Handler) return String; -- Get the dynamo installation directory path. function Get_Install_Directory (H : in Handler) return String; -- Return the search directories that the AWA application can use to find files. -- The search directories is built by using the project dependencies. function Get_Search_Directories (H : in Handler) return String; -- Get the exit status -- Returns 0 if the generation was successful -- Returns 1 if there was a generation error function Get_Status (H : in Handler) return Ada.Command_Line.Exit_Status; -- Get the configuration parameter. function Get_Parameter (H : in Handler; Name : in String; Default : in String := "") return String; -- Get the configuration parameter. function Get_Parameter (H : in Handler; Name : in String; Default : in Boolean := False) return Boolean; -- Set the force-save file mode. When False, if the generated file exists already, -- an error message is reported. procedure Set_Force_Save (H : in out Handler; To : in Boolean); -- Set the project name. procedure Set_Project_Name (H : in out Handler; Name : in String); -- Get the project name. function Get_Project_Name (H : in Handler) return String; -- Set the project property. procedure Set_Project_Property (H : in out Handler; Name : in String; Value : in String); -- Get the project property identified by the given name. If the project property -- does not exist, returns the default value. Project properties are loaded -- by <b>Read_Project</b>. function Get_Project_Property (H : in Handler; Name : in String; Default : in String := "") return String; -- Save the project description and parameters. procedure Save_Project (H : in out Handler); -- Get the path of the last generated file. function Get_Generated_File (H : in Handler) return String; -- Update the project model through the <b>Process</b> procedure. procedure Update_Project (H : in out Handler; Process : not null access procedure (P : in out Model.Projects.Root_Project_Definition)); -- Scan the dynamo directories and execute the <b>Process</b> procedure with the -- directory path. procedure Scan_Directories (H : in Handler; Process : not null access procedure (Dir : in String)); private use Ada.Strings.Unbounded; use Gen.Artifacts; type Template_Context is record Mode : Gen.Artifacts.Iteration_Mode; Mapping : UString; end record; package Template_Map is new Ada.Containers.Hashed_Maps (Key_Type => UString, Element_Type => Template_Context, Hash => Ada.Strings.Unbounded.Hash, Equivalent_Keys => "="); type Object_Access is access all UBO.Object; type Handler is new ASF.Applications.Main.Application and Gen.Artifacts.Generator with record Conf : ASF.Applications.Config; -- Config directory. Config_Dir : UString; -- Output base directory. Output_Dir : UString; Model : aliased Gen.Model.Packages.Model_Definition; Status : Ada.Command_Line.Exit_Status := 0; -- The file that must be saved (the file attribute in <f:view>. File : Object_Access; -- Indicates whether the file must be saved at each generation or only once. -- This is the mode attribute in <f:view>. Mode : Object_Access; -- Indicates whether the file must be ignored after the generation. -- This is the ignore attribute in <f:view>. It is intended to be used for the package -- body generation to skip that in some cases when it turns out there is no operation. Ignore : Object_Access; -- Whether the AdaMappings.xml file was loaded or not. Type_Mapping_Loaded : Boolean := False; -- The root project document. Project : aliased Gen.Model.Projects.Root_Project_Definition; -- Hibernate XML artifact Hibernate : Gen.Artifacts.Hibernate.Artifact; -- Query generation artifact. Query : Gen.Artifacts.Query.Artifact; -- Type mapping artifact. Mappings : Gen.Artifacts.Mappings.Artifact; -- The distribution artifact. Distrib : Gen.Artifacts.Distribs.Artifact; -- Ada generation from UML-XMI models. XMI : Gen.Artifacts.XMI.Artifact; -- Yaml model files support. Yaml : Gen.Artifacts.Yaml.Artifact; -- The list of templates that must be generated. Templates : Template_Map.Map; -- Force the saving of a generated file, even if a file already exist. Force_Save : Boolean := True; -- A fake servlet for template evaluation. Servlet : ASF.Servlets.Servlet_Access; end record; -- Execute the lifecycle phases on the faces context. overriding procedure Execute_Lifecycle (App : in Handler; Context : in out ASF.Contexts.Faces.Faces_Context'Class); end Gen.Generator;
----------------------------------------------------------------------- -- gen-generator -- Code Generator -- Copyright (C) 2009, 2010, 2011, 2012, 2013, 2015, 2018, 2022 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Text_IO; with Ada.Command_Line; with Ada.Strings.Unbounded; with Ada.Strings.Unbounded.Hash; with Ada.Containers.Hashed_Maps; with Util.Beans.Objects; with Util.Properties; with ASF.Applications.Main; with ASF.Contexts.Faces; with ASF.Servlets; with Gen.Model.Packages; with Gen.Model.Projects; with Gen.Artifacts.Hibernate; with Gen.Artifacts.Query; with Gen.Artifacts.Mappings; with Gen.Artifacts.Distribs; with Gen.Artifacts.XMI; with Gen.Artifacts.Yaml; package Gen.Generator is package UBO renames Util.Beans.Objects; -- A fatal error that prevents the generator to proceed has occurred. Fatal_Error : exception; G_URI : constant String := "http://code.google.com/p/ada-ado/generator"; type Package_Type is (PACKAGE_MODEL, PACKAGE_FORMS); type Mapping_File is record Path : UString; Output : Ada.Text_IO.File_Type; end record; type Handler is new ASF.Applications.Main.Application and Gen.Artifacts.Generator with private; -- Initialize the generator procedure Initialize (H : in out Handler; Config_Dir : in UString; Debug : in Boolean); -- Get the configuration properties. function Get_Properties (H : in Handler) return Util.Properties.Manager; -- Report an error and set the exit status accordingly procedure Error (H : in out Handler; Message : in String; Arg1 : in String; Arg2 : in String := ""); overriding procedure Error (H : in out Handler; Message : in String); -- Report an info message. procedure Info (H : in out Handler; Message : in String; Arg1 : in String := ""; Arg2 : in String := ""; Arg3 : in String := ""); -- Read the XML package file procedure Read_Package (H : in out Handler; File : in String); -- Read the model mapping types and initialize the hibernate artifact. procedure Read_Mappings (H : in out Handler); -- Read the XML model file procedure Read_Model (H : in out Handler; File : in String; Silent : in Boolean); -- Read the model and query files stored in the application directory <b>db</b>. procedure Read_Models (H : in out Handler; Dirname : in String); -- Read the XML project file. When <b>Recursive</b> is set, read the GNAT project -- files used by the main project and load all the <b>dynamo.xml</b> files defined -- by these project. procedure Read_Project (H : in out Handler; File : in String; Recursive : in Boolean := False); -- Prepare the model by checking, verifying and initializing it after it is completely known. procedure Prepare (H : in out Handler); -- Finish the generation. Some artifacts could generate other files that take into -- account files generated previously. procedure Finish (H : in out Handler); -- Tell the generator to activate the generation of the given template name. -- The name is a property name that must be defined in generator.properties to -- indicate the template file. Several artifacts can trigger the generation -- of a given template. The template is generated only once. procedure Add_Generation (H : in out Handler; Name : in String; Mode : in Gen.Artifacts.Iteration_Mode; Mapping : in String); -- Enable the generation of the Ada package given by the name. By default all the Ada -- packages found in the model are generated. When called, this enables the generation -- only for the Ada packages registered here. procedure Enable_Package_Generation (H : in out Handler; Name : in String); -- Save the content generated by the template generator. procedure Save_Content (H : in out Handler; File : in String; Content : in UString); -- Generate the code using the template file procedure Generate (H : in out Handler; Mode : in Gen.Artifacts.Iteration_Mode; File : in String; Save : not null access procedure (H : in out Handler; File : in String; Content : in UString)); -- Generate the code using the template file procedure Generate (H : in out Handler; File : in String; Model : in Gen.Model.Definition_Access; Save : not null access procedure (H : in out Handler; File : in String; Content : in UString)); -- Generate all the code for the templates activated through <b>Add_Generation</b>. procedure Generate_All (H : in out Handler); -- Generate all the code generation files stored in the directory procedure Generate_All (H : in out Handler; Mode : in Gen.Artifacts.Iteration_Mode; Name : in String); -- Set the directory where template files are stored. procedure Set_Template_Directory (H : in out Handler; Path : in UString); -- Set the directory where results files are generated. procedure Set_Result_Directory (H : in out Handler; Path : in String); -- Get the result directory path. function Get_Result_Directory (H : in Handler) return String; -- Get the project plugin directory path. function Get_Plugin_Directory (H : in Handler) return String; -- Get the config directory path. function Get_Config_Directory (H : in Handler) return String; -- Get the dynamo installation directory path. function Get_Install_Directory (H : in Handler) return String; -- Return the search directories that the AWA application can use to find files. -- The search directories is built by using the project dependencies. function Get_Search_Directories (H : in Handler) return String; -- Get the exit status -- Returns 0 if the generation was successful -- Returns 1 if there was a generation error function Get_Status (H : in Handler) return Ada.Command_Line.Exit_Status; -- Get the configuration parameter. function Get_Parameter (H : in Handler; Name : in String; Default : in String := "") return String; -- Get the configuration parameter. function Get_Parameter (H : in Handler; Name : in String; Default : in Boolean := False) return Boolean; -- Set the force-save file mode. When False, if the generated file exists already, -- an error message is reported. procedure Set_Force_Save (H : in out Handler; To : in Boolean); -- Set the project name. procedure Set_Project_Name (H : in out Handler; Name : in String); -- Get the project name. function Get_Project_Name (H : in Handler) return String; -- Set the project property. procedure Set_Project_Property (H : in out Handler; Name : in String; Value : in String); -- Get the project property identified by the given name. If the project property -- does not exist, returns the default value. Project properties are loaded -- by <b>Read_Project</b>. function Get_Project_Property (H : in Handler; Name : in String; Default : in String := "") return String; -- Set the global configuration identified by the name by pre-pending the -- environtment variable if it is defined. procedure Set_Configuration (H : in out Handler; Name : in String; Env_Name : in String); -- Save the project description and parameters. procedure Save_Project (H : in out Handler); -- Get the path of the last generated file. function Get_Generated_File (H : in Handler) return String; -- Update the project model through the <b>Process</b> procedure. procedure Update_Project (H : in out Handler; Process : not null access procedure (P : in out Model.Projects.Root_Project_Definition)); -- Scan the dynamo directories and execute the <b>Process</b> procedure with the -- directory path. procedure Scan_Directories (H : in Handler; Process : not null access procedure (Dir : in String)); private use Ada.Strings.Unbounded; use Gen.Artifacts; type Template_Context is record Mode : Gen.Artifacts.Iteration_Mode; Mapping : UString; end record; package Template_Map is new Ada.Containers.Hashed_Maps (Key_Type => UString, Element_Type => Template_Context, Hash => Ada.Strings.Unbounded.Hash, Equivalent_Keys => "="); type Object_Access is access all UBO.Object; type Handler is new ASF.Applications.Main.Application and Gen.Artifacts.Generator with record Conf : ASF.Applications.Config; -- Config directory. Config_Dir : UString; -- Output base directory. Output_Dir : UString; Model : aliased Gen.Model.Packages.Model_Definition; Status : Ada.Command_Line.Exit_Status := 0; -- The file that must be saved (the file attribute in <f:view>. File : Object_Access; -- Indicates whether the file must be saved at each generation or only once. -- This is the mode attribute in <f:view>. Mode : Object_Access; -- Indicates whether the file must be ignored after the generation. -- This is the ignore attribute in <f:view>. It is intended to be used for the package -- body generation to skip that in some cases when it turns out there is no operation. Ignore : Object_Access; -- Whether the AdaMappings.xml file was loaded or not. Type_Mapping_Loaded : Boolean := False; -- The root project document. Project : aliased Gen.Model.Projects.Root_Project_Definition; -- Hibernate XML artifact Hibernate : Gen.Artifacts.Hibernate.Artifact; -- Query generation artifact. Query : Gen.Artifacts.Query.Artifact; -- Type mapping artifact. Mappings : Gen.Artifacts.Mappings.Artifact; -- The distribution artifact. Distrib : Gen.Artifacts.Distribs.Artifact; -- Ada generation from UML-XMI models. XMI : Gen.Artifacts.XMI.Artifact; -- Yaml model files support. Yaml : Gen.Artifacts.Yaml.Artifact; -- The list of templates that must be generated. Templates : Template_Map.Map; -- Force the saving of a generated file, even if a file already exist. Force_Save : Boolean := True; -- A fake servlet for template evaluation. Servlet : ASF.Servlets.Servlet_Access; end record; -- Execute the lifecycle phases on the faces context. overriding procedure Execute_Lifecycle (App : in Handler; Context : in out ASF.Contexts.Faces.Faces_Context'Class); end Gen.Generator;
Declare the Set_Configuration procedure
Declare the Set_Configuration procedure
Ada
apache-2.0
stcarrez/dynamo,stcarrez/dynamo,stcarrez/dynamo
d6df5a380b6a82dcd0836f7188dbfcf48a46ec21
awa/src/awa-users-principals.adb
awa/src/awa-users-principals.adb
----------------------------------------------------------------------- -- awa-users-principals -- User principals -- Copyright (C) 2011 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- package body AWA.Users.Principals is -- ------------------------------ -- Get the principal name. -- ------------------------------ function Get_Name (From : in Principal) return String is begin return From.User.Get_Name; end Get_Name; -- ------------------------------ -- Returns true if the given role is stored in the user principal. -- ------------------------------ -- function Has_Role (User : in Principal; -- Role : in Security.Permissions.Role_Type) return Boolean is -- begin -- return User.Roles (Role); -- end Has_Role; -- ------------------------------ -- Get the principal identifier (name) -- ------------------------------ function Get_Id (From : in Principal) return String is begin return From.User.Get_Name; end Get_Id; -- ------------------------------ -- Get the user associated with the principal. -- ------------------------------ function Get_User (From : in Principal) return AWA.Users.Models.User_Ref is begin return From.User; end Get_User; -- ------------------------------ -- Get the current user identifier invoking the service operation. -- Returns NO_IDENTIFIER if there is none. -- ------------------------------ function Get_User_Identifier (From : in Principal) return ADO.Identifier is begin return From.User.Get_Id; end Get_User_Identifier; -- ------------------------------ -- Get the connection session used by the user. -- ------------------------------ function Get_Session (From : in Principal) return AWA.Users.Models.Session_Ref is begin return From.Session; end Get_Session; -- ------------------------------ -- Get the connection session identifier used by the user. -- ------------------------------ function Get_Session_Identifier (From : in Principal) return ADO.Identifier is begin return From.Session.Get_Id; end Get_Session_Identifier; -- ------------------------------ -- Create a principal for the given user. -- ------------------------------ function Create (User : in AWA.Users.Models.User_Ref; Session : in AWA.Users.Models.Session_Ref) return Principal_Access is Result : constant Principal_Access := new Principal; begin Result.User := User; Result.Session := Session; return Result; end Create; -- ------------------------------ -- Get the current user identifier invoking the service operation. -- Returns NO_IDENTIFIER if there is none or if the principal is not an AWA principal. -- ------------------------------ function Get_User_Identifier (From : in ASF.Principals.Principal_Access) return ADO.Identifier is use type ASF.Principals.Principal_Access; begin if From = null then return ADO.NO_IDENTIFIER; elsif not (From.all in Principal'Class) then return ADO.NO_IDENTIFIER; else return Principal'Class (From.all).Get_User_Identifier; end if; end Get_User_Identifier; end AWA.Users.Principals;
----------------------------------------------------------------------- -- awa-users-principals -- User principals -- 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. ----------------------------------------------------------------------- package body AWA.Users.Principals is -- ------------------------------ -- Get the principal name. -- ------------------------------ function Get_Name (From : in Principal) return String is begin return From.User.Get_Name; end Get_Name; -- ------------------------------ -- Get the principal identifier (name) -- ------------------------------ function Get_Id (From : in Principal) return String is begin return From.User.Get_Name; end Get_Id; -- ------------------------------ -- Get the user associated with the principal. -- ------------------------------ function Get_User (From : in Principal) return AWA.Users.Models.User_Ref is begin return From.User; end Get_User; -- ------------------------------ -- Get the current user identifier invoking the service operation. -- Returns NO_IDENTIFIER if there is none. -- ------------------------------ function Get_User_Identifier (From : in Principal) return ADO.Identifier is begin return From.User.Get_Id; end Get_User_Identifier; -- ------------------------------ -- Get the connection session used by the user. -- ------------------------------ function Get_Session (From : in Principal) return AWA.Users.Models.Session_Ref is begin return From.Session; end Get_Session; -- ------------------------------ -- Get the connection session identifier used by the user. -- ------------------------------ function Get_Session_Identifier (From : in Principal) return ADO.Identifier is begin return From.Session.Get_Id; end Get_Session_Identifier; -- ------------------------------ -- Create a principal for the given user. -- ------------------------------ function Create (User : in AWA.Users.Models.User_Ref; Session : in AWA.Users.Models.Session_Ref) return Principal_Access is Result : constant Principal_Access := new Principal; begin Result.User := User; Result.Session := Session; return Result; end Create; -- ------------------------------ -- Get the current user identifier invoking the service operation. -- Returns NO_IDENTIFIER if there is none or if the principal is not an AWA principal. -- ------------------------------ function Get_User_Identifier (From : in ASF.Principals.Principal_Access) return ADO.Identifier is use type ASF.Principals.Principal_Access; begin if From = null then return ADO.NO_IDENTIFIER; elsif not (From.all in Principal'Class) then return ADO.NO_IDENTIFIER; else return Principal'Class (From.all).Get_User_Identifier; end if; end Get_User_Identifier; end AWA.Users.Principals;
Fix compilation warnings
Fix compilation warnings
Ada
apache-2.0
tectronics/ada-awa,Letractively/ada-awa,Letractively/ada-awa,tectronics/ada-awa,Letractively/ada-awa,tectronics/ada-awa
c4786404c37de22d6718fbcc662bc83fa0f5f307
src/asf-views-facelets.ads
src/asf-views-facelets.ads
----------------------------------------------------------------------- -- asf-views-facelets -- Facelets representation and management -- Copyright (C) 2009, 2010, 2011, 2014, 2015 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Calendar; with Ada.Strings.Unbounded; with Ada.Containers.Hashed_Maps; with Ada.Strings.Unbounded.Hash; with ASF.Views.Nodes; with ASF.Contexts.Facelets; with ASF.Factory; with ASF.Components.Base; with Ada.Finalization; -- The <b>ASF.Views.Facelets</b> package contains the facelet factory -- responsible for getting the facelet tree from a facelet name. -- The facelets (or *.xhtml) files are loaded by the reader to form -- a tag node tree which is cached by the factory. The facelet factory -- is shared by multiple requests and threads. package ASF.Views.Facelets is type Facelet is private; type Facelet_Access is access all Facelet; -- Returns True if the facelet is null/empty. function Is_Null (F : Facelet) return Boolean; -- ------------------------------ -- Facelet factory -- ------------------------------ -- The facelet factory allows to retrieve the node tree to build the -- component tree. The node tree can be shared by several component trees. -- The node tree is initialized from the <b>XHTML</b> view file. It is put -- in a cache to avoid loading and parsing the file several times. type Facelet_Factory is limited private; -- Get the facelet identified by the given name. If the facelet is already -- loaded, the cached value is returned. The facelet file is searched in -- a set of directories configured in the facelet factory. procedure Find_Facelet (Factory : in out Facelet_Factory; Name : in String; Context : in ASF.Contexts.Facelets.Facelet_Context'Class; Result : out Facelet); -- Create the component tree from the facelet view. procedure Build_View (View : in Facelet; Context : in out ASF.Contexts.Facelets.Facelet_Context'Class; Root : in ASF.Components.Base.UIComponent_Access); -- Initialize the facelet factory. -- Set the search directories for facelet files. -- Set the ignore white space configuration when reading XHTML files. -- Set the ignore empty lines configuration when reading XHTML files. -- Set the escape unknown tags configuration when reading XHTML files. procedure Initialize (Factory : in out Facelet_Factory; Components : access ASF.Factory.Component_Factory; Paths : in String; Ignore_White_Spaces : in Boolean; Ignore_Empty_Lines : in Boolean; Escape_Unknown_Tags : in Boolean); -- Find the facelet file in one of the facelet directories. -- Returns the path to be used for reading the facelet file. function Find_Facelet_Path (Factory : in Facelet_Factory; Name : in String) return String; -- Clear the facelet cache procedure Clear_Cache (Factory : in out Facelet_Factory); private use Ada.Strings.Unbounded; type Facelet is record Root : ASF.Views.Nodes.Tag_Node_Access; File : ASF.Views.File_Info_Access; Modify_Time : Ada.Calendar.Time; end record; Empty : constant Facelet := (others => <>); -- Tag library map indexed on the library namespace. package Facelet_Maps is new Ada.Containers.Hashed_Maps (Key_Type => Unbounded_String, Element_Type => Facelet, Hash => Ada.Strings.Unbounded.Hash, Equivalent_Keys => "="); use Facelet_Maps; protected type Facelet_Cache is -- Find the facelet entry associated with the given name. function Find (Name : in Unbounded_String) return Facelet; -- Insert or replace the facelet entry associated with the given name. procedure Insert (Name : in Unbounded_String; Item : in Facelet); -- Clear the cache. procedure Clear; private Map : Facelet_Maps.Map; end Facelet_Cache; type Facelet_Factory is new Ada.Finalization.Limited_Controlled with record Paths : Unbounded_String := To_Unbounded_String (""); -- The facelet cache. Map : Facelet_Cache; -- The component factory Factory : access ASF.Factory.Component_Factory; -- Whether the unknown tags are escaped using XML escape rules. Escape_Unknown_Tags : Boolean := True; -- Whether white spaces can be ignored. Ignore_White_Spaces : Boolean := True; -- Whether empty lines should be ignored (when white spaces are kept). Ignore_Empty_Lines : Boolean := True; end record; -- Free the storage held by the factory cache. overriding procedure Finalize (Factory : in out Facelet_Factory); end ASF.Views.Facelets;
----------------------------------------------------------------------- -- asf-views-facelets -- Facelets representation and management -- Copyright (C) 2009, 2010, 2011, 2014, 2015, 2019 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Calendar; with ASF.Views.Nodes; with ASF.Contexts.Facelets; with ASF.Factory; with ASF.Components.Base; with Ada.Finalization; private with Ada.Strings.Unbounded; private with Ada.Containers.Hashed_Sets; private with Util.Refs; private with Ada.Strings.Hash; -- The <b>ASF.Views.Facelets</b> package contains the facelet factory -- responsible for getting the facelet tree from a facelet name. -- The facelets (or *.xhtml) files are loaded by the reader to form -- a tag node tree which is cached by the factory. The facelet factory -- is shared by multiple requests and threads. package ASF.Views.Facelets is type Facelet is private; -- Returns True if the facelet is null/empty. function Is_Null (F : Facelet) return Boolean; -- ------------------------------ -- Facelet factory -- ------------------------------ -- The facelet factory allows to retrieve the node tree to build the -- component tree. The node tree can be shared by several component trees. -- The node tree is initialized from the <b>XHTML</b> view file. It is put -- in a cache to avoid loading and parsing the file several times. type Facelet_Factory is limited private; -- Get the facelet identified by the given name. If the facelet is already -- loaded, the cached value is returned. The facelet file is searched in -- a set of directories configured in the facelet factory. procedure Find_Facelet (Factory : in out Facelet_Factory; Name : in String; Context : in ASF.Contexts.Facelets.Facelet_Context'Class; Result : out Facelet); -- Create the component tree from the facelet view. procedure Build_View (View : in Facelet; Context : in out ASF.Contexts.Facelets.Facelet_Context'Class; Root : in ASF.Components.Base.UIComponent_Access); -- Initialize the facelet factory. -- Set the search directories for facelet files. -- Set the ignore white space configuration when reading XHTML files. -- Set the ignore empty lines configuration when reading XHTML files. -- Set the escape unknown tags configuration when reading XHTML files. procedure Initialize (Factory : in out Facelet_Factory; Components : access ASF.Factory.Component_Factory; Paths : in String; Ignore_White_Spaces : in Boolean; Ignore_Empty_Lines : in Boolean; Escape_Unknown_Tags : in Boolean); -- Find the facelet file in one of the facelet directories. -- Returns the path to be used for reading the facelet file. function Find_Facelet_Path (Factory : in Facelet_Factory; Name : in String) return String; -- Clear the facelet cache procedure Clear_Cache (Factory : in out Facelet_Factory); private use Ada.Strings.Unbounded; CHECK_FILE_DELAY : constant := 10.0; type Facelet_Type (Len : Natural) is limited new Util.Refs.Ref_Entity with record Root : ASF.Views.Nodes.Tag_Node_Access; File : ASF.Views.File_Info_Access; Modify_Time : Ada.Calendar.Time; Check_Time : Ada.Calendar.Time; Name : String (1 .. Len); end record; type Facelet_Access is access all Facelet_Type; package Ref is new Util.Refs.Indefinite_References (Facelet_Type, Facelet_Access); type Facelet is record Facelet : Facelet_Access; end record; Empty : constant Facelet := (others => <>); function Hash (Item : in Facelet_Access) return Ada.Containers.Hash_Type is (Ada.Strings.Hash (Item.Name)); function Compare (Left, Right : in Facelet_Access) return Boolean is (Left.Name = Right.Name); -- Tag library map indexed on the library namespace. package Facelet_Sets is new Ada.Containers.Hashed_Sets (Element_Type => Facelet_Access, Hash => Hash, Equivalent_Elements => Compare); use Facelet_Sets; protected type Facelet_Cache is -- Find the facelet entry associated with the given name. function Find (Name : in String) return Facelet_Access; -- Insert or replace the facelet entry associated with the given name. procedure Insert (Facelet : in Facelet_Access); -- Clear the cache. procedure Clear; private Map : Facelet_Sets.Set; end Facelet_Cache; type Facelet_Factory is new Ada.Finalization.Limited_Controlled with record Paths : Unbounded_String := To_Unbounded_String (""); -- The facelet cache. Map : Facelet_Cache; -- The component factory Factory : access ASF.Factory.Component_Factory; -- Whether the unknown tags are escaped using XML escape rules. Escape_Unknown_Tags : Boolean := True; -- Whether white spaces can be ignored. Ignore_White_Spaces : Boolean := True; -- Whether empty lines should be ignored (when white spaces are kept). Ignore_Empty_Lines : Boolean := True; end record; -- Free the storage held by the factory cache. overriding procedure Finalize (Factory : in out Facelet_Factory); end ASF.Views.Facelets;
Refactor the Facelet type to store the name within the record and add a Check_Time member
Refactor the Facelet type to store the name within the record and add a Check_Time member
Ada
apache-2.0
stcarrez/ada-asf,stcarrez/ada-asf,stcarrez/ada-asf
62771abe8f8a54f71c4c2869e9174a797d404817
src/util-serialize-io.adb
src/util-serialize-io.adb
----------------------------------------------------------------------- -- util-serialize-io -- IO Drivers for serialization -- Copyright (C) 2010, 2011, 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.Streams.Files; with Ada.Streams; with Ada.Streams.Stream_IO; with Ada.Exceptions; with Ada.IO_Exceptions; package body Util.Serialize.IO is -- use Util.Log; use type Util.Log.Loggers.Logger_Access; -- The logger' Log : aliased constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("Util.Serialize.IO", Util.Log.WARN_LEVEL); procedure Write_Attribute (Stream : in out Output_Stream'Class; Name : in String; Value : in Ada.Strings.Unbounded.Unbounded_String) is begin Stream.Write_Attribute (Name, Ada.Strings.Unbounded.To_String (Value)); end Write_Attribute; procedure Write_Entity (Stream : in out Output_Stream'Class; Name : in String; Value : in Ada.Strings.Unbounded.Unbounded_String) is begin Stream.Write_Entity (Name, Ada.Strings.Unbounded.To_String (Value)); end Write_Entity; -- ------------------------------ -- Read the file and parse it using the JSON parser. -- ------------------------------ procedure Parse (Handler : in out Parser; File : in String; Sink : in out Reader'Class) is Stream : aliased Util.Streams.Files.File_Stream; Buffer : Util.Streams.Buffered.Buffered_Stream; begin if Handler.Error_Logger = null then Handler.Error_Logger := Log'Access; end if; Handler.Error_Logger.Info ("Reading file {0}", File); Handler.File := Ada.Strings.Unbounded.To_Unbounded_String (File); Buffer.Initialize (Output => null, Input => Stream'Unchecked_Access, Size => 1024); Stream.Open (Mode => Ada.Streams.Stream_IO.In_File, Name => File); -- Context_Stack.Clear (Handler.Stack); Parser'Class (Handler).Parse (Buffer, Sink); exception -- when Util.Serialize.Mappers.Field_Fatal_Error => -- null; when Ada.IO_Exceptions.Name_Error => Parser'Class (Handler).Error ("File '" & File & "' does not exist."); when E : others => if not Handler.Error_Flag then Parser'Class (Handler).Error ("Exception " & Ada.Exceptions.Exception_Name (E)); end if; end Parse; -- ------------------------------ -- Parse the content string. -- ------------------------------ procedure Parse_String (Handler : in out Parser; Content : in String; Sink : in out Reader'Class) is Stream : aliased Util.Streams.Buffered.Buffered_Stream; begin if Handler.Error_Logger = null then Handler.Error_Logger := Log'Access; end if; Handler.File := Ada.Strings.Unbounded.To_Unbounded_String ("<inline>"); Stream.Initialize (Content => Content); -- Context_Stack.Clear (Handler.Stack); Parser'Class (Handler).Parse (Stream, Sink); exception -- when Util.Serialize.Mappers.Field_Fatal_Error => -- null; when E : others => if not Handler.Error_Flag then Parser'Class (Handler).Error ("Exception " & Ada.Exceptions.Exception_Name (E)); end if; end Parse_String; -- ------------------------------ -- Returns true if the <b>Parse</b> operation detected at least one error. -- ------------------------------ function Has_Error (Handler : in Parser) return Boolean is begin return Handler.Error_Flag; end Has_Error; -- ------------------------------ -- Set the error logger to report messages while parsing and reading the input file. -- ------------------------------ procedure Set_Logger (Handler : in out Parser; Logger : in Util.Log.Loggers.Logger_Access) is begin Handler.Error_Logger := Logger; end Set_Logger; -- ------------------------------ -- Get the current location (file and line) to report an error message. -- ------------------------------ function Get_Location (Handler : in Parser) return String is begin return Ada.Strings.Unbounded.To_String (Handler.File); end Get_Location; -- ------------------------------ -- Report an error while parsing the input stream. The error message will be reported -- on the logger associated with the parser. The parser will be set as in error so that -- the <b>Has_Error</b> function will return True after parsing the whole file. -- ------------------------------ procedure Error (Handler : in out Parser; Message : in String) is begin Handler.Error_Logger.Error ("{0}: {1}", Parser'Class (Handler).Get_Location, Message); Handler.Error_Flag := True; end Error; end Util.Serialize.IO;
----------------------------------------------------------------------- -- util-serialize-io -- IO Drivers for serialization -- Copyright (C) 2010, 2011, 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.Streams.Files; with Ada.Streams; with Ada.Streams.Stream_IO; with Ada.Exceptions; with Ada.IO_Exceptions; package body Util.Serialize.IO is -- use Util.Log; use type Util.Log.Loggers.Logger_Access; -- The logger' Log : aliased constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("Util.Serialize.IO", Util.Log.WARN_LEVEL); procedure Write_Attribute (Stream : in out Output_Stream'Class; Name : in String; Value : in Ada.Strings.Unbounded.Unbounded_String) is begin Stream.Write_Attribute (Name, Ada.Strings.Unbounded.To_String (Value)); end Write_Attribute; procedure Write_Entity (Stream : in out Output_Stream'Class; Name : in String; Value : in Ada.Strings.Unbounded.Unbounded_String) is begin Stream.Write_Entity (Name, Ada.Strings.Unbounded.To_String (Value)); end Write_Entity; -- ------------------------------ -- Read the file and parse it using the JSON parser. -- ------------------------------ procedure Parse (Handler : in out Parser; File : in String; Sink : in out Reader'Class) is Stream : aliased Util.Streams.Files.File_Stream; Buffer : Util.Streams.Buffered.Buffered_Stream; begin if Handler.Error_Logger = null then Handler.Error_Logger := Log'Access; end if; Handler.Error_Logger.Info ("Reading file {0}", File); Handler.File := Ada.Strings.Unbounded.To_Unbounded_String (File); Buffer.Initialize (Output => null, Input => Stream'Unchecked_Access, Size => 1024); Stream.Open (Mode => Ada.Streams.Stream_IO.In_File, Name => File); -- Context_Stack.Clear (Handler.Stack); Sink.Start_Document; Parser'Class (Handler).Parse (Buffer, Sink); exception -- when Util.Serialize.Mappers.Field_Fatal_Error => -- null; when Ada.IO_Exceptions.Name_Error => Parser'Class (Handler).Error ("File '" & File & "' does not exist."); when E : others => if not Handler.Error_Flag then Parser'Class (Handler).Error ("Exception " & Ada.Exceptions.Exception_Name (E)); end if; end Parse; -- ------------------------------ -- Parse the content string. -- ------------------------------ procedure Parse_String (Handler : in out Parser; Content : in String; Sink : in out Reader'Class) is Stream : aliased Util.Streams.Buffered.Buffered_Stream; begin if Handler.Error_Logger = null then Handler.Error_Logger := Log'Access; end if; Handler.File := Ada.Strings.Unbounded.To_Unbounded_String ("<inline>"); Stream.Initialize (Content => Content); -- Context_Stack.Clear (Handler.Stack); Sink.Start_Document; Parser'Class (Handler).Parse (Stream, Sink); exception -- when Util.Serialize.Mappers.Field_Fatal_Error => -- null; when E : others => if not Handler.Error_Flag then Parser'Class (Handler).Error ("Exception " & Ada.Exceptions.Exception_Name (E)); end if; end Parse_String; -- ------------------------------ -- Returns true if the <b>Parse</b> operation detected at least one error. -- ------------------------------ function Has_Error (Handler : in Parser) return Boolean is begin return Handler.Error_Flag; end Has_Error; -- ------------------------------ -- Set the error logger to report messages while parsing and reading the input file. -- ------------------------------ procedure Set_Logger (Handler : in out Parser; Logger : in Util.Log.Loggers.Logger_Access) is begin Handler.Error_Logger := Logger; end Set_Logger; -- ------------------------------ -- Get the current location (file and line) to report an error message. -- ------------------------------ function Get_Location (Handler : in Parser) return String is begin return Ada.Strings.Unbounded.To_String (Handler.File); end Get_Location; -- ------------------------------ -- Report an error while parsing the input stream. The error message will be reported -- on the logger associated with the parser. The parser will be set as in error so that -- the <b>Has_Error</b> function will return True after parsing the whole file. -- ------------------------------ procedure Error (Handler : in out Parser; Message : in String) is begin Handler.Error_Logger.Error ("{0}: {1}", Parser'Class (Handler).Get_Location, Message); Handler.Error_Flag := True; end Error; end Util.Serialize.IO;
Call the Start_Document operation before parsing the stream
Call the Start_Document operation before parsing the stream
Ada
apache-2.0
stcarrez/ada-util,stcarrez/ada-util
3055807e0f56ee626d1b3d46569c4693ac7b78f4
src/wiki-filters-html.adb
src/wiki-filters-html.adb
----------------------------------------------------------------------- -- wiki-filters-html -- Wiki HTML filters -- Copyright (C) 2015, 2019, 2020 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Wiki.Helpers; package body Wiki.Filters.Html is -- ------------------------------ -- Add a simple node such as N_LINE_BREAK, N_HORIZONTAL_RULE or N_PARAGRAPH to the document. -- ------------------------------ overriding procedure Add_Node (Filter : in out Html_Filter_Type; Document : in out Wiki.Documents.Document; Kind : in Wiki.Nodes.Simple_Node_Kind) is Tag : Html_Tag; begin case Kind is when N_LINE_BREAK => Tag := BR_TAG; when N_PARAGRAPH => Tag := P_TAG; when N_HORIZONTAL_RULE => Tag := HR_TAG; when N_TOC_DISPLAY => return; when N_NEWLINE => Filter_Type (Filter).Add_Node (Document, Kind); return; end case; if Filter.Allowed (Tag) then Filter_Type (Filter).Add_Node (Document, Kind); end if; end Add_Node; -- ------------------------------ -- Add a text content with the given format to the document. -- ------------------------------ overriding procedure Add_Text (Filter : in out Html_Filter_Type; Document : in out Wiki.Documents.Document; Text : in Wiki.Strings.WString; Format : in Wiki.Format_Map) is begin if Filter.Hide_Level > 0 then return; end if; Filter_Type (Filter).Add_Text (Document, Text, Format); end Add_Text; -- ------------------------------ -- Add a section header with the given level in the document. -- ------------------------------ overriding procedure Add_Header (Filter : in out Html_Filter_Type; Document : in out Wiki.Documents.Document; Header : in Wiki.Strings.WString; Level : in Natural) is begin Filter.Flush_Stack (Document); Filter_Type (Filter).Add_Header (Document, Header, Level); end Add_Header; -- ------------------------------ -- Push a HTML node with the given tag to the document. -- ------------------------------ overriding procedure Push_Node (Filter : in out Html_Filter_Type; Document : in out Wiki.Documents.Document; Tag : in Wiki.Html_Tag; Attributes : in out Wiki.Attributes.Attribute_List) is Current_Tag : Html_Tag; begin while not Filter.Stack.Is_Empty loop Current_Tag := Filter.Stack.Last_Element; if Wiki.Helpers.Need_Close (Tag, Current_Tag) then if Filter.Hide_Level = 0 then Filter_Type (Filter).Pop_Node (Document, Current_Tag); end if; Filter.Stack.Delete_Last; end if; exit; end loop; if Filter.Hidden (Tag) then Filter.Hide_Level := Filter.Hide_Level + 1; elsif not Filter.Allowed (Tag) then return; end if; Filter.Stack.Append (Tag); if Filter.Hide_Level = 0 then Filter_Type (Filter).Push_Node (Document, Tag, Attributes); end if; end Push_Node; -- ------------------------------ -- Pop a HTML node with the given tag. -- ------------------------------ overriding procedure Pop_Node (Filter : in out Html_Filter_Type; Document : in out Wiki.Documents.Document; Tag : in Wiki.Html_Tag) is Current_Tag : Html_Tag; begin if Filter.Stack.Is_Empty then return; elsif not Filter.Allowed (Tag) and not Filter.Hidden (Tag) then return; end if; -- Emit a end tag element until we find our matching tag and the top most tag -- allows the end tag to be omitted (ex: a td, tr, td, dd, ...). while not Filter.Stack.Is_Empty loop Current_Tag := Filter.Stack.Last_Element; exit when Current_Tag = Tag or not Tag_Omission (Current_Tag); if Filter.Hide_Level = 0 then Filter_Type (Filter).Pop_Node (Document, Current_Tag); end if; Filter.Stack.Delete_Last; end loop; if Filter.Hide_Level = 0 then Filter_Type (Filter).Pop_Node (Document, Tag); end if; if Filter.Hidden (Current_Tag) then Filter.Hide_Level := Filter.Hide_Level - 1; end if; Filter.Stack.Delete_Last; end Pop_Node; -- ------------------------------ -- Add a link. -- ------------------------------ overriding procedure Add_Link (Filter : in out Html_Filter_Type; Document : in out Wiki.Documents.Document; Name : in Wiki.Strings.WString; Attributes : in out Wiki.Attributes.Attribute_List) is begin if Filter.Allowed (A_TAG) then Filter_Type (Filter).Add_Link (Document, Name, Attributes); end if; end Add_Link; -- ------------------------------ -- Add an image. -- ------------------------------ overriding procedure Add_Image (Filter : in out Html_Filter_Type; Document : in out Wiki.Documents.Document; Name : in Wiki.Strings.WString; Attributes : in out Wiki.Attributes.Attribute_List) is begin if Filter.Allowed (IMG_TAG) then Filter_Type (Filter).Add_Image (Document, Name, Attributes); end if; end Add_Image; -- ------------------------------ -- Flush the HTML element that have not yet been closed. -- ------------------------------ procedure Flush_Stack (Filter : in out Html_Filter_Type; Document : in out Wiki.Documents.Document) is begin while not Filter.Stack.Is_Empty loop declare Tag : constant Html_Tag := Filter.Stack.Last_Element; begin if Filter.Hide_Level = 0 then Filter_Type (Filter).Pop_Node (Document, Tag); end if; if Filter.Hidden (Tag) then Filter.Hide_Level := Filter.Hide_Level - 1; end if; end; Filter.Stack.Delete_Last; end loop; end Flush_Stack; -- ------------------------------ -- Finish the document after complete wiki text has been parsed. -- ------------------------------ overriding procedure Finish (Filter : in out Html_Filter_Type; Document : in out Wiki.Documents.Document) is begin Filter.Flush_Stack (Document); Filter_Type (Filter).Finish (Document); end Finish; -- ------------------------------ -- Mark the HTML tag as being forbidden. -- ------------------------------ procedure Forbidden (Filter : in out Html_Filter_Type; Tag : in Html_Tag) is begin Filter.Allowed (Tag) := False; end Forbidden; -- ------------------------------ -- Mark the HTML tag as being allowed. -- ------------------------------ procedure Allowed (Filter : in out Html_Filter_Type; Tag : in Html_Tag) is begin Filter.Allowed (Tag) := True; end Allowed; -- ------------------------------ -- Mark the HTML tag as being hidden. The tag and its inner content including the text -- will be removed and not passed to the final document. -- ------------------------------ procedure Hide (Filter : in out Html_Filter_Type; Tag : in Html_Tag) is begin Filter.Hidden (Tag) := True; end Hide; -- ------------------------------ -- Mark the HTML tag as being visible. -- ------------------------------ procedure Visible (Filter : in out Html_Filter_Type; Tag : in Html_Tag) is begin Filter.Hidden (Tag) := False; end Visible; end Wiki.Filters.Html;
----------------------------------------------------------------------- -- wiki-filters-html -- Wiki HTML filters -- Copyright (C) 2015, 2019, 2020, 2022 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Wiki.Helpers; package body Wiki.Filters.Html is -- ------------------------------ -- Add a simple node such as N_LINE_BREAK, N_HORIZONTAL_RULE or N_PARAGRAPH to the document. -- ------------------------------ overriding procedure Add_Node (Filter : in out Html_Filter_Type; Document : in out Wiki.Documents.Document; Kind : in Wiki.Nodes.Simple_Node_Kind) is Tag : Html_Tag; begin case Kind is when N_LINE_BREAK => Tag := BR_TAG; when N_PARAGRAPH => Tag := P_TAG; when N_HORIZONTAL_RULE => Tag := HR_TAG; when N_TOC_DISPLAY | N_NONE => return; when N_NEWLINE | N_LIST_END | N_LIST_ITEM_END | N_NUM_LIST_END | N_LIST_ITEM => Filter_Type (Filter).Add_Node (Document, Kind); return; end case; if Filter.Allowed (Tag) then Filter_Type (Filter).Add_Node (Document, Kind); end if; end Add_Node; -- ------------------------------ -- Add a text content with the given format to the document. -- ------------------------------ overriding procedure Add_Text (Filter : in out Html_Filter_Type; Document : in out Wiki.Documents.Document; Text : in Wiki.Strings.WString; Format : in Wiki.Format_Map) is begin if Filter.Hide_Level > 0 then return; end if; Filter_Type (Filter).Add_Text (Document, Text, Format); end Add_Text; -- ------------------------------ -- Add a section header with the given level in the document. -- ------------------------------ overriding procedure Add_Header (Filter : in out Html_Filter_Type; Document : in out Wiki.Documents.Document; Header : in Wiki.Strings.WString; Level : in Natural) is begin Filter.Flush_Stack (Document); Filter_Type (Filter).Add_Header (Document, Header, Level); end Add_Header; -- ------------------------------ -- Push a HTML node with the given tag to the document. -- ------------------------------ overriding procedure Push_Node (Filter : in out Html_Filter_Type; Document : in out Wiki.Documents.Document; Tag : in Wiki.Html_Tag; Attributes : in out Wiki.Attributes.Attribute_List) is Current_Tag : Html_Tag; begin while not Filter.Stack.Is_Empty loop Current_Tag := Filter.Stack.Last_Element; if Wiki.Helpers.Need_Close (Tag, Current_Tag) then if Filter.Hide_Level = 0 then Filter_Type (Filter).Pop_Node (Document, Current_Tag); end if; Filter.Stack.Delete_Last; end if; exit; end loop; if Filter.Hidden (Tag) then Filter.Hide_Level := Filter.Hide_Level + 1; elsif not Filter.Allowed (Tag) then return; end if; Filter.Stack.Append (Tag); if Filter.Hide_Level = 0 then Filter_Type (Filter).Push_Node (Document, Tag, Attributes); end if; end Push_Node; -- ------------------------------ -- Pop a HTML node with the given tag. -- ------------------------------ overriding procedure Pop_Node (Filter : in out Html_Filter_Type; Document : in out Wiki.Documents.Document; Tag : in Wiki.Html_Tag) is Current_Tag : Html_Tag; begin if Filter.Stack.Is_Empty then return; elsif not Filter.Allowed (Tag) and not Filter.Hidden (Tag) then return; end if; -- Emit a end tag element until we find our matching tag and the top most tag -- allows the end tag to be omitted (ex: a td, tr, td, dd, ...). while not Filter.Stack.Is_Empty loop Current_Tag := Filter.Stack.Last_Element; exit when Current_Tag = Tag or not Tag_Omission (Current_Tag); if Filter.Hide_Level = 0 then Filter_Type (Filter).Pop_Node (Document, Current_Tag); end if; Filter.Stack.Delete_Last; end loop; if Filter.Hide_Level = 0 then Filter_Type (Filter).Pop_Node (Document, Tag); end if; if Filter.Hidden (Current_Tag) then Filter.Hide_Level := Filter.Hide_Level - 1; end if; Filter.Stack.Delete_Last; end Pop_Node; -- ------------------------------ -- Add a link. -- ------------------------------ overriding procedure Add_Link (Filter : in out Html_Filter_Type; Document : in out Wiki.Documents.Document; Name : in Wiki.Strings.WString; Attributes : in out Wiki.Attributes.Attribute_List) is begin if Filter.Allowed (A_TAG) then Filter_Type (Filter).Add_Link (Document, Name, Attributes); end if; end Add_Link; -- ------------------------------ -- Add an image. -- ------------------------------ overriding procedure Add_Image (Filter : in out Html_Filter_Type; Document : in out Wiki.Documents.Document; Name : in Wiki.Strings.WString; Attributes : in out Wiki.Attributes.Attribute_List) is begin if Filter.Allowed (IMG_TAG) then Filter_Type (Filter).Add_Image (Document, Name, Attributes); end if; end Add_Image; -- ------------------------------ -- Flush the HTML element that have not yet been closed. -- ------------------------------ procedure Flush_Stack (Filter : in out Html_Filter_Type; Document : in out Wiki.Documents.Document) is begin while not Filter.Stack.Is_Empty loop declare Tag : constant Html_Tag := Filter.Stack.Last_Element; begin if Filter.Hide_Level = 0 then Filter_Type (Filter).Pop_Node (Document, Tag); end if; if Filter.Hidden (Tag) then Filter.Hide_Level := Filter.Hide_Level - 1; end if; end; Filter.Stack.Delete_Last; end loop; end Flush_Stack; -- ------------------------------ -- Finish the document after complete wiki text has been parsed. -- ------------------------------ overriding procedure Finish (Filter : in out Html_Filter_Type; Document : in out Wiki.Documents.Document) is begin Filter.Flush_Stack (Document); Filter_Type (Filter).Finish (Document); end Finish; -- ------------------------------ -- Mark the HTML tag as being forbidden. -- ------------------------------ procedure Forbidden (Filter : in out Html_Filter_Type; Tag : in Html_Tag) is begin Filter.Allowed (Tag) := False; end Forbidden; -- ------------------------------ -- Mark the HTML tag as being allowed. -- ------------------------------ procedure Allowed (Filter : in out Html_Filter_Type; Tag : in Html_Tag) is begin Filter.Allowed (Tag) := True; end Allowed; -- ------------------------------ -- Mark the HTML tag as being hidden. The tag and its inner content including the text -- will be removed and not passed to the final document. -- ------------------------------ procedure Hide (Filter : in out Html_Filter_Type; Tag : in Html_Tag) is begin Filter.Hidden (Tag) := True; end Hide; -- ------------------------------ -- Mark the HTML tag as being visible. -- ------------------------------ procedure Visible (Filter : in out Html_Filter_Type; Tag : in Html_Tag) is begin Filter.Hidden (Tag) := False; end Visible; end Wiki.Filters.Html;
Update to take into account the new document nodes
Update to take into account the new document nodes
Ada
apache-2.0
stcarrez/ada-wiki,stcarrez/ada-wiki
934ef025e0c011029a1024c676657cccbd4c56e0
samples/mapping.adb
samples/mapping.adb
----------------------------------------------------------------------- -- mapping -- Example of serialization mappings -- Copyright (C) 2010, 2011, 2012 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Log.Loggers; package body Mapping is use Util.Beans.Objects; Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("Mapping"); type Property_Fields is (FIELD_NAME, FIELD_VALUE); type Property_Access is access all Property; type Address_Fields is (FIELD_CITY, FIELD_STREET, FIELD_COUNTRY, FIELD_ZIP); type Address_Access is access all Address; procedure Proxy_Address (Attr : in Util.Serialize.Mappers.Mapping'Class; Element : in out Person; Value : in Util.Beans.Objects.Object); function Get_Address_Member (Addr : in Address; Field : in Address_Fields) return Util.Beans.Objects.Object; procedure Set_Member (Addr : in out Address; Field : in Address_Fields; Value : in Util.Beans.Objects.Object); procedure Set_Member (P : in out Property; Field : in Property_Fields; Value : in Util.Beans.Objects.Object); procedure Set_Member (P : in out Property; Field : in Property_Fields; Value : in Util.Beans.Objects.Object) is begin case Field is when FIELD_NAME => P.Name := To_Unbounded_String (Value); when FIELD_VALUE => P.Value := To_Unbounded_String (Value); end case; end Set_Member; package Property_Mapper is new Util.Serialize.Mappers.Record_Mapper (Element_Type => Property, Element_Type_Access => Property_Access, Fields => Property_Fields, Set_Member => Set_Member); -- ------------------------------ -- Set the name/value pair on the current object. -- ------------------------------ procedure Set_Member (P : in out Person; Field : in Person_Fields; Value : in Util.Beans.Objects.Object) is begin Log.Debug ("Person field {0} - {0}", Person_Fields'Image (Field), To_String (Value)); case Field is when FIELD_FIRST_NAME => P.First_Name := To_Unbounded_String (Value); when FIELD_LAST_NAME => P.Last_Name := To_Unbounded_String (Value); when FIELD_AGE => P.Age := To_Integer (Value); when FIELD_ID => P.Id := To_Long_Long_Integer (Value); when FIELD_NAME => P.Name := To_Unbounded_String (Value); when FIELD_USER_NAME => P.Username := To_Unbounded_String (Value); when FIELD_GENDER => P.Gender := To_Unbounded_String (Value); when FIELD_LINK => P.Link := To_Unbounded_String (Value); end case; end Set_Member; -- ------------------------------ -- Set the name/value pair on the current object. -- ------------------------------ function Get_Person_Member (From : in Person; Field : in Person_Fields) return Util.Beans.Objects.Object is begin case Field is when FIELD_FIRST_NAME => return Util.Beans.Objects.To_Object (From.First_Name); when FIELD_LAST_NAME => return Util.Beans.Objects.To_Object (From.Last_Name); when FIELD_AGE => return Util.Beans.Objects.To_Object (From.Age); when FIELD_NAME => return Util.Beans.Objects.To_Object (From.Name); when FIELD_USER_NAME => return Util.Beans.Objects.To_Object (From.Username); when FIELD_LINK => return Util.Beans.Objects.To_Object (From.Link); when FIELD_GENDER => return Util.Beans.Objects.To_Object (From.Gender); when FIELD_ID => return Util.Beans.Objects.To_Object (From.Id); end case; end Get_Person_Member; -- ------------------------------ -- Set the name/value pair on the current object. -- ------------------------------ procedure Set_Member (Addr : in out Address; Field : in Address_Fields; Value : in Util.Beans.Objects.Object) is begin case Field is when FIELD_CITY => Addr.City := To_Unbounded_String (Value); when FIELD_STREET => Addr.Street := To_Unbounded_String (Value); when FIELD_COUNTRY => Addr.Country := To_Unbounded_String (Value); when FIELD_ZIP => Addr.Zip := To_Integer (Value); end case; end Set_Member; function Get_Address_Member (Addr : in Address; Field : in Address_Fields) return Util.Beans.Objects.Object is begin case Field is when FIELD_CITY => return Util.Beans.Objects.To_Object (Addr.City); when FIELD_STREET => return Util.Beans.Objects.To_Object (Addr.Street); when FIELD_COUNTRY => return Util.Beans.Objects.To_Object (Addr.Country); when FIELD_ZIP => return Util.Beans.Objects.To_Object (Addr.Zip); end case; end Get_Address_Member; package Address_Mapper is new Util.Serialize.Mappers.Record_Mapper (Element_Type => Address, Element_Type_Access => Address_Access, Fields => Address_Fields, Set_Member => Set_Member); -- Mapping for the Property record. Property_Mapping : aliased Property_Mapper.Mapper; -- Mapping for the Address record. Address_Mapping : aliased Address_Mapper.Mapper; -- Mapping for the Person record. Person_Mapping : aliased Person_Mapper.Mapper; -- Mapping for a list of Person records (stored as a Vector). Person_Vector_Mapping : aliased Person_Vector_Mapper.Mapper; -- ------------------------------ -- Get the address mapper which describes how to load an Address. -- ------------------------------ function Get_Address_Mapper return Util.Serialize.Mappers.Mapper_Access is begin return Address_Mapping'Access; end Get_Address_Mapper; -- ------------------------------ -- Get the person mapper which describes how to load a Person. -- ------------------------------ function Get_Person_Mapper return Person_Mapper.Mapper_Access is begin return Person_Mapping'Access; end Get_Person_Mapper; -- ------------------------------ -- Get the person vector mapper which describes how to load a list of Person. -- ------------------------------ function Get_Person_Vector_Mapper return Person_Vector_Mapper.Mapper_Access is begin return Person_Vector_Mapping'Access; end Get_Person_Vector_Mapper; -- ------------------------------ -- Helper to give access to the <b>Address</b> member of a <b>Person</b>. -- ------------------------------ procedure Proxy_Address (Attr : in Util.Serialize.Mappers.Mapping'Class; Element : in out Person; Value : in Util.Beans.Objects.Object) is begin Address_Mapper.Set_Member (Attr, Element.Addr, Value); end Proxy_Address; begin Property_Mapping.Add_Default_Mapping; -- XML: JSON: -- ---- ----- -- <city>Paris</city> "city" : "Paris" -- <street>Champs de Mars</street> "street" : "Champs de Mars" -- <country>France</country> "country" : "France" -- <zip>75</zip> "zip" : 75 Address_Mapping.Bind (Get_Address_Member'Access); -- Address_Mapping.Add_Mapping ("info", Property_Mapping'Access, Proxy_Info'Access); Address_Mapping.Add_Default_Mapping; -- XML: -- ---- -- <xxx id='23'> -- <address> -- <city>...</city> -- <street number='44'>..</street> -- <country>..</country> -- <zip>..</zip> -- </address> -- <name>John</name> -- <last_name>Harry</last_name> -- <age>23</age> -- <info><facebook><id>...</id></facebook></info> -- </xxx> -- Person_Mapper.Add_Mapping ("@id"); Person_Mapping.Bind (Get_Person_Member'Access); Person_Mapping.Add_Mapping ("address", Address_Mapping'Access, Proxy_Address'Access); Person_Mapping.Add_Default_Mapping; -- Person_Mapper.Add_Mapping ("info/*"); -- Person_Mapper.Add_Mapping ("address/street/@number"); Person_Vector_Mapping.Set_Mapping (Person_Mapping'Access); end Mapping;
----------------------------------------------------------------------- -- mapping -- Example of serialization mappings -- Copyright (C) 2010, 2011, 2012, 2014 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Log.Loggers; package body Mapping is use Util.Beans.Objects; Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("Mapping"); type Property_Fields is (FIELD_NAME, FIELD_VALUE); type Property_Access is access all Property; type Address_Fields is (FIELD_CITY, FIELD_STREET, FIELD_COUNTRY, FIELD_ZIP); type Address_Access is access all Address; procedure Proxy_Address (Attr : in Util.Serialize.Mappers.Mapping'Class; Element : in out Person; Value : in Util.Beans.Objects.Object); function Get_Address_Member (Addr : in Address; Field : in Address_Fields) return Util.Beans.Objects.Object; procedure Set_Member (Addr : in out Address; Field : in Address_Fields; Value : in Util.Beans.Objects.Object); procedure Set_Member (P : in out Property; Field : in Property_Fields; Value : in Util.Beans.Objects.Object); procedure Set_Member (P : in out Property; Field : in Property_Fields; Value : in Util.Beans.Objects.Object) is begin case Field is when FIELD_NAME => P.Name := To_Unbounded_String (Value); when FIELD_VALUE => P.Value := To_Unbounded_String (Value); end case; end Set_Member; package Property_Mapper is new Util.Serialize.Mappers.Record_Mapper (Element_Type => Property, Element_Type_Access => Property_Access, Fields => Property_Fields, Set_Member => Set_Member); -- ------------------------------ -- Set the name/value pair on the current object. -- ------------------------------ procedure Set_Member (P : in out Person; Field : in Person_Fields; Value : in Util.Beans.Objects.Object) is begin Log.Debug ("Person field {0} - {0}", Person_Fields'Image (Field), To_String (Value)); case Field is when FIELD_FIRST_NAME => P.First_Name := To_Unbounded_String (Value); when FIELD_LAST_NAME => P.Last_Name := To_Unbounded_String (Value); when FIELD_AGE => P.Age := To_Integer (Value); when FIELD_ID => P.Id := To_Long_Long_Integer (Value); when FIELD_NAME => P.Name := To_Unbounded_String (Value); when FIELD_USER_NAME => P.Username := To_Unbounded_String (Value); when FIELD_GENDER => P.Gender := To_Unbounded_String (Value); when FIELD_LINK => P.Link := To_Unbounded_String (Value); end case; end Set_Member; -- ------------------------------ -- Set the name/value pair on the current object. -- ------------------------------ function Get_Person_Member (From : in Person; Field : in Person_Fields) return Util.Beans.Objects.Object is begin case Field is when FIELD_FIRST_NAME => return Util.Beans.Objects.To_Object (From.First_Name); when FIELD_LAST_NAME => return Util.Beans.Objects.To_Object (From.Last_Name); when FIELD_AGE => return Util.Beans.Objects.To_Object (From.Age); when FIELD_NAME => return Util.Beans.Objects.To_Object (From.Name); when FIELD_USER_NAME => return Util.Beans.Objects.To_Object (From.Username); when FIELD_LINK => return Util.Beans.Objects.To_Object (From.Link); when FIELD_GENDER => return Util.Beans.Objects.To_Object (From.Gender); when FIELD_ID => return Util.Beans.Objects.To_Object (From.Id); end case; end Get_Person_Member; -- ------------------------------ -- Set the name/value pair on the current object. -- ------------------------------ procedure Set_Member (Addr : in out Address; Field : in Address_Fields; Value : in Util.Beans.Objects.Object) is begin case Field is when FIELD_CITY => Addr.City := To_Unbounded_String (Value); when FIELD_STREET => Addr.Street := To_Unbounded_String (Value); when FIELD_COUNTRY => Addr.Country := To_Unbounded_String (Value); when FIELD_ZIP => Addr.Zip := To_Integer (Value); end case; end Set_Member; function Get_Address_Member (Addr : in Address; Field : in Address_Fields) return Util.Beans.Objects.Object is begin case Field is when FIELD_CITY => return Util.Beans.Objects.To_Object (Addr.City); when FIELD_STREET => return Util.Beans.Objects.To_Object (Addr.Street); when FIELD_COUNTRY => return Util.Beans.Objects.To_Object (Addr.Country); when FIELD_ZIP => return Util.Beans.Objects.To_Object (Addr.Zip); end case; end Get_Address_Member; package Address_Mapper is new Util.Serialize.Mappers.Record_Mapper (Element_Type => Address, Element_Type_Access => Address_Access, Fields => Address_Fields, Set_Member => Set_Member); -- Mapping for the Property record. Property_Mapping : aliased Property_Mapper.Mapper; -- Mapping for the Address record. Address_Mapping : aliased Address_Mapper.Mapper; -- Mapping for the Person record. Person_Mapping : aliased Person_Mapper.Mapper; -- ------------------------------ -- Get the address mapper which describes how to load an Address. -- ------------------------------ function Get_Address_Mapper return Util.Serialize.Mappers.Mapper_Access is begin return Address_Mapping'Access; end Get_Address_Mapper; -- ------------------------------ -- Get the person mapper which describes how to load a Person. -- ------------------------------ function Get_Person_Mapper return Person_Mapper.Mapper_Access is begin return Person_Mapping'Access; end Get_Person_Mapper; -- ------------------------------ -- Helper to give access to the <b>Address</b> member of a <b>Person</b>. -- ------------------------------ procedure Proxy_Address (Attr : in Util.Serialize.Mappers.Mapping'Class; Element : in out Person; Value : in Util.Beans.Objects.Object) is begin Address_Mapper.Set_Member (Attr, Element.Addr, Value); end Proxy_Address; begin Property_Mapping.Add_Default_Mapping; -- XML: JSON: -- ---- ----- -- <city>Paris</city> "city" : "Paris" -- <street>Champs de Mars</street> "street" : "Champs de Mars" -- <country>France</country> "country" : "France" -- <zip>75</zip> "zip" : 75 Address_Mapping.Bind (Get_Address_Member'Access); -- Address_Mapping.Add_Mapping ("info", Property_Mapping'Access, Proxy_Info'Access); Address_Mapping.Add_Default_Mapping; -- XML: -- ---- -- <xxx id='23'> -- <address> -- <city>...</city> -- <street number='44'>..</street> -- <country>..</country> -- <zip>..</zip> -- </address> -- <name>John</name> -- <last_name>Harry</last_name> -- <age>23</age> -- <info><facebook><id>...</id></facebook></info> -- </xxx> -- Person_Mapper.Add_Mapping ("@id"); Person_Mapping.Bind (Get_Person_Member'Access); Person_Mapping.Add_Mapping ("address", Address_Mapping'Access, Proxy_Address'Access); Person_Mapping.Add_Default_Mapping; -- Person_Mapper.Add_Mapping ("info/*"); -- Person_Mapper.Add_Mapping ("address/street/@number"); end Mapping;
Remove the Person_Vector_Mapper package
Remove the Person_Vector_Mapper package
Ada
apache-2.0
flottokarotto/ada-util,Letractively/ada-util,flottokarotto/ada-util,Letractively/ada-util
18358bb92638fa3d200272ff2c9817234937ce22
src/gen-generator.adb
src/gen-generator.adb
----------------------------------------------------------------------- -- Gen -- Code Generator -- Copyright (C) 2009, 2010 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Directories; with Ada.IO_Exceptions; with Input_Sources.File; with DOM.Core.Documents; with DOM.Readers; with Sax.Readers; with ASF.Requests.Mockup; with ASF.Responses.Mockup; with ASF.Components.Core; with ASF.Contexts.Faces; with ASF.Applications.Views; with ASF.Contexts.Writer.String; with EL.Objects; with EL.Contexts; with EL.Contexts.Default; with EL.Functions; with EL.Variables; with EL.Variables.Default; with Gen.Model; with Gen.Utils; with Util.Files; with Util.Log.Loggers; package body Gen.Generator is use ASF; use Ada.Strings.Unbounded; use Util.Log; Log : constant Loggers.Logger := Loggers.Create ("Gen.Generator"); RESULT_DIR : constant String := "generator.output.dir"; function To_Ada_Type (Name : EL.Objects.Object) return EL.Objects.Object; function Indent (Value : EL.Objects.Object) return EL.Objects.Object; -- EL Function to translate a model type to the key enum value function To_Key_Enum (Name : EL.Objects.Object) return EL.Objects.Object; -- ------------------------------ -- EL Function to translate a model type to an Ada implementation type -- ------------------------------ function To_Ada_Type (Name : EL.Objects.Object) return EL.Objects.Object is Value : constant String := EL.Objects.To_String (Name); begin if Value = "String" then return EL.Objects.To_Object (String '("Unbounded_String")); elsif Value = "Integer" or Value = "int" then return EL.Objects.To_Object (String '("Integer")); else return Name; end if; end To_Ada_Type; -- ------------------------------ -- EL Function to check whether a type is an integer type -- ------------------------------ function Is_Integer_Type (Name : EL.Objects.Object) return EL.Objects.Object is Value : constant String := EL.Objects.To_String (Name); begin if Value = "Integer" or Value = "int" then return EL.Objects.To_Object (True); else return EL.Objects.To_Object (False); end if; end Is_Integer_Type; KEY_INTEGER_LABEL : constant String := "KEY_INTEGER"; KEY_STRING_LABEL : constant String := "KEY_STRING"; -- ------------------------------ -- EL Function to translate a model type to the key enum value -- ------------------------------ function To_Key_Enum (Name : EL.Objects.Object) return EL.Objects.Object is Value : constant String := EL.Objects.To_String (Name); begin if Value = "Integer" or Value = "int" or Value = "Identifier" or Value = "ADO.Identifier" then return EL.Objects.To_Object (KEY_INTEGER_LABEL); else return EL.Objects.To_Object (KEY_STRING_LABEL); end if; end To_Key_Enum; -- ------------------------------ -- EL function to indent the code -- ------------------------------ function Indent (Value : EL.Objects.Object) return EL.Objects.Object is S : constant String := EL.Objects.To_String (Value); Result : constant String (S'Range) := (others => ' '); begin return EL.Objects.To_Object (Result); end Indent; -- ------------------------------ -- EL function to indent the code -- ------------------------------ function To_Sql_Type (Value : EL.Objects.Object) return EL.Objects.Object is Name : constant String := EL.Objects.To_String (Value); Result : Unbounded_String; begin if Name = "Identifier" then Append (Result, "BIGINT NOT NULL"); elsif Name = "Integer" then Append (Result, "INTEGER"); elsif Name = "String" then Append (Result, "VARCHAR(255)"); elsif Name = "Date" then Append (Result, "DATE"); else Append (Result, "VARCHAR(255)"); end if; return EL.Objects.To_Object (Result); end To_Sql_Type; -- ------------------------------ -- Register the generator EL functions -- ------------------------------ procedure Set_Functions (Mapper : in out EL.Functions.Function_Mapper'Class) is URI : constant String := "http://code.google.com/p/ada-ado/generator"; begin Mapper.Set_Function (Name => "adaType", Namespace => URI, Func => To_Ada_Type'Access); Mapper.Set_Function (Name => "indent", Namespace => URI, Func => Indent'Access); Mapper.Set_Function (Name => "isInteger", Namespace => URI, Func => Is_Integer_Type'Access); Mapper.Set_Function (Name => "sqlType", Namespace => URI, Func => To_Sql_Type'Access); Mapper.Set_Function (Name => "keyEnum", Namespace => URI, Func => To_Key_Enum'Access); end Set_Functions; -- ------------------------------ -- Initialize the generator -- ------------------------------ procedure Initialize (H : in out Handler) is procedure Register_Funcs is new ASF.Applications.Main.Register_Functions (Set_Functions); begin H.Conf.Set (ASF.Applications.VIEW_IGNORE_WHITE_SPACES, "false"); H.Conf.Set (ASF.Applications.VIEW_ESCAPE_UNKNOWN_TAGS, "false"); H.Conf.Set (ASF.Applications.VIEW_IGNORE_EMPTY_LINES, "true"); H.Conf.Set (ASF.Applications.VIEW_FILE_EXT, ""); if not H.Conf.Exists (ASF.Applications.VIEW_DIR) then H.Set_Template_Directory ("templates/"); end if; H.Initialize (H.Conf); Register_Funcs (H); end Initialize; -- ------------------------------ -- Set the directory where template files are stored. -- ------------------------------ procedure Set_Template_Directory (H : in out Handler; Path : in String) is begin H.Conf.Set (ASF.Applications.VIEW_DIR, Path); end Set_Template_Directory; -- ------------------------------ -- Set the directory where results files are generated. -- ------------------------------ procedure Set_Result_Directory (H : in out Handler; Path : in String) is begin H.Conf.Set (RESULT_DIR, Path); end Set_Result_Directory; -- ------------------------------ -- Register a model mapping -- ------------------------------ procedure Register_Mapping (H : in out Handler; Node : in DOM.Core.Node) is begin H.Model.Initialize (Node); end Register_Mapping; -- ------------------------------ -- Get the exit status -- Returns 0 if the generation was successful -- Returns 1 if there was a generation error -- ------------------------------ function Get_Status (H : in Handler) return Ada.Command_Line.Exit_Status is begin return H.Status; end Get_Status; -- ------------------------------ -- Report an error and set the exit status accordingly -- ------------------------------ procedure Error (H : in out Handler; Message : in String; Arg1 : in String := ""; Arg2 : in String := "") is begin Log.Error (Message, Arg1, Arg2); H.Status := 1; end Error; -- ------------------------------ -- Read the XML model file -- ------------------------------ procedure Read_Model (H : in out Handler; File : in String) is Read : Input_Sources.File.File_Input; My_Tree_Reader : DOM.Readers.Tree_Reader; Name_Start : Natural; procedure Iterate is new Gen.Utils.Iterate_Nodes (T => Handler, Process => Register_Mapping); begin Log.Info ("Reading model file {0}", File); -- Base file name should be used as the public Id Name_Start := File'Last; while Name_Start >= File'First and then File (Name_Start) /= '/' loop Name_Start := Name_Start - 1; end loop; Input_Sources.File.Open (File, Read); -- Full name is used as the system id Input_Sources.File.Set_System_Id (Read, File); Input_Sources.File.Set_Public_Id (Read, File (Name_Start + 1 .. File'Last)); DOM.Readers.Set_Feature (My_Tree_Reader, Sax.Readers.Validation_Feature, False); DOM.Readers.Parse (My_Tree_Reader, Read); Input_Sources.File.Close (Read); H.Doc := DOM.Readers.Get_Tree (My_Tree_Reader); H.Root := DOM.Core.Documents.Get_Element (H.Doc); Iterate (H, H.Root, "hibernate-mapping"); exception when Ada.IO_Exceptions.Name_Error => H.Error ("Model file {0} does not exist", File); end Read_Model; -- ------------------------------ -- Generate the code using the template file -- ------------------------------ procedure Generate (H : in out Handler; File : in String; Model : in Gen.Model.Definition_Access) is Context : aliased Contexts.Faces.Faces_Context; View : Components.Core.UIViewRoot; Resolver : aliased EL.Contexts.Default.Default_ELResolver; Req : ASF.Requests.Mockup.Request; Reply : ASF.Responses.Mockup.Response; begin Log.Info ("Generating {0}", File); -- Model.Initialize (H.Model); Resolver.Register (To_Unbounded_String ("model"), Model.all'Unchecked_Access); -- Context.Set_Response_Writer (Writer'Unchecked_Access); -- Context.Set_ELContext (ELContext'Unchecked_Access); -- ELContext.Set_Variable_Mapper (Variables'Unchecked_Access); -- ELContext.Set_Resolver (Resolver'Unchecked_Access); -- Writer.Initialize ("text/plain", "UTF-8", 8192); -- H.Set_Context (Context'Unchecked_Access); -- H.Restore_View (File, Context, View); H.Dispatch (Page => File, Request => Req, Response => Reply); declare Dir : constant String := H.Conf.Get (RESULT_DIR, "./"); Result : constant EL.Objects.Object := View.Get_Root.Get_Attribute (Context, "file"); Path : constant String := Dir & EL.Objects.To_String (Result); Content : Unbounded_String; begin Log.Info ("Writing result file {0}", Path); Reply.Read_Content (Content); Util.Files.Write_File (Path => Path, Content => Content); end; end Generate; -- ------------------------------ -- Generate the code using the template file -- ------------------------------ procedure Generate (H : in out Handler; Mode : in Iteration_Mode; File : in String) is begin case Mode is when ITERATION_PACKAGE => declare Pos : Gen.Model.Tables.Package_Cursor := H.Model.First; begin while Gen.Model.Tables.Has_Element (Pos) loop H.Generate (File, Gen.Model.Tables.Element (Pos).all'Access); Gen.Model.Tables.Next (Pos); end loop; end; when ITERATION_TABLE => H.Generate (File, H.Model'Unchecked_Access); end case; end Generate; -- Generate all the code generation files stored in the directory procedure Generate_All (H : in out Handler; Mode : in Iteration_Mode; Name : in String) is use Ada.Directories; Search : Search_Type; Filter : constant Filter_Type := (others => True); Ent : Directory_Entry_Type; Dir : constant String := H.Conf.Get (ASF.Applications.VIEW_DIR); Path : constant String := Dir & Name; begin if Kind (Path) /= Directory then Ada.Text_IO.Put_Line ("Cannot read model directory: " & Path); end if; Start_Search (Search, Directory => Path, Pattern => "*.xhtml", Filter => Filter); while More_Entries (Search) loop Get_Next_Entry (Search, Ent); declare File_Path : constant String := Full_Name (Ent); begin H.Generate (Mode, File_Path); end; end loop; exception when Ada.IO_Exceptions.Name_Error => H.Error ("Template directory {0} does not exist", Path); end Generate_All; end Gen.Generator;
----------------------------------------------------------------------- -- Gen -- Code Generator -- Copyright (C) 2009, 2010 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Directories; with Ada.IO_Exceptions; with Input_Sources.File; with DOM.Core.Documents; with DOM.Readers; with Sax.Readers; with ASF.Requests.Mockup; with ASF.Responses.Mockup; with ASF.Components.Core; with ASF.Contexts.Faces; with ASF.Applications.Views; with EL.Objects; with EL.Contexts; with EL.Contexts.Default; with EL.Functions; with Gen.Model; with Gen.Utils; with Util.Files; with Util.Log.Loggers; package body Gen.Generator is use ASF; use Ada.Strings.Unbounded; use Util.Log; Log : constant Loggers.Logger := Loggers.Create ("Gen.Generator"); RESULT_DIR : constant String := "generator.output.dir"; function To_Ada_Type (Name : EL.Objects.Object) return EL.Objects.Object; function Indent (Value : EL.Objects.Object) return EL.Objects.Object; -- EL Function to translate a model type to the key enum value function To_Key_Enum (Name : EL.Objects.Object) return EL.Objects.Object; -- ------------------------------ -- EL Function to translate a model type to an Ada implementation type -- ------------------------------ function To_Ada_Type (Name : EL.Objects.Object) return EL.Objects.Object is Value : constant String := EL.Objects.To_String (Name); begin if Value = "String" then return EL.Objects.To_Object (String '("Unbounded_String")); elsif Value = "Integer" or Value = "int" then return EL.Objects.To_Object (String '("Integer")); else return Name; end if; end To_Ada_Type; -- ------------------------------ -- EL Function to check whether a type is an integer type -- ------------------------------ function Is_Integer_Type (Name : EL.Objects.Object) return EL.Objects.Object is Value : constant String := EL.Objects.To_String (Name); begin if Value = "Integer" or Value = "int" then return EL.Objects.To_Object (True); else return EL.Objects.To_Object (False); end if; end Is_Integer_Type; KEY_INTEGER_LABEL : constant String := "KEY_INTEGER"; KEY_STRING_LABEL : constant String := "KEY_STRING"; -- ------------------------------ -- EL Function to translate a model type to the key enum value -- ------------------------------ function To_Key_Enum (Name : EL.Objects.Object) return EL.Objects.Object is Value : constant String := EL.Objects.To_String (Name); begin if Value = "Integer" or Value = "int" or Value = "Identifier" or Value = "ADO.Identifier" then return EL.Objects.To_Object (KEY_INTEGER_LABEL); else return EL.Objects.To_Object (KEY_STRING_LABEL); end if; end To_Key_Enum; -- ------------------------------ -- EL function to indent the code -- ------------------------------ function Indent (Value : EL.Objects.Object) return EL.Objects.Object is S : constant String := EL.Objects.To_String (Value); Result : constant String (S'Range) := (others => ' '); begin return EL.Objects.To_Object (Result); end Indent; -- ------------------------------ -- EL function to indent the code -- ------------------------------ function To_Sql_Type (Value : EL.Objects.Object) return EL.Objects.Object is Name : constant String := EL.Objects.To_String (Value); Result : Unbounded_String; begin if Name = "Identifier" then Append (Result, "BIGINT NOT NULL"); elsif Name = "Integer" then Append (Result, "INTEGER"); elsif Name = "String" then Append (Result, "VARCHAR(255)"); elsif Name = "Date" then Append (Result, "DATE"); else Append (Result, "VARCHAR(255)"); end if; return EL.Objects.To_Object (Result); end To_Sql_Type; -- ------------------------------ -- Register the generator EL functions -- ------------------------------ procedure Set_Functions (Mapper : in out EL.Functions.Function_Mapper'Class) is URI : constant String := "http://code.google.com/p/ada-ado/generator"; begin Mapper.Set_Function (Name => "adaType", Namespace => URI, Func => To_Ada_Type'Access); Mapper.Set_Function (Name => "indent", Namespace => URI, Func => Indent'Access); Mapper.Set_Function (Name => "isInteger", Namespace => URI, Func => Is_Integer_Type'Access); Mapper.Set_Function (Name => "sqlType", Namespace => URI, Func => To_Sql_Type'Access); Mapper.Set_Function (Name => "keyEnum", Namespace => URI, Func => To_Key_Enum'Access); end Set_Functions; -- ------------------------------ -- Initialize the generator -- ------------------------------ procedure Initialize (H : in out Handler) is procedure Register_Funcs is new ASF.Applications.Main.Register_Functions (Set_Functions); begin H.Conf.Set (ASF.Applications.VIEW_IGNORE_WHITE_SPACES, "false"); H.Conf.Set (ASF.Applications.VIEW_ESCAPE_UNKNOWN_TAGS, "false"); H.Conf.Set (ASF.Applications.VIEW_IGNORE_EMPTY_LINES, "true"); H.Conf.Set (ASF.Applications.VIEW_FILE_EXT, ""); if not H.Conf.Exists (ASF.Applications.VIEW_DIR) then H.Set_Template_Directory ("templates/"); end if; H.Initialize (H.Conf); Register_Funcs (H); end Initialize; -- ------------------------------ -- Set the directory where template files are stored. -- ------------------------------ procedure Set_Template_Directory (H : in out Handler; Path : in String) is begin H.Conf.Set (ASF.Applications.VIEW_DIR, Path); end Set_Template_Directory; -- ------------------------------ -- Set the directory where results files are generated. -- ------------------------------ procedure Set_Result_Directory (H : in out Handler; Path : in String) is begin H.Conf.Set (RESULT_DIR, Path); end Set_Result_Directory; -- ------------------------------ -- Register a model mapping -- ------------------------------ procedure Register_Mapping (H : in out Handler; Node : in DOM.Core.Node) is begin H.Model.Initialize (Node); end Register_Mapping; -- ------------------------------ -- Get the exit status -- Returns 0 if the generation was successful -- Returns 1 if there was a generation error -- ------------------------------ function Get_Status (H : in Handler) return Ada.Command_Line.Exit_Status is begin return H.Status; end Get_Status; -- ------------------------------ -- Report an error and set the exit status accordingly -- ------------------------------ procedure Error (H : in out Handler; Message : in String; Arg1 : in String := ""; Arg2 : in String := "") is begin Log.Error (Message, Arg1, Arg2); H.Status := 1; end Error; -- ------------------------------ -- Read the XML model file -- ------------------------------ procedure Read_Model (H : in out Handler; File : in String) is Read : Input_Sources.File.File_Input; My_Tree_Reader : DOM.Readers.Tree_Reader; Name_Start : Natural; procedure Iterate is new Gen.Utils.Iterate_Nodes (T => Handler, Process => Register_Mapping); begin Log.Info ("Reading model file {0}", File); -- Base file name should be used as the public Id Name_Start := File'Last; while Name_Start >= File'First and then File (Name_Start) /= '/' loop Name_Start := Name_Start - 1; end loop; Input_Sources.File.Open (File, Read); -- Full name is used as the system id Input_Sources.File.Set_System_Id (Read, File); Input_Sources.File.Set_Public_Id (Read, File (Name_Start + 1 .. File'Last)); DOM.Readers.Set_Feature (My_Tree_Reader, Sax.Readers.Validation_Feature, False); DOM.Readers.Parse (My_Tree_Reader, Read); Input_Sources.File.Close (Read); H.Doc := DOM.Readers.Get_Tree (My_Tree_Reader); H.Root := DOM.Core.Documents.Get_Element (H.Doc); Iterate (H, H.Root, "hibernate-mapping"); exception when Ada.IO_Exceptions.Name_Error => H.Error ("Model file {0} does not exist", File); end Read_Model; -- ------------------------------ -- Generate the code using the template file -- ------------------------------ procedure Generate (H : in out Handler; File : in String; Model : in Gen.Model.Definition_Access) is Context : aliased Contexts.Faces.Faces_Context; View : Components.Core.UIViewRoot; Resolver : aliased EL.Contexts.Default.Default_ELResolver; Req : ASF.Requests.Mockup.Request; Reply : ASF.Responses.Mockup.Response; Bean : constant EL.Objects.Object := EL.Objects.To_Object (Model.all'Unchecked_Access); begin Log.Info ("Generating {0}", File); Req.Set_Attribute (Name => "model", Value => Bean); Resolver.Register (To_Unbounded_String ("model"), Model.all'Unchecked_Access); H.Dispatch (Page => File, Request => Req, Response => Reply); declare Dir : constant String := H.Conf.Get (RESULT_DIR, "./"); Result : constant EL.Objects.Object := View.Get_Root.Get_Attribute (Context, "file"); Path : constant String := Dir & EL.Objects.To_String (Result); Content : Unbounded_String; begin Log.Info ("Writing result file {0}", Path); Reply.Read_Content (Content); Util.Files.Write_File (Path => Path, Content => Content); end; end Generate; -- ------------------------------ -- Generate the code using the template file -- ------------------------------ procedure Generate (H : in out Handler; Mode : in Iteration_Mode; File : in String) is begin case Mode is when ITERATION_PACKAGE => declare Pos : Gen.Model.Tables.Package_Cursor := H.Model.First; begin while Gen.Model.Tables.Has_Element (Pos) loop H.Generate (File, Gen.Model.Tables.Element (Pos).all'Access); Gen.Model.Tables.Next (Pos); end loop; end; when ITERATION_TABLE => H.Generate (File, H.Model'Unchecked_Access); end case; end Generate; -- Generate all the code generation files stored in the directory procedure Generate_All (H : in out Handler; Mode : in Iteration_Mode; Name : in String) is use Ada.Directories; Search : Search_Type; Filter : constant Filter_Type := (others => True); Ent : Directory_Entry_Type; Dir : constant String := H.Conf.Get (ASF.Applications.VIEW_DIR); Path : constant String := Dir & Name; begin if Kind (Path) /= Directory then Ada.Text_IO.Put_Line ("Cannot read model directory: " & Path); end if; Start_Search (Search, Directory => Path, Pattern => "*.xhtml", Filter => Filter); while More_Entries (Search) loop Get_Next_Entry (Search, Ent); declare File_Path : constant String := Full_Name (Ent); begin H.Generate (Mode, File_Path); end; end loop; exception when Ada.IO_Exceptions.Name_Error => H.Error ("Template directory {0} does not exist", Path); end Generate_All; end Gen.Generator;
Store the model bean in a request mockup object
Store the model bean in a request mockup object
Ada
apache-2.0
Letractively/ada-gen,Letractively/ada-gen,Letractively/ada-gen,Letractively/ada-gen
386ddecc2ec215be37a69d23a558b9d823d1539a
regtests/util-log-tests.adb
regtests/util-log-tests.adb
----------------------------------------------------------------------- -- log.tests -- Unit tests for loggers -- Copyright (C) 2009, 2010, 2011, 2013, 2015, 2018, 2021 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Strings.Fixed; with Ada.Directories; with Ada.Text_IO; with Ada.Strings.Unbounded; with Util.Test_Caller; with Util.Log; with Util.Log.Loggers; with Util.Files; with Util.Properties; with Util.Measures; package body Util.Log.Tests is Log : constant Loggers.Logger := Loggers.Create ("util.log.test"); procedure Test_Log (T : in out Test) is L : Loggers.Logger := Loggers.Create ("util.log.test.debug"); begin L.Set_Level (DEBUG_LEVEL); Log.Info ("My log message"); Log.Error ("My error message"); Log.Debug ("A debug message Not printed"); L.Info ("An info message"); L.Info ("A {0} {1} {2} {3}", "info", "message", "not", "printed"); L.Debug ("A debug message on logger 'L'"); Util.Tests.Assert_Equals (T, "DEBUG", L.Get_Level_Name, "Get_Level_Name function is invalid"); end Test_Log; procedure Test_Debug (T : in out Test) is L : Loggers.Logger := Loggers.Create ("util.log.test.debug"); C : Ada.Strings.Unbounded.Unbounded_String; begin L.Set_Level (DEBUG_LEVEL); L.Info ("My log message"); L.Error ("My error message"); L.Debug ("A {0} {1} {2} {3}", "debug", "message", "not", "printed"); L.Debug ("A {0} {1} {2} {3}", C, "message", "printed"); L.Info ("An info message"); L.Debug ("A debug message on logger 'L'"); Util.Tests.Assert_Equals (T, "DEBUG", L.Get_Level_Name, "Get_Level_Name function is invalid"); end Test_Debug; -- Test configuration and creation of file procedure Test_File_Appender (T : in out Test) is Path : constant String := Util.Tests.Get_Test_Path ("test.log"); Props : Util.Properties.Manager; begin Props.Set ("log4j.appender.test", "File"); Props.Set ("log4j.appender.test.File", Path); Props.Set ("log4j.logger.util.log.test.file", "DEBUG,test"); Util.Log.Loggers.Initialize (Props); declare L : constant Loggers.Logger := Loggers.Create ("util.log.test.file"); begin L.Debug ("Writing a debug message"); L.Debug ("{0}: {1}", "Parameter", "Value"); end; T.Assert (Ada.Directories.Exists (Path), "Log file " & Path & " not found"); end Test_File_Appender; procedure Test_Log_Perf (T : in out Test) is Path : constant String := Util.Tests.Get_Test_Path ("test_perf.log"); Props : Util.Properties.Manager; begin Props.Set ("log4j.appender.test", "File"); Props.Set ("log4j.appender.test.File", Path); Props.Set ("log4j.logger.util.log.test.perf", "DEBUG,test"); Util.Log.Loggers.Initialize (Props); for I in 1 .. 1000 loop declare S : Util.Measures.Stamp; begin Util.Measures.Report (S, "Util.Measures.Report", 1000); end; end loop; declare L : Loggers.Logger := Loggers.Create ("util.log.test.perf"); S : Util.Measures.Stamp; begin L.Set_Level (DEBUG_LEVEL); for I in 1 .. 1000 loop L.Info ("My log message: {0}: {1}", "A message", "A second parameter"); end loop; Util.Measures.Report (S, "Log.Info message (output)", 1000); L.Set_Level (INFO_LEVEL); for I in 1 .. 10_000 loop L.Debug ("My log message: {0}: {1}", "A message", "A second parameter"); end loop; Util.Measures.Report (S, "Log.Debug message (no output)", 10_000); end; T.Assert (Ada.Directories.Exists (Path), "Log file " & Path & " not found"); end Test_Log_Perf; -- ------------------------------ -- Test appending the log on several log files -- ------------------------------ procedure Test_List_Appender (T : in out Test) is use Ada.Strings; use Ada.Directories; Props : Util.Properties.Manager; begin for I in 1 .. 10 loop declare Id : constant String := Fixed.Trim (Integer'Image (I), Both); Path : constant String := Util.Tests.Get_Test_Path ("test" & Id & ".log"); Name : constant String := "log4j.appender.test" & Id; begin Props.Set (Name, "File"); Props.Set (Name & ".File", Path); Props.Set (Name & ".layout", "date-level-message"); if I > 5 then Props.Set (Name & ".level", "INFO"); end if; end; end loop; Props.Set ("log4j.rootCategory", "DEBUG, test.log"); Props.Set ("log4j.logger.util.log.test.file", "DEBUG,test4,test1 , test2,test3, test4, test5 , test6 , test7,test8,"); Util.Log.Loggers.Initialize (Props); declare L : constant Loggers.Logger := Loggers.Create ("util.log.test.file"); begin L.Debug ("Writing a debug message"); L.Debug ("{0}: {1}", "Parameter", "Value"); L.Debug ("Done"); end; -- Check that we have non empty log files (up to test8.log). for I in 1 .. 8 loop declare Id : constant String := Fixed.Trim (Integer'Image (I), Both); Path : constant String := Util.Tests.Get_Test_Path ("test" & Id & ".log"); begin T.Assert (Ada.Directories.Exists (Path), "Log file " & Path & " not found"); if I > 5 then T.Assert (Ada.Directories.Size (Path) < 100, "Log file " & Path & " should be empty"); else T.Assert (Ada.Directories.Size (Path) > 100, "Log file " & Path & " is empty"); end if; end; end loop; end Test_List_Appender; -- ------------------------------ -- Test file appender with different modes. -- ------------------------------ procedure Test_File_Appender_Modes (T : in out Test) is use Ada.Directories; Append_Path : constant String := Util.Tests.Get_Test_Path ("test-append.log"); Append2_Path : constant String := Util.Tests.Get_Test_Path ("test-append2.log"); Global_Path : constant String := Util.Tests.Get_Test_Path ("test-append-global.log"); Props : Util.Properties.Manager; begin Props.Set ("log4j.appender.test", "File"); Props.Set ("log4j.appender.test.File", Append_Path); Props.Set ("log4j.appender.test.append", "true"); Props.Set ("log4j.appender.test.immediateFlush", "true"); Props.Set ("log4j.appender.test_global", "File"); Props.Set ("log4j.appender.test_global.File", Global_Path); Props.Set ("log4j.appender.test_global.append", "false"); Props.Set ("log4j.appender.test_global.immediateFlush", "false"); Props.Set ("log4j.logger.util.log.test.file", "DEBUG"); Props.Set ("log4j.rootCategory", "DEBUG,test_global,test"); Util.Log.Loggers.Initialize (Props); declare L : constant Loggers.Logger := Loggers.Create ("util.log.test.file"); begin L.Debug ("Writing a debug message"); L.Debug ("{0}: {1}", "Parameter", "Value"); L.Debug ("Done"); L.Error ("This is the error test message"); end; Props.Set ("log4j.appender.test_append", "File"); Props.Set ("log4j.appender.test_append.File", Append2_Path); Props.Set ("log4j.appender.test_append.append", "true"); Props.Set ("log4j.appender.test_append.immediateFlush", "true"); Props.Set ("log4j.logger.util.log.test2.file", "DEBUG,test_append,test_global"); Util.Log.Loggers.Initialize (Props); declare L1 : constant Loggers.Logger := Loggers.Create ("util.log.test.file"); L2 : constant Loggers.Logger := Loggers.Create ("util.log.test2.file"); begin L1.Info ("L1-1 Writing a info message"); L2.Info ("L2-2 {0}: {1}", "Parameter", "Value"); L1.Info ("L1-3 Done"); L2.Error ("L2-4 This is the error test2 message"); end; Props.Set ("log4j.appender.test_append.append", "plop"); Props.Set ("log4j.appender.test_append.immediateFlush", "falsex"); Props.Set ("log4j.rootCategory", "DEBUG, test.log"); Util.Log.Loggers.Initialize (Props); T.Assert (Ada.Directories.Size (Append_Path) > 100, "Log file test-append.log is empty"); T.Assert (Ada.Directories.Size (Append2_Path) > 100, "Log file test-append2.log is empty"); T.Assert (Ada.Directories.Size (Global_Path) > 100, "Log file test-append.log is empty"); end Test_File_Appender_Modes; -- ------------------------------ -- Test file appender with different modes. -- ------------------------------ procedure Test_Console_Appender (T : in out Test) is Path : constant String := Util.Tests.Get_Test_Path ("test_err.log"); Props : Util.Properties.Manager; File : Ada.Text_IO.File_Type; Content : Ada.Strings.Unbounded.Unbounded_String; begin Ada.Text_IO.Create (File, Ada.Text_IO.Out_File, Path); Ada.Text_IO.Set_Error (File); Props.Set ("log4j.appender.test_console", "Console"); Props.Set ("log4j.appender.test_console.stderr", "true"); Props.Set ("log4j.appender.test_console.level", "WARN"); Props.Set ("log4j.rootCategory", "INFO,test_console"); Util.Log.Loggers.Initialize (Props); declare L : constant Loggers.Logger := Loggers.Create ("util.log.test.file"); begin L.Debug ("Writing a debug message"); L.Debug ("{0}: {1}", "Parameter", "Value"); L.Debug ("Done"); L.Info ("INFO MESSAGE!"); L.Warn ("WARN MESSAGE!"); L.Error ("This {0} {1} {2} test message", "is", "the", "error"); end; Ada.Text_IO.Flush (Ada.Text_IO.Current_Error); Ada.Text_IO.Set_Error (Ada.Text_IO.Standard_Error); Ada.Text_IO.Close (File); Util.Files.Read_File (Path, Content); Util.Tests.Assert_Matches (T, ".*WARN MESSAGE!", Content, "Invalid console log (WARN)"); Util.Tests.Assert_Matches (T, ".*This is the error test message", Content, "Invalid console log (ERROR)"); exception when others => Ada.Text_IO.Set_Error (Ada.Text_IO.Standard_Error); raise; end Test_Console_Appender; procedure Test_Missing_Config (T : in out Test) is L : constant Loggers.Logger := Loggers.Create ("util.log.test.debug"); begin Util.Log.Loggers.Initialize ("plop"); L.Info ("An info message"); L.Debug ("A debug message on logger 'L'"); end Test_Missing_Config; procedure Test_Log_Traceback (T : in out Test) is Path : constant String := Util.Tests.Get_Test_Path ("test-traceback.log"); Props : Util.Properties.Manager; Content : Ada.Strings.Unbounded.Unbounded_String; begin Props.Set ("log4j.appender.test", "File"); Props.Set ("log4j.appender.test.File", Path); Props.Set ("log4j.appender.test.append", "false"); Props.Set ("log4j.appender.test.immediateFlush", "true"); Props.Set ("log4j.rootCategory", "DEBUG,test"); Util.Log.Loggers.Initialize (Props); declare L : constant Loggers.Logger := Loggers.Create ("util.log.test.file"); begin L.Error ("This is the error test message"); raise Constraint_Error with "Test"; exception when E : others => L.Error ("Something wrong", E, True); end; Props.Set ("log4j.rootCategory", "DEBUG,console"); Props.Set ("log4j.appender.console", "Console"); Util.Log.Loggers.Initialize (Props); Util.Files.Read_File (Path, Content); Util.Tests.Assert_Matches (T, ".*Something wrong: Exception CONSTRAINT_ERROR:", Content, "Invalid console log (ERROR)"); end Test_Log_Traceback; package Caller is new Util.Test_Caller (Test, "Log"); procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is begin Caller.Add_Test (Suite, "Test Util.Log.Loggers.Info", Test_Log'Access); Caller.Add_Test (Suite, "Test Util.Log.Loggers.Debug", Test_Debug'Access); Caller.Add_Test (Suite, "Test Util.Log.Loggers.Set_Level", Test_Log'Access); Caller.Add_Test (Suite, "Test Util.Log.Loggers.Error", Test_Log_Traceback'Access); Caller.Add_Test (Suite, "Test Util.Log.Loggers.Initialize", Test_Missing_Config'Access); Caller.Add_Test (Suite, "Test Util.Log.Appenders.File_Appender", Test_File_Appender'Access); Caller.Add_Test (Suite, "Test Util.Log.Appenders.File_Appender (append)", Test_File_Appender_Modes'Access); Caller.Add_Test (Suite, "Test Util.Log.Appenders.List_Appender", Test_List_Appender'Access); Caller.Add_Test (Suite, "Test Util.Log.Appenders.Console", Test_Console_Appender'Access); Caller.Add_Test (Suite, "Test Util.Log.Loggers.Log (Perf)", Test_Log_Perf'Access); end Add_Tests; end Util.Log.Tests;
----------------------------------------------------------------------- -- log.tests -- Unit tests for loggers -- Copyright (C) 2009, 2010, 2011, 2013, 2015, 2018, 2021 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Strings.Fixed; with Ada.Directories; with Ada.Text_IO; with Ada.Strings.Unbounded; with Util.Test_Caller; with Util.Log; with Util.Log.Loggers; with Util.Files; with Util.Properties; with Util.Measures; package body Util.Log.Tests is Log : constant Loggers.Logger := Loggers.Create ("util.log.test"); procedure Test_Log (T : in out Test) is L : Loggers.Logger := Loggers.Create ("util.log.test.debug"); begin L.Set_Level (DEBUG_LEVEL); Log.Info ("My log message"); Log.Error ("My error message"); Log.Debug ("A debug message Not printed"); L.Info ("An info message"); L.Info ("A {0} {1} {2} {3}", "info", "message", "not", "printed"); L.Debug ("A debug message on logger 'L'"); Util.Tests.Assert_Equals (T, "DEBUG", L.Get_Level_Name, "Get_Level_Name function is invalid"); end Test_Log; procedure Test_Debug (T : in out Test) is L : Loggers.Logger := Loggers.Create ("util.log.test.debug"); C : Ada.Strings.Unbounded.Unbounded_String; begin L.Set_Level (DEBUG_LEVEL); L.Info ("My log message"); L.Error ("My error message"); L.Debug ("A {0} {1} {2} {3}", "debug", "message", "not", "printed"); L.Debug ("A {0} {1} {2} {3}", C, "message", "printed"); L.Info ("An info message"); L.Debug ("A debug message on logger 'L'"); Util.Tests.Assert_Equals (T, "DEBUG", L.Get_Level_Name, "Get_Level_Name function is invalid"); end Test_Debug; -- Test configuration and creation of file procedure Test_File_Appender (T : in out Test) is Path : constant String := Util.Tests.Get_Test_Path ("test.log"); Props : Util.Properties.Manager; begin Props.Set ("log4j.appender.test", "File"); Props.Set ("log4j.appender.test.File", Path); Props.Set ("log4j.logger.util.log.test.file", "DEBUG,test"); Util.Log.Loggers.Initialize (Props); declare L : constant Loggers.Logger := Loggers.Create ("util.log.test.file"); begin L.Debug ("Writing a debug message"); L.Debug ("{0}: {1}", "Parameter", "Value"); end; T.Assert (Ada.Directories.Exists (Path), "Log file " & Path & " not found"); end Test_File_Appender; procedure Test_Log_Perf (T : in out Test) is Path : constant String := Util.Tests.Get_Test_Path ("test_perf.log"); Props : Util.Properties.Manager; begin Props.Set ("log4j.appender.test", "File"); Props.Set ("log4j.appender.test.File", Path); Props.Set ("log4j.logger.util.log.test.perf", "DEBUG,test"); Util.Log.Loggers.Initialize (Props); for I in 1 .. 1000 loop declare S : Util.Measures.Stamp; begin Util.Measures.Report (S, "Util.Measures.Report", 1000); end; end loop; declare L : Loggers.Logger := Loggers.Create ("util.log.test.perf"); S : Util.Measures.Stamp; begin L.Set_Level (DEBUG_LEVEL); for I in 1 .. 1000 loop L.Info ("My log message: {0}: {1}", "A message", "A second parameter"); end loop; Util.Measures.Report (S, "Log.Info message (output)", 1000); L.Set_Level (INFO_LEVEL); for I in 1 .. 10_000 loop L.Debug ("My log message: {0}: {1}", "A message", "A second parameter"); end loop; Util.Measures.Report (S, "Log.Debug message (no output)", 10_000); end; T.Assert (Ada.Directories.Exists (Path), "Log file " & Path & " not found"); end Test_Log_Perf; -- ------------------------------ -- Test appending the log on several log files -- ------------------------------ procedure Test_List_Appender (T : in out Test) is use Ada.Strings; use Ada.Directories; Props : Util.Properties.Manager; begin for I in 1 .. 10 loop declare Id : constant String := Fixed.Trim (Integer'Image (I), Both); Path : constant String := Util.Tests.Get_Test_Path ("test" & Id & ".log"); Name : constant String := "log4j.appender.test" & Id; begin Props.Set (Name, "File"); Props.Set (Name & ".File", Path); Props.Set (Name & ".layout", "date-level-message"); if I > 5 then Props.Set (Name & ".level", "INFO"); end if; end; end loop; Props.Set ("log4j.rootCategory", "DEBUG, test.log"); Props.Set ("log4j.appender.test.log.File", Util.Tests.Get_Test_Path ("test-default.log")); Props.Set ("log4j.logger.util.log.test.file", "DEBUG,test4,test1 , test2,test3, test4, test5 , test6 , test7,test8,"); Util.Log.Loggers.Initialize (Props); declare L : constant Loggers.Logger := Loggers.Create ("util.log.test.file"); begin L.Debug ("Writing a debug message"); L.Debug ("{0}: {1}", "Parameter", "Value"); L.Debug ("Done"); end; -- Check that we have non empty log files (up to test8.log). for I in 1 .. 8 loop declare Id : constant String := Fixed.Trim (Integer'Image (I), Both); Path : constant String := Util.Tests.Get_Test_Path ("test" & Id & ".log"); begin T.Assert (Ada.Directories.Exists (Path), "Log file " & Path & " not found"); if I > 5 then T.Assert (Ada.Directories.Size (Path) < 100, "Log file " & Path & " should be empty"); else T.Assert (Ada.Directories.Size (Path) > 100, "Log file " & Path & " is empty"); end if; end; end loop; end Test_List_Appender; -- ------------------------------ -- Test file appender with different modes. -- ------------------------------ procedure Test_File_Appender_Modes (T : in out Test) is use Ada.Directories; Append_Path : constant String := Util.Tests.Get_Test_Path ("test-append.log"); Append2_Path : constant String := Util.Tests.Get_Test_Path ("test-append2.log"); Global_Path : constant String := Util.Tests.Get_Test_Path ("test-append-global.log"); Props : Util.Properties.Manager; begin Props.Set ("log4j.appender.test", "File"); Props.Set ("log4j.appender.test.File", Append_Path); Props.Set ("log4j.appender.test.append", "true"); Props.Set ("log4j.appender.test.immediateFlush", "true"); Props.Set ("log4j.appender.test_global", "File"); Props.Set ("log4j.appender.test_global.File", Global_Path); Props.Set ("log4j.appender.test_global.append", "false"); Props.Set ("log4j.appender.test_global.immediateFlush", "false"); Props.Set ("log4j.logger.util.log.test.file", "DEBUG"); Props.Set ("log4j.rootCategory", "DEBUG,test_global,test"); Util.Log.Loggers.Initialize (Props); declare L : constant Loggers.Logger := Loggers.Create ("util.log.test.file"); begin L.Debug ("Writing a debug message"); L.Debug ("{0}: {1}", "Parameter", "Value"); L.Debug ("Done"); L.Error ("This is the error test message"); end; Props.Set ("log4j.appender.test_append", "File"); Props.Set ("log4j.appender.test_append.File", Append2_Path); Props.Set ("log4j.appender.test_append.append", "true"); Props.Set ("log4j.appender.test_append.immediateFlush", "true"); Props.Set ("log4j.logger.util.log.test2.file", "DEBUG,test_append,test_global"); Util.Log.Loggers.Initialize (Props); declare L1 : constant Loggers.Logger := Loggers.Create ("util.log.test.file"); L2 : constant Loggers.Logger := Loggers.Create ("util.log.test2.file"); begin L1.Info ("L1-1 Writing a info message"); L2.Info ("L2-2 {0}: {1}", "Parameter", "Value"); L1.Info ("L1-3 Done"); L2.Error ("L2-4 This is the error test2 message"); end; Props.Set ("log4j.appender.test_append.append", "plop"); Props.Set ("log4j.appender.test_append.immediateFlush", "falsex"); Props.Set ("log4j.rootCategory", "DEBUG, test.log"); Util.Log.Loggers.Initialize (Props); T.Assert (Ada.Directories.Size (Append_Path) > 100, "Log file test-append.log is empty"); T.Assert (Ada.Directories.Size (Append2_Path) > 100, "Log file test-append2.log is empty"); T.Assert (Ada.Directories.Size (Global_Path) > 100, "Log file test-append.log is empty"); end Test_File_Appender_Modes; -- ------------------------------ -- Test file appender with different modes. -- ------------------------------ procedure Test_Console_Appender (T : in out Test) is Path : constant String := Util.Tests.Get_Test_Path ("test_err.log"); Props : Util.Properties.Manager; File : Ada.Text_IO.File_Type; Content : Ada.Strings.Unbounded.Unbounded_String; begin Ada.Text_IO.Create (File, Ada.Text_IO.Out_File, Path); Ada.Text_IO.Set_Error (File); Props.Set ("log4j.appender.test_console", "Console"); Props.Set ("log4j.appender.test_console.stderr", "true"); Props.Set ("log4j.appender.test_console.level", "WARN"); Props.Set ("log4j.rootCategory", "INFO,test_console"); Util.Log.Loggers.Initialize (Props); declare L : constant Loggers.Logger := Loggers.Create ("util.log.test.file"); begin L.Debug ("Writing a debug message"); L.Debug ("{0}: {1}", "Parameter", "Value"); L.Debug ("Done"); L.Info ("INFO MESSAGE!"); L.Warn ("WARN MESSAGE!"); L.Error ("This {0} {1} {2} test message", "is", "the", "error"); end; Ada.Text_IO.Flush (Ada.Text_IO.Current_Error); Ada.Text_IO.Set_Error (Ada.Text_IO.Standard_Error); Ada.Text_IO.Close (File); Util.Files.Read_File (Path, Content); Util.Tests.Assert_Matches (T, ".*WARN MESSAGE!", Content, "Invalid console log (WARN)"); Util.Tests.Assert_Matches (T, ".*This is the error test message", Content, "Invalid console log (ERROR)"); exception when others => Ada.Text_IO.Set_Error (Ada.Text_IO.Standard_Error); raise; end Test_Console_Appender; procedure Test_Missing_Config (T : in out Test) is L : constant Loggers.Logger := Loggers.Create ("util.log.test.debug"); begin Util.Log.Loggers.Initialize ("plop"); L.Info ("An info message"); L.Debug ("A debug message on logger 'L'"); end Test_Missing_Config; procedure Test_Log_Traceback (T : in out Test) is Path : constant String := Util.Tests.Get_Test_Path ("test-traceback.log"); Props : Util.Properties.Manager; Content : Ada.Strings.Unbounded.Unbounded_String; begin Props.Set ("log4j.appender.test", "File"); Props.Set ("log4j.appender.test.File", Path); Props.Set ("log4j.appender.test.append", "false"); Props.Set ("log4j.appender.test.immediateFlush", "true"); Props.Set ("log4j.rootCategory", "DEBUG,test"); Util.Log.Loggers.Initialize (Props); declare L : constant Loggers.Logger := Loggers.Create ("util.log.test.file"); begin L.Error ("This is the error test message"); raise Constraint_Error with "Test"; exception when E : others => L.Error ("Something wrong", E, True); end; Props.Set ("log4j.rootCategory", "DEBUG,console"); Props.Set ("log4j.appender.console", "Console"); Util.Log.Loggers.Initialize (Props); Util.Files.Read_File (Path, Content); Util.Tests.Assert_Matches (T, ".*Something wrong: Exception CONSTRAINT_ERROR:", Content, "Invalid console log (ERROR)"); end Test_Log_Traceback; package Caller is new Util.Test_Caller (Test, "Log"); procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is begin Caller.Add_Test (Suite, "Test Util.Log.Loggers.Info", Test_Log'Access); Caller.Add_Test (Suite, "Test Util.Log.Loggers.Debug", Test_Debug'Access); Caller.Add_Test (Suite, "Test Util.Log.Loggers.Set_Level", Test_Log'Access); Caller.Add_Test (Suite, "Test Util.Log.Loggers.Error", Test_Log_Traceback'Access); Caller.Add_Test (Suite, "Test Util.Log.Loggers.Initialize", Test_Missing_Config'Access); Caller.Add_Test (Suite, "Test Util.Log.Appenders.File_Appender", Test_File_Appender'Access); Caller.Add_Test (Suite, "Test Util.Log.Appenders.File_Appender (append)", Test_File_Appender_Modes'Access); Caller.Add_Test (Suite, "Test Util.Log.Appenders.List_Appender", Test_List_Appender'Access); Caller.Add_Test (Suite, "Test Util.Log.Appenders.Console", Test_Console_Appender'Access); Caller.Add_Test (Suite, "Test Util.Log.Loggers.Log (Perf)", Test_Log_Perf'Access); end Add_Tests; end Util.Log.Tests;
Fix configuration of a unit test
Fix configuration of a unit test
Ada
apache-2.0
stcarrez/ada-util,stcarrez/ada-util
63626699a0e6bb547ee5359117cc20f3ac3e3a55
awa/src/awa-events-configs.adb
awa/src/awa-events-configs.adb
----------------------------------------------------------------------- -- awa-events-configs -- Event configuration -- 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.Serialize.Mappers.Record_Mapper; with EL.Utils; with AWA.Services.Contexts; package body AWA.Events.Configs is use AWA.Events.Queues; -- ------------------------------ -- Set the configuration value identified by <b>Value</b> after having parsed -- the element identified by <b>Field</b>. -- ------------------------------ procedure Set_Member (Into : in out Controller_Config; Field : in Config_Fields; Value : in Util.Beans.Objects.Object) is use Ada.Strings.Unbounded; use Util.Beans.Objects; begin case Field is when FIELD_NAME => Into.Name := Value; when FIELD_TYPE => Into.Queue_Type := Value; when FIELD_QUEUE_NAME => declare Name : constant String := Util.Beans.Objects.To_String (Value); begin Into.Queue := Into.Manager.Find_Queue (Name); end; when FIELD_ACTION => declare Expr : constant String := Util.Beans.Objects.To_String (Value); begin Into.Action := EL.Expressions.Create_Expression (Expr, Into.Context.all); exception when others => raise Util.Serialize.Mappers.Field_Error with "Invalid entity type: " & Expr; end; when FIELD_PROPERTY_NAME => Into.Prop_Name := Value; when FIELD_PROPERTY_VALUE => if Util.Beans.Objects.Is_Null (Into.Prop_Name) then raise Util.Serialize.Mappers.Field_Error with "Missing property name"; end if; -- Add the new property. declare Name : constant String := Util.Beans.Objects.To_String (Into.Prop_Name); Expr : constant String := Util.Beans.Objects.To_String (Value); begin EL.Beans.Add_Parameter (Container => Into.Params, Name => Name, Value => Expr, Context => Into.Context.all); end; Into.Prop_Name := Util.Beans.Objects.Null_Object; when FIELD_ON_EVENT => if Util.Beans.Objects.Is_Null (Into.Name) then raise Util.Serialize.Mappers.Field_Error with "Missing event name"; end if; declare Name : constant String := Util.Beans.Objects.To_String (Into.Name); begin Into.Manager.Add_Action (Event => Name, Queue => Into.Queue, Action => Into.Action, Params => Into.Params); end; Into.Name := Util.Beans.Objects.Null_Object; Into.Queue := AWA.Events.Queues.Null_Queue; Into.Params.Clear; when FIELD_QUEUE => -- Create the queue with the given name and properties and add it to the manager. declare Name : constant String := Util.Beans.Objects.To_String (Into.Name); Kind : constant String := Util.Beans.Objects.To_String (Into.Queue_Type); Queue : constant Queue_Ref := Queues.Create_Queue (Name => Name, Kind => Kind, Props => Into.Params, Context => Into.Context.all); begin Into.Manager.Add_Queue (Queue); end; Into.Name := Util.Beans.Objects.Null_Object; Into.Queue_Type := Util.Beans.Objects.Null_Object; Into.Params.Clear; when FIELD_DISPATCHER_PRIORITY => Into.Priority := To_Integer (EL.Utils.Eval (Value => Value, Context => Into.Context.all)); when FIELD_DISPATCHER_COUNT => Into.Count := To_Integer (EL.Utils.Eval (Value => Value, Context => Into.Context.all)); when FIELD_DISPATCHER_QUEUE => declare Match : constant String := Util.Beans.Objects.To_String (Value); begin if Length (Into.Match) > 0 then Append (Into.Match, ","); end if; Append (Into.Match, Match); end; when FIELD_DISPATCHER => if Into.Count > 0 then Into.Manager.Add_Dispatcher (Match => To_String (Into.Match), Count => Into.Count, Priority => Into.Priority); end if; Into.Match := To_Unbounded_String (""); end case; end Set_Member; package Config_Mapper is new Util.Serialize.Mappers.Record_Mapper (Element_Type => Controller_Config, Element_Type_Access => Controller_Config_Access, Fields => Config_Fields, Set_Member => Set_Member); Mapper : aliased Config_Mapper.Mapper; -- Setup the XML parser to read the <b>queue</b> and <b>on-event</b> description. -- For example: -- -- <queue name="async" type="fifo"> -- <property name="size">254</property> -- </queue> -- -- <on-event name="create-user" queue="async"> -- <action>#{mail.send}</action> -- <property name="user">#{event.name}</property> -- <property name="template">mail/welcome.xhtml</property> -- </on-event> -- -- This defines an event action called when the <b>create-user</b> event is posted. -- The Ada bean <b>mail</b> is created and is populated with the <b>user</b> and -- <b>template</b> properties. The Ada bean action method <b>send</b> is called. package body Reader_Config is begin Reader.Add_Mapping ("module", Mapper'Access); Config.Manager := Manager; Config.Context := Context; Config.Session := AWA.Services.Contexts.Get_Session (AWA.Services.Contexts.Current); Config_Mapper.Set_Context (Reader, Config'Unchecked_Access); end Reader_Config; begin Mapper.Add_Mapping ("queue", FIELD_QUEUE); Mapper.Add_Mapping ("queue/@name", FIELD_NAME); Mapper.Add_Mapping ("queue/@type", FIELD_TYPE); Mapper.Add_Mapping ("queue/property/@name", FIELD_PROPERTY_NAME); Mapper.Add_Mapping ("queue/property", FIELD_PROPERTY_VALUE); Mapper.Add_Mapping ("on-event", FIELD_ON_EVENT); Mapper.Add_Mapping ("on-event/@name", FIELD_NAME); Mapper.Add_Mapping ("on-event/@queue", FIELD_QUEUE_NAME); Mapper.Add_Mapping ("on-event/property/@name", FIELD_PROPERTY_NAME); Mapper.Add_Mapping ("on-event/property", FIELD_PROPERTY_VALUE); Mapper.Add_Mapping ("on-event/action", FIELD_ACTION); Mapper.Add_Mapping ("dispatcher", FIELD_DISPATCHER); Mapper.Add_Mapping ("dispatcher/@name", FIELD_NAME); Mapper.Add_Mapping ("dispatcher/queue/@match", FIELD_DISPATCHER_QUEUE); Mapper.Add_Mapping ("dispatcher/priority", FIELD_DISPATCHER_PRIORITY); Mapper.Add_Mapping ("dispatcher/count", FIELD_DISPATCHER_COUNT); end AWA.Events.Configs;
----------------------------------------------------------------------- -- awa-events-configs -- Event configuration -- Copyright (C) 2012, 2013, 2017 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Serialize.Mappers.Record_Mapper; with EL.Utils; with AWA.Services.Contexts; package body AWA.Events.Configs is use AWA.Events.Queues; -- ------------------------------ -- Set the configuration value identified by <b>Value</b> after having parsed -- the element identified by <b>Field</b>. -- ------------------------------ procedure Set_Member (Into : in out Controller_Config; Field : in Config_Fields; Value : in Util.Beans.Objects.Object) is use Ada.Strings.Unbounded; use Util.Beans.Objects; begin case Field is when FIELD_NAME => Into.Name := Value; when FIELD_TYPE => Into.Queue_Type := Value; when FIELD_QUEUE_NAME => declare Name : constant String := Util.Beans.Objects.To_String (Value); begin Into.Queue := Into.Manager.Find_Queue (Name); end; when FIELD_ACTION => declare Expr : constant String := Util.Beans.Objects.To_String (Value); begin Into.Action := EL.Expressions.Create_Expression (Expr, Into.Context.all); exception when others => raise Util.Serialize.Mappers.Field_Error with "Invalid entity type: " & Expr; end; when FIELD_PROPERTY_NAME => Into.Prop_Name := Value; when FIELD_PROPERTY_VALUE => if Util.Beans.Objects.Is_Null (Into.Prop_Name) then raise Util.Serialize.Mappers.Field_Error with "Missing property name"; end if; -- Add the new property. declare Name : constant String := Util.Beans.Objects.To_String (Into.Prop_Name); Expr : constant String := Util.Beans.Objects.To_String (Value); begin EL.Beans.Add_Parameter (Container => Into.Params, Name => Name, Value => Expr, Context => Into.Context.all); end; Into.Prop_Name := Util.Beans.Objects.Null_Object; when FIELD_ON_EVENT => if Util.Beans.Objects.Is_Null (Into.Name) then raise Util.Serialize.Mappers.Field_Error with "Missing event name"; end if; declare Name : constant String := Util.Beans.Objects.To_String (Into.Name); begin Into.Manager.Add_Action (Event => Name, Queue => Into.Queue, Action => Into.Action, Params => Into.Params); end; Into.Name := Util.Beans.Objects.Null_Object; Into.Queue := AWA.Events.Queues.Null_Queue; Into.Params.Clear; when FIELD_QUEUE => -- Create the queue with the given name and properties and add it to the manager. declare Name : constant String := Util.Beans.Objects.To_String (Into.Name); Kind : constant String := Util.Beans.Objects.To_String (Into.Queue_Type); Queue : constant Queue_Ref := Queues.Create_Queue (Name => Name, Kind => Kind, Props => Into.Params, Context => Into.Context.all); begin Into.Manager.Add_Queue (Queue); end; Into.Name := Util.Beans.Objects.Null_Object; Into.Queue_Type := Util.Beans.Objects.Null_Object; Into.Params.Clear; when FIELD_DISPATCHER_PRIORITY => Into.Priority := To_Integer (EL.Utils.Eval (Value => Value, Context => Into.Context.all)); when FIELD_DISPATCHER_COUNT => Into.Count := To_Integer (EL.Utils.Eval (Value => Value, Context => Into.Context.all)); when FIELD_DISPATCHER_QUEUE => declare Match : constant String := Util.Beans.Objects.To_String (Value); begin if Length (Into.Match) > 0 then Append (Into.Match, ","); end if; Append (Into.Match, Match); end; when FIELD_DISPATCHER => if Into.Count > 0 then Into.Manager.Add_Dispatcher (Match => To_String (Into.Match), Count => Into.Count, Priority => Into.Priority); end if; Into.Match := To_Unbounded_String (""); end case; end Set_Member; package Config_Mapper is new Util.Serialize.Mappers.Record_Mapper (Element_Type => Controller_Config, Element_Type_Access => Controller_Config_Access, Fields => Config_Fields, Set_Member => Set_Member); Event_Mapper : aliased Config_Mapper.Mapper; -- Setup the XML parser to read the <b>queue</b> and <b>on-event</b> description. -- For example: -- -- <queue name="async" type="fifo"> -- <property name="size">254</property> -- </queue> -- -- <on-event name="create-user" queue="async"> -- <action>#{mail.send}</action> -- <property name="user">#{event.name}</property> -- <property name="template">mail/welcome.xhtml</property> -- </on-event> -- -- This defines an event action called when the <b>create-user</b> event is posted. -- The Ada bean <b>mail</b> is created and is populated with the <b>user</b> and -- <b>template</b> properties. The Ada bean action method <b>send</b> is called. package body Reader_Config is begin Mapper.Add_Mapping ("module", Event_Mapper'Access); Config.Manager := Manager; Config.Context := Context; Config.Session := AWA.Services.Contexts.Get_Session (AWA.Services.Contexts.Current); Config_Mapper.Set_Context (Mapper, Config'Unchecked_Access); end Reader_Config; begin Event_Mapper.Add_Mapping ("queue", FIELD_QUEUE); Event_Mapper.Add_Mapping ("queue/@name", FIELD_NAME); Event_Mapper.Add_Mapping ("queue/@type", FIELD_TYPE); Event_Mapper.Add_Mapping ("queue/property/@name", FIELD_PROPERTY_NAME); Event_Mapper.Add_Mapping ("queue/property", FIELD_PROPERTY_VALUE); Event_Mapper.Add_Mapping ("on-event", FIELD_ON_EVENT); Event_Mapper.Add_Mapping ("on-event/@name", FIELD_NAME); Event_Mapper.Add_Mapping ("on-event/@queue", FIELD_QUEUE_NAME); Event_Mapper.Add_Mapping ("on-event/property/@name", FIELD_PROPERTY_NAME); Event_Mapper.Add_Mapping ("on-event/property", FIELD_PROPERTY_VALUE); Event_Mapper.Add_Mapping ("on-event/action", FIELD_ACTION); Event_Mapper.Add_Mapping ("dispatcher", FIELD_DISPATCHER); Event_Mapper.Add_Mapping ("dispatcher/@name", FIELD_NAME); Event_Mapper.Add_Mapping ("dispatcher/queue/@match", FIELD_DISPATCHER_QUEUE); Event_Mapper.Add_Mapping ("dispatcher/priority", FIELD_DISPATCHER_PRIORITY); Event_Mapper.Add_Mapping ("dispatcher/count", FIELD_DISPATCHER_COUNT); end AWA.Events.Configs;
Update the Prepare_Config to use the new parser/mapper interface
Update the Prepare_Config to use the new parser/mapper interface
Ada
apache-2.0
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
0dadc6f2a711964d3c201a313812f65229f0acbb
src/ado.adb
src/ado.adb
----------------------------------------------------------------------- -- ADO Databases -- Database Objects -- Copyright (C) 2012 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Directories; with Ada.Streams.Stream_IO; with Util.Streams.Files; package body ADO is use Util.Refs; use Ada.Streams; -- ------------------------------ -- Create a blob with an allocated buffer of <b>Size</b> bytes. -- ------------------------------ function Create_Blob (Size : in Natural) return Blob_Ref is B : constant Blob_Access := new Blob '(Ref_Entity with Len => Stream_Element_Offset (Size), others => <>); begin return Blob_References.Create (B); end Create_Blob; -- ------------------------------ -- Create a blob initialized with the given data buffer. -- ------------------------------ function Create_Blob (Data : in Ada.Streams.Stream_Element_Array) return Blob_Ref is B : constant Blob_Access := new Blob '(Ref_Entity with Len => Data'Length, Data => Data); begin return Blob_References.Create (B); end Create_Blob; -- ------------------------------ -- 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 is Size : constant Stream_Element_Offset := Stream_Element_Offset (Ada.Directories.Size (Path)); File : Util.Streams.Files.File_Stream; Last : Stream_Element_Offset; begin File.Open (Name => Path, Mode => Ada.Streams.Stream_IO.In_File); declare B : constant Blob_Access := new Blob '(Ref_Entity with Len => Size, others => <>); begin File.Read (Into => B.Data, Last => Last); File.Close; return Blob_References.Create (B); end; end Create_Blob; Null_Blob_Instance : Blob_Ref; -- ------------------------------ -- Return a null blob. -- ------------------------------ function Null_Blob return Blob_Ref is begin return Null_Blob_Instance; end Null_Blob; end ADO;
----------------------------------------------------------------------- -- ADO Databases -- Database Objects -- 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 Ada.Directories; with Ada.Streams.Stream_IO; with Util.Streams.Files; package body ADO is use Util.Refs; use Ada.Streams; -- ------------------------------ -- Create a blob with an allocated buffer of <b>Size</b> bytes. -- ------------------------------ function Create_Blob (Size : in Natural) return Blob_Ref is B : constant Blob_Access := new Blob '(Ref_Entity with Len => Stream_Element_Offset (Size), others => <>); begin return Blob_References.Create (B); end Create_Blob; -- ------------------------------ -- Create a blob initialized with the given data buffer. -- ------------------------------ function Create_Blob (Data : in Ada.Streams.Stream_Element_Array) return Blob_Ref is B : constant Blob_Access := new Blob '(Ref_Entity with Len => Data'Length, Data => Data); begin return Blob_References.Create (B); end Create_Blob; -- ------------------------------ -- 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 is Size : constant Stream_Element_Offset := Stream_Element_Offset (Ada.Directories.Size (Path)); File : Util.Streams.Files.File_Stream; Last : Stream_Element_Offset; begin File.Open (Name => Path, Mode => Ada.Streams.Stream_IO.In_File); declare B : constant Blob_Access := new Blob '(Ref_Entity with Len => Size, others => <>); begin File.Read (Into => B.Data, Last => Last); File.Close; return Blob_References.Create (B); end; end Create_Blob; Null_Blob_Instance : Blob_Ref; -- ------------------------------ -- Return a null blob. -- ------------------------------ function Null_Blob return Blob_Ref is begin return Null_Blob_Instance; end Null_Blob; -- ------------------------------ -- Return True if the two nullable times are identical (both null or both same time). -- ------------------------------ function "=" (Left, Right : in Nullable_Time) return Boolean is use type Ada.Calendar.Time; begin if Left.Is_Null /= Right.Is_Null then return False; elsif Left.Is_Null then return True; else return Left.Value = Right.Value; end if; end "="; end ADO;
Implement the "=" function operator to compare a nullable_time on the is_null first and on the value when they are not null only
Implement the "=" function operator to compare a nullable_time on the is_null first and on the value when they are not null only
Ada
apache-2.0
stcarrez/ada-ado
ca36c6489578ef9dfe65dd10cd15562e053514c2
matp/src/frames/mat-frames-targets.adb
matp/src/frames/mat-frames-targets.adb
----------------------------------------------------------------------- -- mat-frames-targets - Representation of stack frames -- Copyright (C) 2015 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- package body MAT.Frames.Targets is -- ------------------------------ -- Insert in the frame tree the new stack frame represented by <tt>Pc</tt>. -- If the frame is already known, the frame reference counter is incremented. -- The frame represented by <tt>Pc</tt> is returned in <tt>Result</tt>. -- ------------------------------ procedure Insert (Frame : in out Target_Frames; Pc : in Frame_Table; Result : out Frame_Type) is begin Frame.Frames.Insert (Pc, Result); end Insert; -- ------------------------------ -- Get the number of different stack frames which have been registered. -- ------------------------------ function Get_Frame_Count (Frame : in Target_Frames) return Natural is begin return Frame.Frames.Get_Frame_Count; end Get_Frame_Count; protected body Frames_Type is -- ------------------------------ -- Insert in the frame tree the new stack frame represented by <tt>Pc</tt>. -- If the frame is already known, the frame reference counter is incremented. -- The frame represented by <tt>Pc</tt> is returned in <tt>Result</tt>. -- ------------------------------ procedure Insert (Pc : in Frame_Table; Result : out Frame_Type) is begin MAT.Frames.Insert (Root, Pc, Result); end Insert; -- ------------------------------ -- Clear and destroy all the frame instances. -- ------------------------------ procedure Clear is begin Destroy (Root); end Clear; end Frames_Type; -- ------------------------------ -- Release all the stack frames. -- ------------------------------ overriding procedure Finalize (Frames : in out Target_Frames) is begin Frames.Frames.Clear; end Finalize; end MAT.Frames.Targets;
----------------------------------------------------------------------- -- mat-frames-targets - Representation of stack frames -- Copyright (C) 2015 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- package body MAT.Frames.Targets is -- ------------------------------ -- Insert in the frame tree the new stack frame represented by <tt>Pc</tt>. -- If the frame is already known, the frame reference counter is incremented. -- The frame represented by <tt>Pc</tt> is returned in <tt>Result</tt>. -- ------------------------------ procedure Insert (Frame : in out Target_Frames; Pc : in Frame_Table; Result : out Frame_Type) is begin Frame.Frames.Insert (Pc, Result); end Insert; -- ------------------------------ -- Get the number of different stack frames which have been registered. -- ------------------------------ function Get_Frame_Count (Frame : in Target_Frames) return Natural is begin return Frame.Frames.Get_Frame_Count; end Get_Frame_Count; protected body Frames_Type is -- ------------------------------ -- Get the number of different stack frames which have been registered. -- ------------------------------ function Get_Frame_Count return Natural is begin return Root.Used; end Get_Frame_Count; -- ------------------------------ -- Insert in the frame tree the new stack frame represented by <tt>Pc</tt>. -- If the frame is already known, the frame reference counter is incremented. -- The frame represented by <tt>Pc</tt> is returned in <tt>Result</tt>. -- ------------------------------ procedure Insert (Pc : in Frame_Table; Result : out Frame_Type) is begin MAT.Frames.Insert (Root, Pc, Result); end Insert; -- ------------------------------ -- Clear and destroy all the frame instances. -- ------------------------------ procedure Clear is begin Destroy (Root); end Clear; end Frames_Type; -- ------------------------------ -- Release all the stack frames. -- ------------------------------ overriding procedure Finalize (Frames : in out Target_Frames) is begin Frames.Frames.Clear; end Finalize; end MAT.Frames.Targets;
Implement the protected operation Get_Frame_Count
Implement the protected operation Get_Frame_Count
Ada
apache-2.0
stcarrez/mat,stcarrez/mat,stcarrez/mat
d3778ab3b7a3525522edf81055531ab39784b6a3
mat/src/mat-readers-streams-sockets.ads
mat/src/mat-readers-streams-sockets.ads
----------------------------------------------------------------------- -- mat-readers-sockets -- Reader for TCP/IP sockets -- Copyright (C) 2014 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Finalization; with Util.Streams.Sockets; with GNAT.Sockets; package MAT.Readers.Streams.Sockets is type Socket_Listener_Type is new Ada.Finalization.Limited_Controlled with private; -- Initialize the socket listener. overriding procedure Initialize (Listener : in out Socket_Listener_Type); -- Destroy the socket listener. overriding procedure Finalize (Listener : in out Socket_Listener_Type); -- Open the socket to accept connections and start the listener task. procedure Start (Listener : in out Socket_Listener_Type; Address : in GNAT.Sockets.Sock_Addr_Type); -- Stop the listener socket. procedure Stop (Listener : in out Socket_Listener_Type); -- Create a target instance for the new client. procedure Create_Target (Listener : in out Socket_Listener_Type; Client : in GNAT.Sockets.Socket_Type; Address : in GNAT.Sockets.Sock_Addr_Type); type Socket_Reader_Type is new MAT.Readers.Streams.Stream_Reader_Type with private; type Socket_Reader_Type_Access is access all Socket_Reader_Type'Class; -- Open the socket to accept connections. procedure Open (Reader : in out Socket_Reader_Type; Address : in GNAT.Sockets.Sock_Addr_Type); procedure Close (Reader : in out Socket_Reader_Type); private type Socket_Listener_Type_Access is access all Socket_Listener_Type; task type Socket_Listener_Task is entry Start (Listener : in Socket_Listener_Type_Access; Address : in GNAT.Sockets.Sock_Addr_Type); end Socket_Listener_Task; task type Socket_Reader_Task is entry Start (Reader : in Socket_Reader_Type_Access; Client : in GNAT.Sockets.Socket_Type); end Socket_Reader_Task; type Socket_Reader_Type is new MAT.Readers.Streams.Stream_Reader_Type with record Socket : aliased Util.Streams.Sockets.Socket_Stream; Server : Socket_Reader_Task; Stop : Boolean := False; end record; type Socket_Listener_Type is new Ada.Finalization.Limited_Controlled with record Accept_Selector : aliased GNAT.Sockets.Selector_Type; Listener : Socket_Listener_Task; end record; end MAT.Readers.Streams.Sockets;
----------------------------------------------------------------------- -- mat-readers-sockets -- Reader for TCP/IP sockets -- Copyright (C) 2014 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Finalization; with Util.Streams.Sockets; with GNAT.Sockets; package MAT.Readers.Streams.Sockets is type Socket_Listener_Type is new Ada.Finalization.Limited_Controlled with private; -- Initialize the socket listener. overriding procedure Initialize (Listener : in out Socket_Listener_Type); -- Destroy the socket listener. overriding procedure Finalize (Listener : in out Socket_Listener_Type); -- Open the socket to accept connections and start the listener task. procedure Start (Listener : in out Socket_Listener_Type; Address : in GNAT.Sockets.Sock_Addr_Type); -- Stop the listener socket. procedure Stop (Listener : in out Socket_Listener_Type); -- Create a target instance for the new client. procedure Create_Target (Listener : in out Socket_Listener_Type; Client : in GNAT.Sockets.Socket_Type; Address : in GNAT.Sockets.Sock_Addr_Type); type Socket_Reader_Type is new MAT.Readers.Streams.Stream_Reader_Type with private; type Socket_Reader_Type_Access is access all Socket_Reader_Type'Class; procedure Close (Reader : in out Socket_Reader_Type); private type Socket_Listener_Type_Access is access all Socket_Listener_Type; task type Socket_Listener_Task is entry Start (Listener : in Socket_Listener_Type_Access; Address : in GNAT.Sockets.Sock_Addr_Type); end Socket_Listener_Task; task type Socket_Reader_Task is entry Start (Reader : in Socket_Reader_Type_Access; Client : in GNAT.Sockets.Socket_Type); end Socket_Reader_Task; type Socket_Reader_Type is new MAT.Readers.Streams.Stream_Reader_Type with record Socket : aliased Util.Streams.Sockets.Socket_Stream; Server : Socket_Reader_Task; Stop : Boolean := False; end record; type Socket_Listener_Type is new Ada.Finalization.Limited_Controlled with record Accept_Selector : aliased GNAT.Sockets.Selector_Type; Listener : Socket_Listener_Task; end record; end MAT.Readers.Streams.Sockets;
Remove the Open procedure
Remove the Open procedure
Ada
apache-2.0
stcarrez/mat,stcarrez/mat,stcarrez/mat
1c0f52d972259fc3381415425c14ee1fbcb4e41d
UNIT_TESTS/test.adb
UNIT_TESTS/test.adb
with Ada.Strings.Fixed; package body Test is package Text_IO renames Ada.Text_IO; package Result_IO is new Ada.Text_IO.Enumeration_IO (Result_t); package Fixed_Strings renames Ada.Strings.Fixed; package Strings renames Ada.Strings; use type UB_Strings.Unbounded_String; -- -- Check -- procedure Check (Test_Context : in Context_t; Test : in Test_t; Condition : in Boolean; Statement : in String := "") is Result : Valid_Result_t; begin if Condition then Result := Pass; else Result := Fail; end if; Satisfy (Test_Context => Test_Context, Test => Test, Result => Result, Statement => Statement); end Check; -- -- Check_Program -- procedure Check_Program (Test_Context : in Context_t; Base : in UB_Strings.Unbounded_String) is Want_Program : UB_Strings.Unbounded_String; Path : UB_Strings.Unbounded_String; File : Text_IO.File_Type; begin UB_Strings.Append (Path, Test_Context.Test_DB); UB_Strings.Append (Path, Base); UB_Strings.Append (Path, "/program"); Text_IO.Open (File => File, Mode => Text_IO.In_File, Name => UB_Strings.To_String (Path)); Want_Program := UB_Strings.To_Unbounded_String (Text_IO.Get_Line (File)); if Want_Program /= Test_Context.Program then raise Program_Error with "program does not match test database"; end if; end Check_Program; -- -- Initialize -- procedure Initialize (Test_Context : out Context_t; Program : in String; Test_DB : in String; Test_Results : in String) is begin Test_Context.Program := UB_Strings.To_Unbounded_String (Program); Test_Context.Test_DB := UB_Strings.To_Unbounded_String (Test_DB); Test_Context.Test_Results := UB_Strings.To_Unbounded_String (Test_Results); Text_IO.Create (File => Test_Context.Output_File, Name => Program & ".log_out", Mode => Text_IO.Out_File); Text_IO.Create (File => Test_Context.Error_File, Name => Program & ".log_error", Mode => Text_IO.Out_File); Text_IO.Set_Output (Test_Context.Output_File); Text_IO.Set_Error (Test_Context.Error_File); end Initialize; -- -- Satisfy -- procedure Satisfy (Test_Context : in Context_t; Test : in Test_t; Result : in Valid_Result_t; Statement : in String := "") is File : Text_IO.File_Type; Base : UB_Strings.Unbounded_String; Path : UB_Strings.Unbounded_String; begin -- Build path to test entry. UB_Strings.Set_Unbounded_String (Base, ""); UB_Strings.Append (Base, "/tests/"); UB_Strings.Append (Base, Fixed_Strings.Trim (Test_t'Image (Test), Strings.Left)); -- Check the current program is the one that should be satisfying the test. Check_Program (Test_Context, Base); -- Build path to state file. UB_Strings.Set_Unbounded_String (Path, ""); UB_Strings.Append (Path, Test_Context.Test_Results); UB_Strings.Append (Path, Base); UB_Strings.Append (Path, "/statement"); -- Yes, Ada has race conditions built in! Text_IO.Create (File, Name => UB_Strings.To_String (Path)); Text_IO.Put (File, Statement); Text_IO.New_Line (File); Text_IO.Close (File); -- Build path to state file. UB_Strings.Set_Unbounded_String (Path, ""); UB_Strings.Append (Path, Test_Context.Test_Results); UB_Strings.Append (Path, Base); UB_Strings.Append (Path, "/state"); -- Yes, Ada has race conditions built in! Text_IO.Create (File, Name => UB_Strings.To_String (Path)); Result_IO.Put (File, Result); Text_IO.New_Line (File); end Satisfy; end Test;
with Ada.Strings.Fixed; with Ada.Directories; package body Test is package Text_IO renames Ada.Text_IO; package Result_IO is new Ada.Text_IO.Enumeration_IO (Result_t); package Fixed_Strings renames Ada.Strings.Fixed; package Strings renames Ada.Strings; package Directories renames Ada.Directories; use type UB_Strings.Unbounded_String; -- -- Check -- procedure Check (Test_Context : in Context_t; Test : in Test_t; Condition : in Boolean; Statement : in String := "") is Result : Valid_Result_t; begin if Condition then Result := Pass; else Result := Fail; end if; Satisfy (Test_Context => Test_Context, Test => Test, Result => Result, Statement => Statement); end Check; -- -- Check_Program -- procedure Check_Program (Test_Context : in Context_t; Base : in UB_Strings.Unbounded_String) is Want_Program : UB_Strings.Unbounded_String; Path : UB_Strings.Unbounded_String; File : Text_IO.File_Type; begin UB_Strings.Append (Path, Test_Context.Test_DB); UB_Strings.Append (Path, Base); UB_Strings.Append (Path, "/program"); Text_IO.Open (File => File, Mode => Text_IO.In_File, Name => UB_Strings.To_String (Path)); Want_Program := UB_Strings.To_Unbounded_String (Text_IO.Get_Line (File)); if Want_Program /= Test_Context.Program then raise Program_Error with "program does not match test database"; end if; end Check_Program; -- -- Initialize -- procedure Initialize (Test_Context : out Context_t; Program : in String; Test_DB : in String; Test_Results : in String) is begin Test_Context.Program := UB_Strings.To_Unbounded_String (Program); Test_Context.Test_DB := UB_Strings.To_Unbounded_String (Test_DB); Test_Context.Test_Results := UB_Strings.To_Unbounded_String (Test_Results); Text_IO.Create (File => Test_Context.Output_File, Name => Program & ".log_out", Mode => Text_IO.Out_File); Text_IO.Create (File => Test_Context.Error_File, Name => Program & ".log_error", Mode => Text_IO.Out_File); Text_IO.Set_Output (Test_Context.Output_File); Text_IO.Set_Error (Test_Context.Error_File); end Initialize; -- -- Satisfy -- procedure Satisfy (Test_Context : in Context_t; Test : in Test_t; Result : in Valid_Result_t; Statement : in String := "") is File : Text_IO.File_Type; Base : UB_Strings.Unbounded_String; Path : UB_Strings.Unbounded_String; begin -- Build path to test entry. UB_Strings.Set_Unbounded_String (Base, ""); UB_Strings.Append (Base, "/tests/"); UB_Strings.Append (Base, Fixed_Strings.Trim (Test_t'Image (Test), Strings.Left)); -- Check database entry exists. UB_Strings.Set_Unbounded_String (Path, ""); UB_Strings.Append (Path, Test_Context.Test_DB); UB_Strings.Append (Path, Base); if Directories.Exists (UB_Strings.To_String (Path)) = False then raise Program_Error with "test " & Fixed_Strings.Trim (Test_t'Image (Test), Strings.Left) & " not defined"; end if; -- Check the current program is the one that should be satisfying the test. Check_Program (Test_Context, Base); -- Build path to state file. UB_Strings.Set_Unbounded_String (Path, ""); UB_Strings.Append (Path, Test_Context.Test_Results); UB_Strings.Append (Path, Base); UB_Strings.Append (Path, "/statement"); -- Yes, Ada has race conditions built in! Text_IO.Create (File, Name => UB_Strings.To_String (Path)); Text_IO.Put (File, Statement); Text_IO.New_Line (File); Text_IO.Close (File); -- Build path to state file. UB_Strings.Set_Unbounded_String (Path, ""); UB_Strings.Append (Path, Test_Context.Test_Results); UB_Strings.Append (Path, Base); UB_Strings.Append (Path, "/state"); -- Yes, Ada has race conditions built in! Text_IO.Create (File, Name => UB_Strings.To_String (Path)); Result_IO.Put (File, Result); Text_IO.New_Line (File); end Satisfy; end Test;
Check test entry in ada code
Check test entry in ada code
Ada
isc
io7m/coreland-openal-ada,io7m/coreland-openal-ada
054f59c4c6524c3663599ac729eb57db45f6fe9a
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; 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;
----------------------------------------------------------------------- -- 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; -- ----------------------- -- Reposition the read/write file offset. -- ----------------------- procedure Seek (Stream : in out Raw_Stream; Pos : in Util.Systems.Types.off_t; Mode : in Util.Systems.Types.Seek_Mode) is Res : Util.Systems.Types.off_t; begin Res := Sys_Lseek (Stream.File, Pos, Mode); if Res < 0 then raise Ada.IO_Exceptions.Device_Error; end if; end Seek; -- ----------------------- -- Flush the stream and release the buffer. -- ----------------------- procedure Finalize (Object : in out Raw_Stream) is begin Close (Object); end Finalize; end Util.Streams.Raw;
Implement the Seek procedure
Implement the Seek procedure
Ada
apache-2.0
stcarrez/ada-util,stcarrez/ada-util
5ab89b912042bd1d7214b9b770ceb17623f259d9
matp/src/mat-consoles.ads
matp/src/mat-consoles.ads
----------------------------------------------------------------------- -- mat-consoles - Console interface -- Copyright (C) 2014, 2015 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Strings.Unbounded; with MAT.Types; package MAT.Consoles is type Field_Type is (F_ADDR, F_SIZE, F_TOTAL_SIZE, F_MIN_SIZE, F_MAX_SIZE, F_MIN_ADDR, F_MAX_ADDR, F_THREAD, F_COUNT, F_FILE_NAME, F_FUNCTION_NAME, F_LINE_NUMBER, F_START_TIME, F_END_TIME, F_MALLOC_COUNT, F_REALLOC_COUNT, F_FREE_COUNT, F_EVENT_RANGE, F_ID, F_OLD_ADDR, F_GROW_SIZE, F_TIME, F_DURATION, F_EVENT, F_MODE, F_FRAME_ID, F_RANGE_ADDR, F_FRAME_ADDR); type Notice_Type is (N_HELP, N_INFO, N_EVENT_ID, N_PID_INFO, N_DURATION, N_PATH_INFO); type Justify_Type is (J_LEFT, -- Justify left |item | J_RIGHT, -- Justify right | item| J_CENTER, -- Justify center | item | J_RIGHT_NO_FILL -- Justify right |item| ); type Console_Type is abstract tagged limited private; type Console_Access is access all Console_Type'Class; -- Report an error message. procedure Error (Console : in out Console_Type; Message : in String) is abstract; -- Report a notice message. procedure Notice (Console : in out Console_Type; Kind : in Notice_Type; Message : in String) is abstract; -- Print the field value for the given field. procedure Print_Field (Console : in out Console_Type; Field : in Field_Type; Value : in String; Justify : in Justify_Type := J_LEFT) is abstract; -- Print the title for the given field. procedure Print_Title (Console : in out Console_Type; Field : in Field_Type; Title : in String) is abstract; -- Start a new title in a report. procedure Start_Title (Console : in out Console_Type) is abstract; -- Finish a new title in a report. procedure End_Title (Console : in out Console_Type) is abstract; -- Start a new row in a report. procedure Start_Row (Console : in out Console_Type) is abstract; -- Finish a new row in a report. procedure End_Row (Console : in out Console_Type) is abstract; -- Print the title for the given field and setup the associated field size. procedure Print_Title (Console : in out Console_Type; Field : in Field_Type; Title : in String; Length : in Positive); -- Format the address and print it for the given field. procedure Print_Field (Console : in out Console_Type; Field : in Field_Type; Addr : in MAT.Types.Target_Addr); -- Format the address range and print it for the given field. procedure Print_Field (Console : in out Console_Type; Field : in Field_Type; From : in MAT.Types.Target_Addr; To : in MAT.Types.Target_Addr); -- Format the size and print it for the given field. procedure Print_Size (Console : in out Console_Type; Field : in Field_Type; Size : in MAT.Types.Target_Size); -- Format the thread information and print it for the given field. procedure Print_Thread (Console : in out Console_Type; Field : in Field_Type; Thread : in MAT.Types.Target_Thread_Ref); -- Format the time tick as a duration and print it for the given field. procedure Print_Duration (Console : in out Console_Type; Field : in Field_Type; Duration : in MAT.Types.Target_Tick_Ref); -- Format the integer and print it for the given field. procedure Print_Field (Console : in out Console_Type; Field : in Field_Type; Value : in Integer; Justify : in Justify_Type := J_LEFT); -- Format the integer and print it for the given field. procedure Print_Field (Console : in out Console_Type; Field : in Field_Type; Value : in Ada.Strings.Unbounded.Unbounded_String; Justify : in Justify_Type := J_LEFT); private type Field_Size_Array is array (Field_Type) of Natural; type Field_List_Array is array (1 .. Field_Type'Pos (Field_Type'Last)) of Field_Type; type Console_Type is abstract tagged limited record Sizes : Field_Size_Array := (others => 1); Cols : Field_Size_Array := (others => 1); Fields : Field_List_Array; Field_Count : Natural := 0; end record; end MAT.Consoles;
----------------------------------------------------------------------- -- mat-consoles - Console interface -- Copyright (C) 2014, 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 MAT.Types; package MAT.Consoles is type Field_Type is (F_ADDR, F_SIZE, F_TOTAL_SIZE, F_MIN_SIZE, F_MAX_SIZE, F_MIN_ADDR, F_MAX_ADDR, F_THREAD, F_COUNT, F_LEVEL, F_FILE_NAME, F_FUNCTION_NAME, F_LINE_NUMBER, F_START_TIME, F_END_TIME, F_MALLOC_COUNT, F_REALLOC_COUNT, F_FREE_COUNT, F_EVENT_RANGE, F_ID, F_OLD_ADDR, F_GROW_SIZE, F_TIME, F_DURATION, F_EVENT, F_MODE, F_FRAME_ID, F_RANGE_ADDR, F_FRAME_ADDR); type Notice_Type is (N_HELP, N_INFO, N_EVENT_ID, N_PID_INFO, N_DURATION, N_PATH_INFO); type Justify_Type is (J_LEFT, -- Justify left |item | J_RIGHT, -- Justify right | item| J_CENTER, -- Justify center | item | J_RIGHT_NO_FILL -- Justify right |item| ); type Console_Type is abstract tagged limited private; type Console_Access is access all Console_Type'Class; -- Report an error message. procedure Error (Console : in out Console_Type; Message : in String) is abstract; -- Report a notice message. procedure Notice (Console : in out Console_Type; Kind : in Notice_Type; Message : in String) is abstract; -- Print the field value for the given field. procedure Print_Field (Console : in out Console_Type; Field : in Field_Type; Value : in String; Justify : in Justify_Type := J_LEFT) is abstract; -- Print the title for the given field. procedure Print_Title (Console : in out Console_Type; Field : in Field_Type; Title : in String) is abstract; -- Start a new title in a report. procedure Start_Title (Console : in out Console_Type) is abstract; -- Finish a new title in a report. procedure End_Title (Console : in out Console_Type) is abstract; -- Start a new row in a report. procedure Start_Row (Console : in out Console_Type) is abstract; -- Finish a new row in a report. procedure End_Row (Console : in out Console_Type) is abstract; -- Print the title for the given field and setup the associated field size. procedure Print_Title (Console : in out Console_Type; Field : in Field_Type; Title : in String; Length : in Positive); -- Format the address and print it for the given field. procedure Print_Field (Console : in out Console_Type; Field : in Field_Type; Addr : in MAT.Types.Target_Addr); -- Format the address range and print it for the given field. procedure Print_Field (Console : in out Console_Type; Field : in Field_Type; From : in MAT.Types.Target_Addr; To : in MAT.Types.Target_Addr); -- Format the size and print it for the given field. procedure Print_Size (Console : in out Console_Type; Field : in Field_Type; Size : in MAT.Types.Target_Size); -- Format the thread information and print it for the given field. procedure Print_Thread (Console : in out Console_Type; Field : in Field_Type; Thread : in MAT.Types.Target_Thread_Ref); -- Format the time tick as a duration and print it for the given field. procedure Print_Duration (Console : in out Console_Type; Field : in Field_Type; Duration : in MAT.Types.Target_Tick_Ref); -- Format the integer and print it for the given field. procedure Print_Field (Console : in out Console_Type; Field : in Field_Type; Value : in Integer; Justify : in Justify_Type := J_LEFT); -- Format the integer and print it for the given field. procedure Print_Field (Console : in out Console_Type; Field : in Field_Type; Value : in Ada.Strings.Unbounded.Unbounded_String; Justify : in Justify_Type := J_LEFT); private type Field_Size_Array is array (Field_Type) of Natural; type Field_List_Array is array (1 .. Field_Type'Pos (Field_Type'Last)) of Field_Type; type Console_Type is abstract tagged limited record Sizes : Field_Size_Array := (others => 1); Cols : Field_Size_Array := (others => 1); Fields : Field_List_Array; Field_Count : Natural := 0; end record; end MAT.Consoles;
Add F_LEVEL
Add F_LEVEL
Ada
apache-2.0
stcarrez/mat,stcarrez/mat,stcarrez/mat
85009007a5077526c7470d8279e831bef82b10fe
awa/plugins/awa-comments/src/awa-comments-modules.adb
awa/plugins/awa-comments/src/awa-comments-modules.adb
----------------------------------------------------------------------- -- awa-comments-module -- Comments module -- Copyright (C) 2011, 2012 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Calendar; with Util.Log.Loggers; with ADO.Sessions; with Security.Permissions; with AWA.Users.Models; with AWA.Permissions; with AWA.Modules.Beans; with AWA.Services.Contexts; with AWA.Comments.Beans; package body AWA.Comments.Modules is Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("AWA.Comments.Module"); package Register is new AWA.Modules.Beans (Module => Comment_Module, Module_Access => Comment_Module_Access); -- ------------------------------ -- Initialize the comments module. -- ------------------------------ overriding procedure Initialize (Plugin : in out Comment_Module; App : in AWA.Modules.Application_Access; Props : in ASF.Applications.Config) is begin Log.Info ("Initializing the comments module"); -- Register the comment list bean. Register.Register (Plugin => Plugin, Name => "AWA.Comments.Beans.Comment_List_Bean", Handler => AWA.Comments.Beans.Create_Comment_List_Bean'Access); -- Register the comment bean. Register.Register (Plugin => Plugin, Name => "AWA.Comments.Beans.Comment_Bean", Handler => AWA.Comments.Beans.Create_Comment_Bean'Access); AWA.Modules.Module (Plugin).Initialize (App, Props); end Initialize; -- ------------------------------ -- Load the comment identified by the given identifier. -- ------------------------------ procedure Load_Comment (Model : in Comment_Module; Comment : in out AWA.Comments.Models.Comment_Ref'Class; Id : in ADO.Identifier) is pragma Unreferenced (Model); Ctx : constant Services.Contexts.Service_Context_Access := AWA.Services.Contexts.Current; DB : ADO.Sessions.Session := AWA.Services.Contexts.Get_Session (Ctx); Found : Boolean; begin Comment.Load (DB, Id, Found); end Load_Comment; -- Create a new comment for the associated database entity. procedure Create_Comment (Model : in Comment_Module; Permission : in String; Comment : in out AWA.Comments.Models.Comment_Ref'Class) is pragma Unreferenced (Model); Ctx : constant Services.Contexts.Service_Context_Access := AWA.Services.Contexts.Current; User : constant AWA.Users.Models.User_Ref := Ctx.Get_User; DB : ADO.Sessions.Master_Session := AWA.Services.Contexts.Get_Master_Session (Ctx); begin Ctx.Start; Log.Info ("Creating new comment for {0}", ADO.Identifier'Image (Comment.Get_Entity_Id)); -- Check that the user has the create permission on the given workspace. AWA.Permissions.Check (Permission => Security.Permissions.Get_Permission_Index (Permission), Entity => Comment.Get_Entity_Id); Comment.Set_Author (User); Comment.Set_Create_Date (Ada.Calendar.Clock); Comment.Save (DB); Ctx.Commit; end Create_Comment; end AWA.Comments.Modules;
----------------------------------------------------------------------- -- awa-comments-module -- Comments module -- Copyright (C) 2011, 2012, 2013, 2014 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Calendar; with Util.Log.Loggers; with ADO.Sessions; with ADO.Sessions.Entities; with Security.Permissions; with AWA.Users.Models; with AWA.Permissions; with AWA.Modules.Beans; with AWA.Services.Contexts; with AWA.Comments.Beans; package body AWA.Comments.Modules is Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("AWA.Comments.Module"); package Register is new AWA.Modules.Beans (Module => Comment_Module, Module_Access => Comment_Module_Access); -- ------------------------------ -- Initialize the comments module. -- ------------------------------ overriding procedure Initialize (Plugin : in out Comment_Module; App : in AWA.Modules.Application_Access; Props : in ASF.Applications.Config) is begin Log.Info ("Initializing the comments module"); -- Register the comment list bean. Register.Register (Plugin => Plugin, Name => "AWA.Comments.Beans.Comment_List_Bean", Handler => AWA.Comments.Beans.Create_Comment_List_Bean'Access); -- Register the comment bean. Register.Register (Plugin => Plugin, Name => "AWA.Comments.Beans.Comment_Bean", Handler => AWA.Comments.Beans.Create_Comment_Bean'Access); AWA.Modules.Module (Plugin).Initialize (App, Props); end Initialize; -- ------------------------------ -- Load the comment identified by the given identifier. -- ------------------------------ procedure Load_Comment (Model : in Comment_Module; Comment : in out AWA.Comments.Models.Comment_Ref'Class; Id : in ADO.Identifier) is pragma Unreferenced (Model); Ctx : constant Services.Contexts.Service_Context_Access := AWA.Services.Contexts.Current; DB : ADO.Sessions.Session := AWA.Services.Contexts.Get_Session (Ctx); Found : Boolean; begin Comment.Load (DB, Id, Found); end Load_Comment; -- ------------------------------ -- Create a new comment for the associated database entity. -- ------------------------------ procedure Create_Comment (Model : in Comment_Module; Permission : in String; Entity_Type : in String; Comment : in out AWA.Comments.Models.Comment_Ref'Class) is pragma Unreferenced (Model); Ctx : constant Services.Contexts.Service_Context_Access := AWA.Services.Contexts.Current; User : constant AWA.Users.Models.User_Ref := Ctx.Get_User; DB : ADO.Sessions.Master_Session := AWA.Services.Contexts.Get_Master_Session (Ctx); begin Ctx.Start; Log.Info ("Creating new comment for {0}", ADO.Identifier'Image (Comment.Get_Entity_Id)); -- Check that the user has the create permission on the given workspace. AWA.Permissions.Check (Permission => Security.Permissions.Get_Permission_Index (Permission), Entity => Comment.Get_Entity_Id); Comment.Set_Entity_Type (ADO.Sessions.Entities.Find_Entity_Type (DB, Entity_Type)); Comment.Set_Author (User); Comment.Set_Create_Date (Ada.Calendar.Clock); Comment.Save (DB); Ctx.Commit; end Create_Comment; end AWA.Comments.Modules;
Use the entity type parameter to setup the new comment
Use the entity type parameter to setup the new comment
Ada
apache-2.0
tectronics/ada-awa,tectronics/ada-awa,Letractively/ada-awa,tectronics/ada-awa,Letractively/ada-awa,Letractively/ada-awa
e3b8ecaa4c2ad730747cf8c99bf149ebeac833b1
src/core/texts/util-texts-builders.adb
src/core/texts/util-texts-builders.adb
----------------------------------------------------------------------- -- util-texts-builders -- Text builder -- Copyright (C) 2013, 2016, 2017, 2021, 2022 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Unchecked_Deallocation; package body Util.Texts.Builders is -- ------------------------------ -- Get the length of the item builder. -- ------------------------------ function Length (Source : in Builder) return Natural is begin return Source.Length; end Length; -- ------------------------------ -- Get the capacity of the builder. -- ------------------------------ function Capacity (Source : in Builder) return Natural is B : constant Block_Access := Source.Current; begin return Source.Length + B.Len - B.Last; end Capacity; -- ------------------------------ -- Get the builder block size. -- ------------------------------ function Block_Size (Source : in Builder) return Positive is begin return Source.Block_Size; end Block_Size; -- ------------------------------ -- Set the block size for the allocation of next chunks. -- ------------------------------ procedure Set_Block_Size (Source : in out Builder; Size : in Positive) is begin Source.Block_Size := Size; end Set_Block_Size; -- ------------------------------ -- Append the <tt>New_Item</tt> at the end of the source growing the buffer if necessary. -- ------------------------------ procedure Append (Source : in out Builder; New_Item : in Input) is B : Block_Access := Source.Current; Start : Natural := New_Item'First; Last : constant Natural := New_Item'Last; begin while Start <= Last loop declare Space : Natural := B.Len - B.Last; Size : constant Natural := Last - Start + 1; begin if Space > Size then Space := Size; elsif Space = 0 then if Size > Source.Block_Size then B.Next_Block := new Block (Size); else B.Next_Block := new Block (Source.Block_Size); end if; B := B.Next_Block; Source.Current := B; if B.Len > Size then Space := Size; else Space := B.Len; end if; end if; B.Content (B.Last + 1 .. B.Last + Space) := New_Item (Start .. Start + Space - 1); Source.Length := Source.Length + Space; B.Last := B.Last + Space; Start := Start + Space; end; end loop; end Append; -- ------------------------------ -- Append the <tt>New_Item</tt> at the end of the source growing the buffer if necessary. -- ------------------------------ procedure Append (Source : in out Builder; New_Item : in Element_Type) is B : Block_Access := Source.Current; begin if B.Len = B.Last then B.Next_Block := new Block (Source.Block_Size); B := B.Next_Block; Source.Current := B; end if; Source.Length := Source.Length + 1; B.Last := B.Last + 1; B.Content (B.Last) := New_Item; end Append; procedure Inline_Append (Source : in out Builder) is B : Block_Access := Source.Current; Last : Natural; begin loop if B.Len = B.Last then B.Next_Block := new Block (Source.Block_Size); B := B.Next_Block; Source.Current := B; end if; Process (B.Content (B.Last + 1 .. B.Len), Last); exit when Last > B.Len or Last <= B.Last; Source.Length := Source.Length + Last - B.Last; B.Last := Last; exit when Last < B.Len; end loop; end Inline_Append; -- ------------------------------ -- Append in `Into` builder the `Content` builder starting at `From` position -- and the up to and including the `To` position. -- ------------------------------ procedure Append (Into : in out Builder; Content : in Builder; From : in Positive; To : in Positive) is begin if From <= Content.First.Last then if To <= Content.First.Last then Append (Into, Content.First.Content (From .. To)); return; end if; Append (Into, Content.First.Content (From .. Content.First.Last)); end if; declare Pos : Integer := From - Into.First.Last; Last : Integer := To - Into.First.Last; B : Block_Access := Into.First.Next_Block; begin loop if B = null then return; end if; if Pos <= B.Last then if Last <= B.Last then Append (Into, B.Content (1 .. Last)); return; end if; Append (Into, B.Content (1 .. B.Last)); end if; Pos := Pos - B.Last; Last := Last - B.Last; B := B.Next_Block; end loop; end; end Append; -- ------------------------------ -- Clear the source freeing any storage allocated for the buffer. -- ------------------------------ procedure Clear (Source : in out Builder) is procedure Free is new Ada.Unchecked_Deallocation (Object => Block, Name => Block_Access); Current, Next : Block_Access; begin Next := Source.First.Next_Block; while Next /= null loop Current := Next; Next := Current.Next_Block; Free (Current); end loop; Source.First.Next_Block := null; Source.First.Last := 0; Source.Current := Source.First'Unchecked_Access; Source.Length := 0; end Clear; -- ------------------------------ -- Iterate over the buffer content calling the <tt>Process</tt> procedure with each -- chunk. -- ------------------------------ procedure Iterate (Source : in Builder; Process : not null access procedure (Chunk : in Input)) is begin if Source.First.Last > 0 then Process (Source.First.Content (1 .. Source.First.Last)); declare B : Block_Access := Source.First.Next_Block; begin while B /= null loop Process (B.Content (1 .. B.Last)); B := B.Next_Block; end loop; end; end if; end Iterate; procedure Inline_Iterate (Source : in Builder) is begin if Source.First.Last > 0 then Process (Source.First.Content (1 .. Source.First.Last)); declare B : Block_Access := Source.First.Next_Block; begin while B /= null loop Process (B.Content (1 .. B.Last)); B := B.Next_Block; end loop; end; end if; end Inline_Iterate; -- ------------------------------ -- Return the content starting from the tail and up to <tt>Length</tt> items. -- ------------------------------ function Tail (Source : in Builder; Length : in Natural) return Input is Last : constant Natural := Source.Current.Last; begin if Last >= Length then return Source.Current.Content (Last - Length + 1 .. Last); elsif Length >= Source.Length then return To_Array (Source); else declare Result : Input (1 .. Length); Offset : Natural := Source.Length - Length; B : access constant Block := Source.First'Access; Src_Pos : Positive := 1; Dst_Pos : Positive := 1; Len : Natural; begin -- Skip the data moving to next blocks as needed. while Offset /= 0 loop if Offset < B.Last then Src_Pos := Offset + 1; Offset := 0; else Offset := Offset - B.Last + 1; B := B.Next_Block; end if; end loop; -- Copy what remains until we reach the length. while Dst_Pos <= Length loop Len := B.Last - Src_Pos + 1; Result (Dst_Pos .. Dst_Pos + Len - 1) := B.Content (Src_Pos .. B.Last); Src_Pos := 1; Dst_Pos := Dst_Pos + Len; B := B.Next_Block; end loop; return Result; end; end if; end Tail; -- ------------------------------ -- Get the buffer content as an array. -- ------------------------------ function To_Array (Source : in Builder) return Input is Result : Input (1 .. Source.Length); begin if Source.First.Last > 0 then declare Pos : Positive := Source.First.Last; B : Block_Access := Source.First.Next_Block; begin Result (1 .. Pos) := Source.First.Content (1 .. Pos); while B /= null loop Result (Pos + 1 .. Pos + B.Last) := B.Content (1 .. B.Last); Pos := Pos + B.Last; B := B.Next_Block; end loop; end; end if; return Result; end To_Array; -- ------------------------------ -- Get the element at the given position. -- ------------------------------ function Element (Source : in Builder; Position : in Positive) return Element_Type is begin if Position <= Source.First.Last then return Source.First.Content (Position); else declare Pos : Positive := Position - Source.First.Last; B : Block_Access := Source.First.Next_Block; begin loop if Pos <= B.Last then return B.Content (Pos); end if; Pos := Pos - B.Last; B := B.Next_Block; end loop; end; end if; end Element; -- ------------------------------ -- Find the position of some content by running the `Index` function. -- The `Index` function is called with chunks starting at the given position and -- until it returns a positive value or we reach the last chunk. It must return -- the found position in the chunk. -- ------------------------------ function Find (Source : in Builder; Position : in Positive) return Natural is Result : Natural; begin if Position <= Source.First.Last then Result := Index (Source.First.Content (Position .. Source.First.Last)); if Result > 0 then return Result; end if; end if; declare Pos : Integer := Position - Source.First.Last; Offset : Positive := Source.First.Last; B : Block_Access := Source.First.Next_Block; begin loop if B = null then return 0; end if; if Pos <= B.Last then if Pos > 0 then Result := Index (B.Content (Pos .. B.Last)); else Result := Index (B.Content (1 .. B.Last)); end if; if Result > 0 then return Offset + Result; end if; end if; Pos := Pos - B.Last; Offset := Offset + B.Last; B := B.Next_Block; end loop; end; end Find; -- ------------------------------ -- Call the <tt>Process</tt> procedure with the full buffer content, trying to avoid -- secondary stack copies as much as possible. -- ------------------------------ procedure Get (Source : in Builder) is begin if Source.Length < Source.First.Len then Process (Source.First.Content (1 .. Source.Length)); else declare Content : constant Input := To_Array (Source); begin Process (Content); end; end if; end Get; -- ------------------------------ -- Format the message and replace occurrences of argument patterns by -- their associated value. -- Returns the formatted message in the stream -- ------------------------------ procedure Format (Into : in out Builder; Message : in Input; Arguments : in Value_List) is C : Element_Type; Old_Pos : Natural; N : Natural := 0; Pos : Natural := Message'First; First : Natural := Pos; begin -- Replace {N} with arg1, arg2, arg3 or ? while Pos <= Message'Last loop C := Message (Pos); if Element_Type'Pos (C) = Character'Pos ('{') and then Pos + 1 <= Message'Last then if First /= Pos then Append (Into, Message (First .. Pos - 1)); end if; N := 0; Pos := Pos + 1; C := Message (Pos); -- Handle {} replacement to emit the current argument and advance argument position. if Element_Type'Pos (C) = Character'Pos ('}') then Pos := Pos + 1; if N >= Arguments'Length then First := Pos - 2; else Append (Into, Arguments (N + Arguments'First)); First := Pos; end if; N := N + 1; else N := 0; Old_Pos := Pos - 1; loop if Element_Type'Pos (C) >= Character'Pos ('0') and Element_Type'Pos (C) <= Character'Pos ('9') then N := N * 10 + Natural (Element_Type'Pos (C) - Character'Pos ('0')); Pos := Pos + 1; if Pos > Message'Last then First := Old_Pos; exit; end if; elsif Element_Type'Pos (C) = Character'Pos ('}') then Pos := Pos + 1; if N >= Arguments'Length then First := Old_Pos; else Append (Into, Arguments (N + Arguments'First)); First := Pos; end if; exit; else First := Old_Pos; exit; end if; C := Message (Pos); end loop; end if; else Pos := Pos + 1; end if; end loop; if First /= Pos then Append (Into, Message (First .. Pos - 1)); end if; end Format; -- ------------------------------ -- Setup the builder. -- ------------------------------ overriding procedure Initialize (Source : in out Builder) is begin Source.Current := Source.First'Unchecked_Access; end Initialize; -- ------------------------------ -- Finalize the builder releasing the storage. -- ------------------------------ overriding procedure Finalize (Source : in out Builder) is begin Clear (Source); end Finalize; end Util.Texts.Builders;
----------------------------------------------------------------------- -- util-texts-builders -- Text builder -- Copyright (C) 2013, 2016, 2017, 2021, 2022 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Unchecked_Deallocation; package body Util.Texts.Builders is -- ------------------------------ -- Get the length of the item builder. -- ------------------------------ function Length (Source : in Builder) return Natural is begin return Source.Length; end Length; -- ------------------------------ -- Get the capacity of the builder. -- ------------------------------ function Capacity (Source : in Builder) return Natural is B : constant Block_Access := Source.Current; begin return Source.Length + B.Len - B.Last; end Capacity; -- ------------------------------ -- Get the builder block size. -- ------------------------------ function Block_Size (Source : in Builder) return Positive is begin return Source.Block_Size; end Block_Size; -- ------------------------------ -- Set the block size for the allocation of next chunks. -- ------------------------------ procedure Set_Block_Size (Source : in out Builder; Size : in Positive) is begin Source.Block_Size := Size; end Set_Block_Size; -- ------------------------------ -- Append the <tt>New_Item</tt> at the end of the source growing the buffer if necessary. -- ------------------------------ procedure Append (Source : in out Builder; New_Item : in Input) is B : Block_Access := Source.Current; Start : Natural := New_Item'First; Last : constant Natural := New_Item'Last; begin while Start <= Last loop declare Space : Natural := B.Len - B.Last; Size : constant Natural := Last - Start + 1; begin if Space > Size then Space := Size; elsif Space = 0 then if Size > Source.Block_Size then B.Next_Block := new Block (Size); else B.Next_Block := new Block (Source.Block_Size); end if; B := B.Next_Block; Source.Current := B; if B.Len > Size then Space := Size; else Space := B.Len; end if; end if; B.Content (B.Last + 1 .. B.Last + Space) := New_Item (Start .. Start + Space - 1); Source.Length := Source.Length + Space; B.Last := B.Last + Space; Start := Start + Space; end; end loop; end Append; -- ------------------------------ -- Append the <tt>New_Item</tt> at the end of the source growing the buffer if necessary. -- ------------------------------ procedure Append (Source : in out Builder; New_Item : in Element_Type) is B : Block_Access := Source.Current; begin if B.Len = B.Last then B.Next_Block := new Block (Source.Block_Size); B := B.Next_Block; Source.Current := B; end if; Source.Length := Source.Length + 1; B.Last := B.Last + 1; B.Content (B.Last) := New_Item; end Append; procedure Inline_Append (Source : in out Builder) is B : Block_Access := Source.Current; Last : Natural; begin loop if B.Len = B.Last then B.Next_Block := new Block (Source.Block_Size); B := B.Next_Block; Source.Current := B; end if; Process (B.Content (B.Last + 1 .. B.Len), Last); exit when Last > B.Len or Last <= B.Last; Source.Length := Source.Length + Last - B.Last; B.Last := Last; exit when Last < B.Len; end loop; end Inline_Append; -- ------------------------------ -- Append in `Into` builder the `Content` builder starting at `From` position -- and the up to and including the `To` position. -- ------------------------------ procedure Append (Into : in out Builder; Content : in Builder; From : in Positive; To : in Positive) is begin if From <= Content.First.Last then if To <= Content.First.Last then Append (Into, Content.First.Content (From .. To)); return; end if; Append (Into, Content.First.Content (From .. Content.First.Last)); end if; declare Pos : Integer := From - Into.First.Last; Last : Integer := To - Into.First.Last; B : Block_Access := Into.First.Next_Block; begin loop if B = null then return; end if; if Pos <= B.Last then if Last <= B.Last then Append (Into, B.Content (1 .. Last)); return; end if; Append (Into, B.Content (1 .. B.Last)); end if; Pos := Pos - B.Last; Last := Last - B.Last; B := B.Next_Block; end loop; end; end Append; -- ------------------------------ -- Clear the source freeing any storage allocated for the buffer. -- ------------------------------ procedure Clear (Source : in out Builder) is procedure Free is new Ada.Unchecked_Deallocation (Object => Block, Name => Block_Access); Current, Next : Block_Access; begin Next := Source.First.Next_Block; while Next /= null loop Current := Next; Next := Current.Next_Block; Free (Current); end loop; Source.First.Next_Block := null; Source.First.Last := 0; Source.Current := Source.First'Unchecked_Access; Source.Length := 0; end Clear; -- ------------------------------ -- Iterate over the buffer content calling the <tt>Process</tt> procedure with each -- chunk. -- ------------------------------ procedure Iterate (Source : in Builder; Process : not null access procedure (Chunk : in Input)) is begin if Source.First.Last > 0 then Process (Source.First.Content (1 .. Source.First.Last)); declare B : Block_Access := Source.First.Next_Block; begin while B /= null loop Process (B.Content (1 .. B.Last)); B := B.Next_Block; end loop; end; end if; end Iterate; procedure Inline_Iterate (Source : in Builder) is begin if Source.First.Last > 0 then Process (Source.First.Content (1 .. Source.First.Last)); declare B : Block_Access := Source.First.Next_Block; begin while B /= null loop Process (B.Content (1 .. B.Last)); B := B.Next_Block; end loop; end; end if; end Inline_Iterate; procedure Inline_Update (Source : in out Builder) is begin if Source.First.Last > 0 then Process (Source.First.Content (1 .. Source.First.Last)); declare B : Block_Access := Source.First.Next_Block; begin while B /= null loop Process (B.Content (1 .. B.Last)); B := B.Next_Block; end loop; end; end if; end Inline_Update; -- ------------------------------ -- Return the content starting from the tail and up to <tt>Length</tt> items. -- ------------------------------ function Tail (Source : in Builder; Length : in Natural) return Input is Last : constant Natural := Source.Current.Last; begin if Last >= Length then return Source.Current.Content (Last - Length + 1 .. Last); elsif Length >= Source.Length then return To_Array (Source); else declare Result : Input (1 .. Length); Offset : Natural := Source.Length - Length; B : access constant Block := Source.First'Access; Src_Pos : Positive := 1; Dst_Pos : Positive := 1; Len : Natural; begin -- Skip the data moving to next blocks as needed. while Offset /= 0 loop if Offset < B.Last then Src_Pos := Offset + 1; Offset := 0; else Offset := Offset - B.Last + 1; B := B.Next_Block; end if; end loop; -- Copy what remains until we reach the length. while Dst_Pos <= Length loop Len := B.Last - Src_Pos + 1; Result (Dst_Pos .. Dst_Pos + Len - 1) := B.Content (Src_Pos .. B.Last); Src_Pos := 1; Dst_Pos := Dst_Pos + Len; B := B.Next_Block; end loop; return Result; end; end if; end Tail; -- ------------------------------ -- Get the buffer content as an array. -- ------------------------------ function To_Array (Source : in Builder) return Input is Result : Input (1 .. Source.Length); begin if Source.First.Last > 0 then declare Pos : Positive := Source.First.Last; B : Block_Access := Source.First.Next_Block; begin Result (1 .. Pos) := Source.First.Content (1 .. Pos); while B /= null loop Result (Pos + 1 .. Pos + B.Last) := B.Content (1 .. B.Last); Pos := Pos + B.Last; B := B.Next_Block; end loop; end; end if; return Result; end To_Array; -- ------------------------------ -- Get the element at the given position. -- ------------------------------ function Element (Source : in Builder; Position : in Positive) return Element_Type is begin if Position <= Source.First.Last then return Source.First.Content (Position); else declare Pos : Positive := Position - Source.First.Last; B : Block_Access := Source.First.Next_Block; begin loop if Pos <= B.Last then return B.Content (Pos); end if; Pos := Pos - B.Last; B := B.Next_Block; end loop; end; end if; end Element; -- ------------------------------ -- Find the position of some content by running the `Index` function. -- The `Index` function is called with chunks starting at the given position and -- until it returns a positive value or we reach the last chunk. It must return -- the found position in the chunk. -- ------------------------------ function Find (Source : in Builder; Position : in Positive) return Natural is Result : Natural; begin if Position <= Source.First.Last then Result := Index (Source.First.Content (Position .. Source.First.Last)); if Result > 0 then return Result; end if; end if; declare Pos : Integer := Position - Source.First.Last; Offset : Positive := Source.First.Last; B : Block_Access := Source.First.Next_Block; begin loop if B = null then return 0; end if; if Pos <= B.Last then if Pos > 0 then Result := Index (B.Content (Pos .. B.Last)); else Result := Index (B.Content (1 .. B.Last)); end if; if Result > 0 then return Offset + Result; end if; end if; Pos := Pos - B.Last; Offset := Offset + B.Last; B := B.Next_Block; end loop; end; end Find; -- ------------------------------ -- Call the <tt>Process</tt> procedure with the full buffer content, trying to avoid -- secondary stack copies as much as possible. -- ------------------------------ procedure Get (Source : in Builder) is begin if Source.Length < Source.First.Len then Process (Source.First.Content (1 .. Source.Length)); else declare Content : constant Input := To_Array (Source); begin Process (Content); end; end if; end Get; -- ------------------------------ -- Format the message and replace occurrences of argument patterns by -- their associated value. -- Returns the formatted message in the stream -- ------------------------------ procedure Format (Into : in out Builder; Message : in Input; Arguments : in Value_List) is C : Element_Type; Old_Pos : Natural; N : Natural := 0; Pos : Natural := Message'First; First : Natural := Pos; begin -- Replace {N} with arg1, arg2, arg3 or ? while Pos <= Message'Last loop C := Message (Pos); if Element_Type'Pos (C) = Character'Pos ('{') and then Pos + 1 <= Message'Last then if First /= Pos then Append (Into, Message (First .. Pos - 1)); end if; N := 0; Pos := Pos + 1; C := Message (Pos); -- Handle {} replacement to emit the current argument and advance argument position. if Element_Type'Pos (C) = Character'Pos ('}') then Pos := Pos + 1; if N >= Arguments'Length then First := Pos - 2; else Append (Into, Arguments (N + Arguments'First)); First := Pos; end if; N := N + 1; else N := 0; Old_Pos := Pos - 1; loop if Element_Type'Pos (C) >= Character'Pos ('0') and Element_Type'Pos (C) <= Character'Pos ('9') then N := N * 10 + Natural (Element_Type'Pos (C) - Character'Pos ('0')); Pos := Pos + 1; if Pos > Message'Last then First := Old_Pos; exit; end if; elsif Element_Type'Pos (C) = Character'Pos ('}') then Pos := Pos + 1; if N >= Arguments'Length then First := Old_Pos; else Append (Into, Arguments (N + Arguments'First)); First := Pos; end if; exit; else First := Old_Pos; exit; end if; C := Message (Pos); end loop; end if; else Pos := Pos + 1; end if; end loop; if First /= Pos then Append (Into, Message (First .. Pos - 1)); end if; end Format; -- ------------------------------ -- Setup the builder. -- ------------------------------ overriding procedure Initialize (Source : in out Builder) is begin Source.Current := Source.First'Unchecked_Access; end Initialize; -- ------------------------------ -- Finalize the builder releasing the storage. -- ------------------------------ overriding procedure Finalize (Source : in out Builder) is begin Clear (Source); end Finalize; end Util.Texts.Builders;
Implement Inline_Update generic procedure
Implement Inline_Update generic procedure
Ada
apache-2.0
stcarrez/ada-util,stcarrez/ada-util
2b13272e5145125128217ad9adbc39589174d8ce
awa/plugins/awa-questions/src/awa-questions-beans.adb
awa/plugins/awa-questions/src/awa-questions-beans.adb
----------------------------------------------------------------------- -- awa-questions-beans -- Beans for module questions -- Copyright (C) 2012, 2013 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with ADO.Queries; with ADO.Sessions; with ADO.Sessions.Entities; with AWA.Services.Contexts; with AWA.Questions.Services; package body AWA.Questions.Beans is -- ------------------------------ -- Get the value identified by the name. -- ------------------------------ overriding function Get_Value (From : in Question_Bean; Name : in String) return Util.Beans.Objects.Object is begin if From.Is_Null then return Util.Beans.Objects.Null_Object; else return AWA.Questions.Models.Question_Bean (From).Get_Value (Name); end if; end Get_Value; -- ------------------------------ -- Set the value identified by the name. -- ------------------------------ overriding procedure Set_Value (From : in out Question_Bean; Name : in String; Value : in Util.Beans.Objects.Object) is begin if Name = "title" then From.Set_Title (Util.Beans.Objects.To_String (Value)); elsif Name = "description" then From.Set_Description (Util.Beans.Objects.To_String (Value)); elsif Name = "id" and not Util.Beans.Objects.Is_Empty (Value) then From.Service.Load_Question (From, ADO.Identifier (Util.Beans.Objects.To_Integer (Value))); end if; end Set_Value; -- ------------------------------ -- Create or save the question. -- ------------------------------ procedure Save (Bean : in out Question_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is begin Bean.Service.Save_Question (Bean); end Save; -- ------------------------------ -- Delete the question. -- ------------------------------ procedure Delete (Bean : in out Question_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is begin Bean.Service.Delete_Question (Bean); end Delete; -- ------------------------------ -- Create the Question_Bean bean instance. -- ------------------------------ function Create_Question_Bean (Module : in AWA.Questions.Modules.Question_Module_Access) return Util.Beans.Basic.Readonly_Bean_Access is Object : constant Question_Bean_Access := new Question_Bean; begin Object.Service := Module.Get_Question_Manager; return Object.all'Access; end Create_Question_Bean; -- Get the value identified by the name. overriding function Get_Value (From : in Answer_Bean; Name : in String) return Util.Beans.Objects.Object is begin if Name = "question_id" then return Util.Beans.Objects.To_Object (Long_Long_Integer (From.Question.Get_Id)); elsif From.Is_Null then return Util.Beans.Objects.Null_Object; else return AWA.Questions.Models.Answer_Bean (From).Get_Value (Name); end if; end Get_Value; -- ------------------------------ -- Set the value identified by the name. -- ------------------------------ overriding procedure Set_Value (From : in out Answer_Bean; Name : in String; Value : in Util.Beans.Objects.Object) is begin if Name = "id" and not Util.Beans.Objects.Is_Null (Value) then From.Service.Load_Answer (From, ADO.Identifier (Util.Beans.Objects.To_Integer (Value))); elsif Name = "answer" then From.Set_Answer (Util.Beans.Objects.To_String (Value)); elsif Name = "question_id" and not Util.Beans.Objects.Is_Null (Value) then From.Service.Load_Question (From.Question, ADO.Identifier (Util.Beans.Objects.To_Integer (Value))); end if; end Set_Value; -- ------------------------------ -- Create or save the answer. -- ------------------------------ procedure Save (Bean : in out Answer_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is begin Bean.Service.Save_Answer (Question => Bean.Question, Answer => Bean); end Save; -- Delete the question. procedure Delete (Bean : in out Answer_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is begin null; end Delete; -- ------------------------------ -- Create the answer bean instance. -- ------------------------------ function Create_Answer_Bean (Module : in AWA.Questions.Modules.Question_Module_Access) return Util.Beans.Basic.Readonly_Bean_Access is Object : constant Answer_Bean_Access := new Answer_Bean; begin Object.Service := Module.Get_Question_Manager; return Object.all'Access; end Create_Answer_Bean; -- ------------------------------ -- Create the Question_Info_List_Bean bean instance. -- ------------------------------ function Create_Question_List_Bean (Module : in AWA.Questions.Modules.Question_Module_Access) return Util.Beans.Basic.Readonly_Bean_Access is use AWA.Questions.Models; use AWA.Services; Object : constant Question_Info_List_Bean_Access := new Question_Info_List_Bean; Session : ADO.Sessions.Session := Module.Get_Session; Query : ADO.Queries.Context; begin Query.Set_Query (AWA.Questions.Models.Query_Question_List); ADO.Sessions.Entities.Bind_Param (Params => Query, Name => "entity_type", Table => AWA.Questions.Models.QUESTION_TABLE, Session => Session); AWA.Questions.Models.List (Object.all, Session, Query); return Object.all'Access; end Create_Question_List_Bean; -- ------------------------------ -- Get the value identified by the name. -- ------------------------------ overriding function Get_Value (From : in Question_Display_Bean; Name : in String) return Util.Beans.Objects.Object is begin if Name = "answers" then return Util.Beans.Objects.To_Object (Value => From.Answer_List_Bean, Storage => Util.Beans.Objects.STATIC); elsif Name = "question" then return Util.Beans.Objects.To_Object (Value => From.Question_Bean, Storage => Util.Beans.Objects.STATIC); else return Util.Beans.Objects.Null_Object; end if; end Get_Value; -- ------------------------------ -- Set the value identified by the name. -- ------------------------------ overriding procedure Set_Value (From : in out Question_Display_Bean; Name : in String; Value : in Util.Beans.Objects.Object) is begin if Name = "id" and not Util.Beans.Objects.Is_Empty (Value) then declare use AWA.Questions.Models; use AWA.Services; Session : ADO.Sessions.Session := From.Service.Get_Session; Query : ADO.Queries.Context; List : AWA.Questions.Models.Question_Display_Info_List_Bean; begin Query.Set_Query (AWA.Questions.Models.Query_Question_Info); Query.Bind_Param ("question_id", Util.Beans.Objects.To_Integer (Value)); ADO.Sessions.Entities.Bind_Param (Params => Query, Name => "entity_type", Table => AWA.Questions.Models.QUESTION_TABLE, Session => Session); AWA.Questions.Models.List (List, Session, Query); if not List.List.Is_Empty then From.Question := List.List.Element (0); end if; Query.Clear; Query.Set_Query (AWA.Questions.Models.Query_Answer_List); Query.Bind_Param ("question_id", Util.Beans.Objects.To_Integer (Value)); AWA.Questions.Models.List (From.Answer_List, Session, Query); end; end if; end Set_Value; -- ------------------------------ -- Create the Question_Display_Bean bean instance. -- ------------------------------ function Create_Question_Display_Bean (Module : in AWA.Questions.Modules.Question_Module_Access) return Util.Beans.Basic.Readonly_Bean_Access is Object : constant Question_Display_Bean_Access := new Question_Display_Bean; begin Object.Service := Module.Get_Question_Manager; Object.Question_Bean := Object.Question'Access; Object.Answer_List_Bean := Object.Answer_List'Access; return Object.all'Access; end Create_Question_Display_Bean; end AWA.Questions.Beans;
----------------------------------------------------------------------- -- awa-questions-beans -- Beans for module questions -- Copyright (C) 2012, 2013 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with ADO.Queries; with ADO.Sessions; with ADO.Sessions.Entities; with AWA.Services.Contexts; package body AWA.Questions.Beans is -- ------------------------------ -- Get the value identified by the name. -- ------------------------------ overriding function Get_Value (From : in Question_Bean; Name : in String) return Util.Beans.Objects.Object is begin if From.Is_Null then return Util.Beans.Objects.Null_Object; else return AWA.Questions.Models.Question_Bean (From).Get_Value (Name); end if; end Get_Value; -- ------------------------------ -- Set the value identified by the name. -- ------------------------------ overriding procedure Set_Value (From : in out Question_Bean; Name : in String; Value : in Util.Beans.Objects.Object) is begin if Name = "title" then From.Set_Title (Util.Beans.Objects.To_String (Value)); elsif Name = "description" then From.Set_Description (Util.Beans.Objects.To_String (Value)); elsif Name = "id" and not Util.Beans.Objects.Is_Empty (Value) then From.Service.Load_Question (From, ADO.Identifier (Util.Beans.Objects.To_Integer (Value))); end if; end Set_Value; -- ------------------------------ -- Create or save the question. -- ------------------------------ procedure Save (Bean : in out Question_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is pragma Unreferenced (Outcome); begin Bean.Service.Save_Question (Bean); end Save; -- ------------------------------ -- Delete the question. -- ------------------------------ procedure Delete (Bean : in out Question_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is pragma Unreferenced (Outcome); begin Bean.Service.Delete_Question (Bean); end Delete; -- ------------------------------ -- Create the Question_Bean bean instance. -- ------------------------------ function Create_Question_Bean (Module : in AWA.Questions.Modules.Question_Module_Access) return Util.Beans.Basic.Readonly_Bean_Access is Object : constant Question_Bean_Access := new Question_Bean; begin Object.Service := Module.Get_Question_Manager; return Object.all'Access; end Create_Question_Bean; -- Get the value identified by the name. overriding function Get_Value (From : in Answer_Bean; Name : in String) return Util.Beans.Objects.Object is begin if Name = "question_id" then return Util.Beans.Objects.To_Object (Long_Long_Integer (From.Question.Get_Id)); elsif From.Is_Null then return Util.Beans.Objects.Null_Object; else return AWA.Questions.Models.Answer_Bean (From).Get_Value (Name); end if; end Get_Value; -- ------------------------------ -- Set the value identified by the name. -- ------------------------------ overriding procedure Set_Value (From : in out Answer_Bean; Name : in String; Value : in Util.Beans.Objects.Object) is begin if Name = "id" and not Util.Beans.Objects.Is_Null (Value) then From.Service.Load_Answer (From, ADO.Identifier (Util.Beans.Objects.To_Integer (Value))); elsif Name = "answer" then From.Set_Answer (Util.Beans.Objects.To_String (Value)); elsif Name = "question_id" and not Util.Beans.Objects.Is_Null (Value) then From.Service.Load_Question (From.Question, ADO.Identifier (Util.Beans.Objects.To_Integer (Value))); end if; end Set_Value; -- ------------------------------ -- Create or save the answer. -- ------------------------------ procedure Save (Bean : in out Answer_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is pragma Unreferenced (Outcome); begin Bean.Service.Save_Answer (Question => Bean.Question, Answer => Bean); end Save; -- Delete the question. procedure Delete (Bean : in out Answer_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is begin null; end Delete; -- ------------------------------ -- Create the answer bean instance. -- ------------------------------ function Create_Answer_Bean (Module : in AWA.Questions.Modules.Question_Module_Access) return Util.Beans.Basic.Readonly_Bean_Access is Object : constant Answer_Bean_Access := new Answer_Bean; begin Object.Service := Module.Get_Question_Manager; return Object.all'Access; end Create_Answer_Bean; -- ------------------------------ -- Create the Question_Info_List_Bean bean instance. -- ------------------------------ function Create_Question_List_Bean (Module : in AWA.Questions.Modules.Question_Module_Access) return Util.Beans.Basic.Readonly_Bean_Access is use AWA.Questions.Models; use AWA.Services; Object : constant Question_Info_List_Bean_Access := new Question_Info_List_Bean; Session : ADO.Sessions.Session := Module.Get_Session; Query : ADO.Queries.Context; begin Query.Set_Query (AWA.Questions.Models.Query_Question_List); ADO.Sessions.Entities.Bind_Param (Params => Query, Name => "entity_type", Table => AWA.Questions.Models.QUESTION_TABLE, Session => Session); AWA.Questions.Models.List (Object.all, Session, Query); return Object.all'Access; end Create_Question_List_Bean; -- ------------------------------ -- Get the value identified by the name. -- ------------------------------ overriding function Get_Value (From : in Question_Display_Bean; Name : in String) return Util.Beans.Objects.Object is begin if Name = "answers" then return Util.Beans.Objects.To_Object (Value => From.Answer_List_Bean, Storage => Util.Beans.Objects.STATIC); elsif Name = "question" then return Util.Beans.Objects.To_Object (Value => From.Question_Bean, Storage => Util.Beans.Objects.STATIC); else return Util.Beans.Objects.Null_Object; end if; end Get_Value; -- ------------------------------ -- Set the value identified by the name. -- ------------------------------ overriding procedure Set_Value (From : in out Question_Display_Bean; Name : in String; Value : in Util.Beans.Objects.Object) is begin if Name = "id" and not Util.Beans.Objects.Is_Empty (Value) then declare package ASC renames AWA.Services.Contexts; use AWA.Questions.Models; use AWA.Services; Session : ADO.Sessions.Session := From.Service.Get_Session; Query : ADO.Queries.Context; List : AWA.Questions.Models.Question_Display_Info_List_Bean; Ctx : constant ASC.Service_Context_Access := ASC.Current; begin Query.Set_Query (AWA.Questions.Models.Query_Question_Info); Query.Bind_Param ("question_id", Util.Beans.Objects.To_Integer (Value)); Query.Bind_Param ("user_id", Ctx.Get_User_Identifier); ADO.Sessions.Entities.Bind_Param (Params => Query, Name => "entity_type", Table => AWA.Questions.Models.QUESTION_TABLE, Session => Session); AWA.Questions.Models.List (List, Session, Query); if not List.List.Is_Empty then From.Question := List.List.Element (0); end if; Query.Clear; Query.Set_Query (AWA.Questions.Models.Query_Answer_List); Query.Bind_Param ("question_id", Util.Beans.Objects.To_Integer (Value)); AWA.Questions.Models.List (From.Answer_List, Session, Query); end; end if; end Set_Value; -- ------------------------------ -- Create the Question_Display_Bean bean instance. -- ------------------------------ function Create_Question_Display_Bean (Module : in AWA.Questions.Modules.Question_Module_Access) return Util.Beans.Basic.Readonly_Bean_Access is Object : constant Question_Display_Bean_Access := new Question_Display_Bean; begin Object.Service := Module.Get_Question_Manager; Object.Question_Bean := Object.Question'Access; Object.Answer_List_Bean := Object.Answer_List'Access; return Object.all'Access; end Create_Question_Display_Bean; end AWA.Questions.Beans;
Add the user identifier (if known) to the query to get his rating for the question
Add the user identifier (if known) to the query to get his rating for the question
Ada
apache-2.0
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
8d0629ee30af42875519c3b7d2523ad17d3c0a34
tools/druss-commands.adb
tools/druss-commands.adb
----------------------------------------------------------------------- -- druss-commands -- Commands available for Druss -- 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 Druss.Commands.Bboxes; with Druss.Commands.Get; with Druss.Commands.Status; with Druss.Commands.Wifi; package body Druss.Commands is Help_Command : aliased Druss.Commands.Drivers.Help_Command_Type; Bbox_Commands : aliased Druss.Commands.Bboxes.Command_Type; Get_Commands : aliased Druss.Commands.Get.Command_Type; Wifi_Commands : aliased Druss.Commands.Wifi.Command_Type; Status_Commands : aliased Druss.Commands.Status.Command_Type; procedure Gateway_Command (Command : in Drivers.Command_Type'Class; Args : in Util.Commands.Argument_List'Class; Arg_Pos : in Positive; Process : access procedure (Gateway : in out Gateways.Gateway_Type; Param : in String); Context : in out Context_Type) is begin if Args.Get_Count < Arg_Pos + 1 then Druss.Commands.Driver.Usage (Args); end if; declare Param : constant String := Args.Get_Argument (Arg_Pos); Gw : Druss.Gateways.Gateway_Ref; procedure Operation (Gateway : in out Druss.Gateways.Gateway_Type) is begin Process (Gateway, Param); end Operation; begin if Args.Get_Count = Arg_Pos then Druss.Gateways.Iterate (Context.Gateways, Operation'Access); else for I in Arg_Pos + 1 .. Args.Get_Count loop Gw := Druss.Gateways.Find_IP (Context.Gateways, Args.Get_Argument (I)); if not Gw.Is_Null then Operation (Gw.Value.all); end if; end loop; end if; end; end Gateway_Command; procedure Initialize is begin Driver.Set_Description ("Druss - The Bbox master controller"); Driver.Set_Usage ("[-v] [-o file] [-c config] <command> [<args>]" & ASCII.LF & "where:" & ASCII.LF & " -v Verbose execution mode" & ASCII.LF & " -c config Use the configuration file" & " (instead of $HOME/.config/druss/druss.properties)" & ASCII.LF & " -o file The output file to use"); Driver.Add_Command ("help", Help_Command'Access); Driver.Add_Command ("bbox", Bbox_Commands'Access); Driver.Add_Command ("get", Get_Commands'Access); Driver.Add_Command ("wifi", Wifi_Commands'Access); Driver.Add_Command ("status", Status_Commands'Access); end Initialize; -- ------------------------------ -- Print the bbox API status. -- ------------------------------ procedure Print_Status (Console : in Consoles.Console_Access; Field : in Field_Type; Value : in String) is begin if Value = "2" then Console.Print_Field (Field, "OK"); elsif Value = "-1" then Console.Print_Field (Field, "KO"); elsif Value = "1" then Console.Print_Field (Field, "Starting"); elsif Value = "0" then Console.Print_Field (Field, "Stopped"); else Console.Print_Field (Field, "?"); end if; end Print_Status; -- ------------------------------ -- Print a ON/OFF status. -- ------------------------------ procedure Print_On_Off (Console : in Consoles.Console_Access; Field : in Field_Type; Value : in String) is begin if Value = "1" then Console.Print_Field (Field, "ON"); elsif Value = "0" then Console.Print_Field (Field, "OFF"); else Console.Print_Field (Field, ""); end if; end Print_On_Off; end Druss.Commands;
----------------------------------------------------------------------- -- druss-commands -- Commands available for Druss -- Copyright (C) 2017 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Strings; with Druss.Commands.Bboxes; with Druss.Commands.Get; with Druss.Commands.Status; with Druss.Commands.Wifi; with Druss.Commands.Devices; with Druss.Commands.Ping; package body Druss.Commands is Help_Command : aliased Druss.Commands.Drivers.Help_Command_Type; Bbox_Commands : aliased Druss.Commands.Bboxes.Command_Type; Get_Commands : aliased Druss.Commands.Get.Command_Type; Wifi_Commands : aliased Druss.Commands.Wifi.Command_Type; Status_Commands : aliased Druss.Commands.Status.Command_Type; Device_Commands : aliased Druss.Commands.Devices.Command_Type; Ping_Commands : aliased Druss.Commands.Ping.Command_Type; procedure Gateway_Command (Command : in Drivers.Command_Type'Class; Args : in Util.Commands.Argument_List'Class; Arg_Pos : in Positive; Process : access procedure (Gateway : in out Gateways.Gateway_Type; Param : in String); Context : in out Context_Type) is begin if Args.Get_Count < Arg_Pos then Context.Console.Notice (N_USAGE, "Missing argument for command"); Druss.Commands.Driver.Usage (Args); end if; declare Param : constant String := Args.Get_Argument (Arg_Pos); Gw : Druss.Gateways.Gateway_Ref; procedure Operation (Gateway : in out Druss.Gateways.Gateway_Type) is begin Process (Gateway, Param); end Operation; begin if Args.Get_Count = Arg_Pos then Druss.Gateways.Iterate (Context.Gateways, Gateways.ITER_ENABLE, Operation'Access); else for I in Arg_Pos + 1 .. Args.Get_Count loop Gw := Druss.Gateways.Find_IP (Context.Gateways, Args.Get_Argument (I)); if not Gw.Is_Null then Operation (Gw.Value.all); end if; end loop; end if; end; end Gateway_Command; procedure Initialize is begin Driver.Set_Description ("Druss - The Bbox master controller"); Driver.Set_Usage ("[-v] [-o file] [-c config] <command> [<args>]" & ASCII.LF & "where:" & ASCII.LF & " -v Verbose execution mode" & ASCII.LF & " -c config Use the configuration file" & " (instead of $HOME/.config/druss/druss.properties)" & ASCII.LF & " -o file The output file to use"); Driver.Add_Command ("help", Help_Command'Access); Driver.Add_Command ("bbox", Bbox_Commands'Access); Driver.Add_Command ("get", Get_Commands'Access); Driver.Add_Command ("wifi", Wifi_Commands'Access); Driver.Add_Command ("status", Status_Commands'Access); Driver.Add_Command ("devices", Device_Commands'Access); Driver.Add_Command ("ping", Ping_Commands'Access); end Initialize; -- ------------------------------ -- Print the bbox API status. -- ------------------------------ procedure Print_Status (Console : in Consoles.Console_Access; Field : in Field_Type; Value : in String) is begin if Value = "2" then Console.Print_Field (Field, "OK"); elsif Value = "-1" then Console.Print_Field (Field, "KO"); elsif Value = "1" then Console.Print_Field (Field, "Starting"); elsif Value = "0" then Console.Print_Field (Field, "Stopped"); else Console.Print_Field (Field, "?"); end if; end Print_Status; -- ------------------------------ -- Print a ON/OFF status. -- ------------------------------ procedure Print_On_Off (Console : in Consoles.Console_Access; Field : in Field_Type; Value : in String) is begin if Value = "1" then Console.Print_Field (Field, "ON"); elsif Value = "0" then Console.Print_Field (Field, "OFF"); else Console.Print_Field (Field, ""); end if; end Print_On_Off; function Uptime_Image (Value : in Natural) return String is D : constant Natural := Value / 86400; R : constant Natural := Value mod 86400; H : constant Natural := R / 3600; M : constant Natural := (R mod 3600) / 60; S : constant Natural := (R mod 3600) mod 60; begin if D > 0 then return Util.Strings.Image (D) & "d" & (if H > 0 then Natural'Image (H) & "h" else "") & (if M > 0 then Natural'Image (M) & "m" else ""); elsif H > 0 then return Util.Strings.Image (H) & "h" & (if M > 0 then Natural'Image (M) & "m" else ""); else return Util.Strings.Image (M) & "m" & Natural'Image (S) & "s"; end if; end Uptime_Image; -- Print a uptime. procedure Print_Uptime (Console : in Consoles.Console_Access; Field : in Field_Type; Value : in String) is begin if Value = "" then Console.Print_Field (Field, Value); else Console.Print_Field (Field, Uptime_Image (Natural'Value (Value))); end if; exception when others => Console.Print_Field (Field, Value); end Print_Uptime; end Druss.Commands;
Add ping and device commands Implement the Print_Uptime procedure
Add ping and device commands Implement the Print_Uptime procedure
Ada
apache-2.0
stcarrez/bbox-ada-api
521328b68c92ad9fbf472f8623fd6ef737306bfb
src/sys/streams/util-streams-buffered-encoders.adb
src/sys/streams/util-streams-buffered-encoders.adb
----------------------------------------------------------------------- -- util-streams-encoders -- Streams with encoding and decoding capabilities -- Copyright (C) 2017, 2018, 2019 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- package body Util.Streams.Buffered.Encoders is -- ----------------------- -- Initialize the stream to write on the given stream. -- An internal buffer is allocated for writing the stream. -- ----------------------- overriding procedure Initialize (Stream : in out Encoder_Stream; Output : access Output_Stream'Class; Size : in Positive) is begin Util.Streams.Buffered.Output_Buffer_Stream (Stream).Initialize (Output, Size); end Initialize; -- ----------------------- -- Close the sink. -- ----------------------- overriding procedure Close (Stream : in out Encoder_Stream) is begin Stream.Flush; Stream.Output.Close; end Close; -- ----------------------- -- Write the buffer array to the output stream. -- ----------------------- overriding procedure Write (Stream : in out Encoder_Stream; Buffer : in Ada.Streams.Stream_Element_Array) is First_Encoded : Ada.Streams.Stream_Element_Offset := Buffer'First; Last_Encoded : Ada.Streams.Stream_Element_Offset; Last_Pos : Ada.Streams.Stream_Element_Offset; begin while First_Encoded <= Buffer'Last loop Stream.Transform.Transform (Data => Buffer (First_Encoded .. Buffer'Last), Into => Stream.Buffer (Stream.Write_Pos .. Stream.Buffer'Last), Last => Last_Pos, Encoded => Last_Encoded); if Last_Encoded < Buffer'Last then Stream.Output.Write (Stream.Buffer (Stream.Buffer'First .. Last_Pos)); Stream.Write_Pos := Stream.Buffer'First; else Stream.Write_Pos := Last_Pos; end if; First_Encoded := Last_Encoded + 1; end loop; end Write; -- ----------------------- -- Flush the buffer by writing on the output stream. -- Raises Data_Error if there is no output stream. -- ----------------------- overriding procedure Flush (Stream : in out Encoder_Stream) is Last_Pos : Ada.Streams.Stream_Element_Offset := Stream.Write_Pos - 1; begin if not Stream.Flushed then Stream.Transform.Finish (Stream.Buffer (Stream.Write_Pos .. Stream.Buffer'Last), Last_Pos); Stream.Write_Pos := Last_Pos; Output_Buffer_Stream (Stream).Flush; Stream.Flushed := True; end if; end Flush; end Util.Streams.Buffered.Encoders;
----------------------------------------------------------------------- -- util-streams-encoders -- Streams with encoding and decoding capabilities -- Copyright (C) 2017, 2018, 2019 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- package body Util.Streams.Buffered.Encoders is -- ----------------------- -- Initialize the stream to write on the given stream. -- An internal buffer is allocated for writing the stream. -- ----------------------- overriding procedure Initialize (Stream : in out Encoder_Stream; Output : access Output_Stream'Class; Size : in Positive) is begin Util.Streams.Buffered.Output_Buffer_Stream (Stream).Initialize (Output, Size); end Initialize; -- ----------------------- -- Close the sink. -- ----------------------- overriding procedure Close (Stream : in out Encoder_Stream) is begin Stream.Flush; Stream.Output.Close; end Close; -- ----------------------- -- Write the buffer array to the output stream. -- ----------------------- overriding procedure Write (Stream : in out Encoder_Stream; Buffer : in Ada.Streams.Stream_Element_Array) is First_Encoded : Ada.Streams.Stream_Element_Offset := Buffer'First; Last_Encoded : Ada.Streams.Stream_Element_Offset; Last_Pos : Ada.Streams.Stream_Element_Offset; begin while First_Encoded <= Buffer'Last loop Stream.Transform.Transform (Data => Buffer (First_Encoded .. Buffer'Last), Into => Stream.Buffer (Stream.Write_Pos .. Stream.Buffer'Last), Last => Last_Pos, Encoded => Last_Encoded); if Last_Encoded < Buffer'Last then Stream.Output.Write (Stream.Buffer (Stream.Buffer'First .. Last_Pos)); Stream.Write_Pos := Stream.Buffer'First; else Stream.Write_Pos := Last_Pos + 1; end if; First_Encoded := Last_Encoded + 1; end loop; end Write; -- ----------------------- -- Flush the buffer by writing on the output stream. -- Raises Data_Error if there is no output stream. -- ----------------------- overriding procedure Flush (Stream : in out Encoder_Stream) is Last_Pos : Ada.Streams.Stream_Element_Offset := Stream.Write_Pos - 1; begin if not Stream.Flushed then Stream.Transform.Finish (Stream.Buffer (Stream.Write_Pos .. Stream.Buffer'Last), Last_Pos); Stream.Write_Pos := Last_Pos + 1; Output_Buffer_Stream (Stream).Flush; Stream.Flushed := True; end if; end Flush; end Util.Streams.Buffered.Encoders;
Fix Flush and Write operations (regression introduced by commit 6857c1b9)
Fix Flush and Write operations (regression introduced by commit 6857c1b9)
Ada
apache-2.0
stcarrez/ada-util,stcarrez/ada-util
73ed2793da02250e43e6cb6c45bc01b460693d55
awa/src/awa-events.adb
awa/src/awa-events.adb
----------------------------------------------------------------------- -- awa-events -- AWA Events -- Copyright (C) 2012 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Strings.Unbounded; with Ada.Unchecked_Deallocation; with Util.Log.Loggers; with EL.Contexts; with EL.Contexts.Default; with EL.Variables; with EL.Variables.Default; with ASF.Beans; with ASF.Requests; with ASF.Sessions; with ADO.SQL; -- with AWA.Events.Action_Method; with AWA.Applications; package body AWA.Events is use Ada.Strings.Unbounded; use Util.Log; Log : constant Loggers.Logger := Loggers.Create ("AWA.Events"); type Event_Name_Pair is record Name : Util.Strings.Name_Access := null; Index : Event_Index := 0; end record; type Event_Name_Pair_Array is array (Event_Index range <>) of Event_Name_Pair; type Event_Name_Pair_Array_Access is access all Event_Name_Pair_Array; -- A static list of event names. This array is created during the elaboration -- of event definitions. It is sorted on event names. Events : Event_Name_Pair_Array_Access; -- ------------------------------ -- Register an event by its name and allocate a unique runtime event index. -- ------------------------------ procedure Add_Event (Name : in Util.Strings.Name_Access; Index : out Event_Index) is Left : Event_Index := 1; Right : Event_Index := Last_Event; begin -- Check the storage and allocate it if necessary. if Events = null then Events := new Event_Name_Pair_Array (1 .. 10); elsif Events'Last = Last_Event then declare N : Event_Name_Pair_Array_Access := new Event_Name_Pair_Array (1 .. Last_Event + 10); begin N (Events'Range) := Events.all; end; end if; -- Find the event position within the sorted table. -- If an event is already registered, bark and re-use the previous event identifier. while Left <= Right loop declare Pos : constant Event_Index := (Left + Right + 1) / 2; Item : constant Util.Strings.Name_Access := Events (Pos).Name; begin if Name.all = Item.all then Log.Error ("Event {0} is already registered.", Name.all); Index := Events (Pos).Index; return; elsif Name.all < Item.all then Right := Pos - 1; else Left := Pos + 1; end if; end; end loop; -- Insert the new event at the good position now. if Left = 0 then Left := Left + 1; end if; if Left <= Last_Event then Events (Left + 1 .. Last_Event + 1) := Events (Left .. Last_Event); end if; Last_Event := Last_Event + 1; Events (Left).Name := Name; Events (Left).Index := Last_Event; Index := Last_Event; -- for I in 1 .. Last_Event loop -- Log.Info ("{0} -> {1}", Event_Index'Image (I), Events (I).Name.all); -- end loop; Log.Debug ("Event {0} index is {1}", Name.all, Event_Index'Image (Index)); end Add_Event; -- ------------------------------ -- Event kind definition -- ------------------------------ package body Definition is Event : Event_Index; Event_Name : aliased constant String := Name; function Kind return Event_Index is begin return Event; end Kind; begin Add_Event (Event_Name'Access, Event); end Definition; -- ------------------------------ -- Find the event runtime index given the event name. -- Raises Not_Found exception if the event name is not recognized. -- ------------------------------ function Find_Event_Index (Name : in String) return Event_Index is Left : Event_Index := 1; Right : Event_Index := Last_Event; begin while Left <= Right loop declare Pos : constant Event_Index := (Left + Right + 1) / 2; Item : constant Util.Strings.Name_Access := Events (Pos).Name; begin if Name = Item.all then return Events (Pos).Index; elsif Name < Item.all then Right := Pos - 1; else Left := Pos + 1; end if; end; end loop; Log.Error ("Event {0} not recognized.", Name); raise Not_Found with "Event " & Name & " not found"; end Find_Event_Index; -- ------------------------------ -- Set the event type which identifies the event. -- ------------------------------ procedure Set_Event_Kind (Event : in out Module_Event; Kind : in Event_Index) is begin Event.Kind := Kind; end Set_Event_Kind; -- ------------------------------ -- Get the event type which identifies the event. -- ------------------------------ function Get_Event_Kind (Event : in Module_Event) return Event_Index is begin return Event.Kind; end Get_Event_Kind; -- ------------------------------ -- Set a parameter on the message. -- ------------------------------ procedure Set_Parameter (Event : in out Module_Event; Name : in String; Value : in String) is begin Event.Props.Set (Name, Value); end Set_Parameter; -- ------------------------------ -- Get the parameter with the given name. -- ------------------------------ function Get_Parameter (Event : in Module_Event; Name : in String) return String is begin return Event.Props.Get (Name, ""); end Get_Parameter; -- ------------------------------ -- Get the value that corresponds to the parameter with the given name. -- ------------------------------ function Get_Value (Event : in Module_Event; Name : in String) return Util.Beans.Objects.Object is begin if Event.Props.Exists (Name) then return Util.Beans.Objects.To_Object (Event.Get_Parameter (Name)); else return Util.Beans.Objects.Null_Object; end if; end Get_Value; -- ------------------------------ -- Get the event type name. -- ------------------------------ function Get_Event_Type_Name (Index : in Event_Index) return Util.Strings.Name_Access is begin return Events (Index).Name; end Get_Event_Type_Name; end AWA.Events;
----------------------------------------------------------------------- -- awa-events -- AWA Events -- Copyright (C) 2012 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Unchecked_Deallocation; with Util.Log.Loggers; package body AWA.Events is use Util.Log; Log : constant Loggers.Logger := Loggers.Create ("AWA.Events"); type Event_Name_Pair is record Name : Util.Strings.Name_Access := null; Index : Event_Index := 0; end record; type Event_Name_Pair_Array is array (Event_Index range <>) of Event_Name_Pair; type Event_Name_Pair_Array_Access is access all Event_Name_Pair_Array; type Name_Array is array (Event_Index range <>) of Util.Strings.Name_Access; type Name_Array_Access is access all Name_Array; -- A static list of event names. This array is created during the elaboration -- of event definitions. It is sorted on event names. Events : Event_Name_Pair_Array_Access; -- A static list of event names indexed by the event index. Names : Name_Array_Access; -- ------------------------------ -- Register an event by its name and allocate a unique runtime event index. -- ------------------------------ procedure Add_Event (Name : in Util.Strings.Name_Access; Index : out Event_Index) is procedure Free is new Ada.Unchecked_Deallocation (Object => Event_Name_Pair_Array, Name => Event_Name_Pair_Array_Access); procedure Free is new Ada.Unchecked_Deallocation (Object => Name_Array, Name => Name_Array_Access); Left : Event_Index := 1; Right : Event_Index := Last_Event; begin -- Check the storage and allocate it if necessary. if Events = null then Events := new Event_Name_Pair_Array (1 .. 10); Names := new Name_Array (1 .. 10); elsif Events'Last = Last_Event then declare E : Event_Name_Pair_Array_Access := new Event_Name_Pair_Array (1 .. Last_Event + 10); N : Name_Array_Access := new Name_Array (1 .. Last_Event + 10); begin E (Events'Range) := Events.all; N (Names'Range) := Names.all; Free (Events); Free (Names); Names := N; Events := E; end; end if; -- Find the event position within the sorted table. -- If an event is already registered, bark and re-use the previous event identifier. while Left <= Right loop declare Pos : constant Event_Index := (Left + Right + 1) / 2; Item : constant Util.Strings.Name_Access := Events (Pos).Name; begin if Name.all = Item.all then Log.Error ("Event {0} is already registered.", Name.all); Index := Events (Pos).Index; return; elsif Name.all < Item.all then Right := Pos - 1; else Left := Pos + 1; end if; end; end loop; -- Insert the new event at the good position now. if Left = 0 then Left := Left + 1; end if; if Left <= Last_Event then Events (Left + 1 .. Last_Event + 1) := Events (Left .. Last_Event); end if; Last_Event := Last_Event + 1; Events (Left).Name := Name; Events (Left).Index := Last_Event; Names (Last_Event) := Name; Index := Last_Event; -- for I in 1 .. Last_Event loop -- Log.Info ("{0} -> {1}", Event_Index'Image (I), Events (I).Name.all); -- end loop; Log.Debug ("Event {0} index is {1}", Name.all, Event_Index'Image (Index)); end Add_Event; -- ------------------------------ -- Event kind definition -- ------------------------------ package body Definition is Event : Event_Index; Event_Name : aliased constant String := Name; function Kind return Event_Index is begin return Event; end Kind; begin Add_Event (Event_Name'Access, Event); end Definition; -- ------------------------------ -- Find the event runtime index given the event name. -- Raises Not_Found exception if the event name is not recognized. -- ------------------------------ function Find_Event_Index (Name : in String) return Event_Index is Left : Event_Index := 1; Right : Event_Index := Last_Event; begin while Left <= Right loop declare Pos : constant Event_Index := (Left + Right + 1) / 2; Item : constant Util.Strings.Name_Access := Events (Pos).Name; begin if Name = Item.all then return Events (Pos).Index; elsif Name < Item.all then Right := Pos - 1; else Left := Pos + 1; end if; end; end loop; Log.Error ("Event {0} not recognized.", Name); raise Not_Found with "Event " & Name & " not found"; end Find_Event_Index; -- ------------------------------ -- Set the event type which identifies the event. -- ------------------------------ procedure Set_Event_Kind (Event : in out Module_Event; Kind : in Event_Index) is begin Event.Kind := Kind; end Set_Event_Kind; -- ------------------------------ -- Get the event type which identifies the event. -- ------------------------------ function Get_Event_Kind (Event : in Module_Event) return Event_Index is begin return Event.Kind; end Get_Event_Kind; -- ------------------------------ -- Set a parameter on the message. -- ------------------------------ procedure Set_Parameter (Event : in out Module_Event; Name : in String; Value : in String) is begin Event.Props.Set (Name, Value); end Set_Parameter; -- ------------------------------ -- Get the parameter with the given name. -- ------------------------------ function Get_Parameter (Event : in Module_Event; Name : in String) return String is begin return Event.Props.Get (Name, ""); end Get_Parameter; -- ------------------------------ -- Get the value that corresponds to the parameter with the given name. -- ------------------------------ function Get_Value (Event : in Module_Event; Name : in String) return Util.Beans.Objects.Object is begin if Event.Props.Exists (Name) then return Util.Beans.Objects.To_Object (Event.Get_Parameter (Name)); else return Util.Beans.Objects.Null_Object; end if; end Get_Value; -- ------------------------------ -- Get the event type name. -- ------------------------------ function Get_Event_Type_Name (Index : in Event_Index) return Util.Strings.Name_Access is begin return Names (Index); end Get_Event_Type_Name; end AWA.Events;
Fix Get_Event_Type_Name so that it returns the good event name
Fix Get_Event_Type_Name so that it returns the good event name
Ada
apache-2.0
tectronics/ada-awa,tectronics/ada-awa,Letractively/ada-awa,Letractively/ada-awa,tectronics/ada-awa,Letractively/ada-awa
93c373907a5be762a179dad62c77f721f1f790b1
awa/src/awa-events.ads
awa/src/awa-events.ads
----------------------------------------------------------------------- -- awa-events -- AWA Events -- 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 Util.Strings; with Util.Events; with Util.Beans.Objects; with Util.Beans.Basic; with Util.Beans.Objects.Maps; with ADO; with AWA.Index_Arrays; -- == Introduction == -- The <b>AWA.Events</b> package defines an event framework for modules to post events -- and have Ada bean methods be invoked when these events are dispatched. Subscription to -- events is done through configuration files. This allows to configure the modules and -- integrate them together easily at configuration time. -- -- === Declaration === -- Modules define the events that they can generate by instantiating the <b>Definition</b> -- package. This is a static definition of the event. Each event is given a unique name. -- -- package Event_New_User is new AWA.Events.Definition ("new-user"); -- -- === Posting an event === -- The module can post an event to inform other modules or the system that a particular -- action occurred. The module creates the event instance of type <b>Module_Event</b> and -- populates that event with useful properties for event receivers. -- -- Event : AWA.Events.Module_Event; -- -- Event.Set_Event_Kind (Event_New_User.Kind); -- Event.Set_Parameter ("email", "[email protected]"); -- -- The module will post the event by using the <b>Send_Event</b> operation. -- -- Manager.Send_Event (Event); -- -- === Receiving an event === -- Modules or applications interested by a particular event will configure the event manager -- to dispatch the event to an Ada bean event action. The Ada bean is an object that must -- implement a procedure that matches the prototype: -- -- type Action_Bean is new Util.Beans.Basic.Readonly_Bean ...; -- procedure Action (Bean : in out Action_Bean; Event : in AWA.Events.Module_Event'Class); -- -- The Ada bean method and object are registered as other Ada beans. -- -- The configuration file indicates how to bind the Ada bean action and the event together. -- The action is specified using an EL Method Expression (See Ada EL or JSR 245). -- -- <on-event name="new_user"> -- <action>#{ada_bean.action}</action> -- </on-event> -- -- === Event queues and dispatchers === -- The *AWA.Events* framework posts events on queues and it uses a dispatcher to process them. -- There are two kinds of dispatchers: -- -- * Synchronous dispatcher process the event when it is posted. The task which posts -- the event invokes the Ada bean action. In this dispatching mode, there is no event queue. -- If the action method raises an exception, it will however be blocked. -- -- * Asynchronous dispatcher are executed by dedicated tasks. The event is put in an event -- queue. A dispatcher task processes the event and invokes the action method at a later -- time. -- -- When the event is queued, there are two types of event queues: -- -- * A Fifo memory queue manages the event and dispatches them in FIFO order. -- If the application is stopped, the events present in the Fifo queue are lost. -- -- * A persistent event queue manages the event in a similar way as the FIFO queue but -- saves them in the database. If the application is stopped, events that have not yet -- been processed will be dispatched when the application is started again. -- -- == Data Model == -- @include Queues.hbm.xml -- package AWA.Events is type Queue_Index is new Natural; type Event_Index is new Natural; package Event_Arrays is new AWA.Index_Arrays (Event_Index, String); use type Event_Arrays.Element_Type_Access; subtype Name_Access is Event_Arrays.Element_Type_Access; generic package Definition renames Event_Arrays.Definition; -- Exception raised if an event name is not found. Not_Found : exception renames Event_Arrays.Not_Found; -- Identifies an invalid event. -- Invalid_Event : constant Event_Index := 0; -- Find the event runtime index given the event name. -- Raises Not_Found exception if the event name is not recognized. function Find_Event_Index (Name : in String) return Event_Index renames Event_Arrays.Find; -- ------------------------------ -- Module event -- ------------------------------ type Module_Event is new Util.Events.Event and Util.Beans.Basic.Readonly_Bean with private; type Module_Event_Access is access all Module_Event'Class; -- Set the event type which identifies the event. procedure Set_Event_Kind (Event : in out Module_Event; Kind : in Event_Index); -- Get the event type which identifies the event. function Get_Event_Kind (Event : in Module_Event) return Event_Index; -- Set a parameter on the message. procedure Set_Parameter (Event : in out Module_Event; Name : in String; Value : in String); -- Get the parameter with the given name. function Get_Parameter (Event : in Module_Event; Name : in String) return String; -- Get the value that corresponds to the parameter with the given name. overriding function Get_Value (Event : in Module_Event; Name : in String) return Util.Beans.Objects.Object; -- Get the entity identifier associated with the event. function Get_Entity_Identifier (Event : in Module_Event) return ADO.Identifier; -- Set the entity identifier associated with the event. procedure Set_Entity_Identifier (Event : in out Module_Event; Id : in ADO.Identifier); -- Copy the event properties to the map passed in <tt>Into</tt>. procedure Copy (Event : in Module_Event; Into : in out Util.Beans.Objects.Maps.Map); private type Module_Event is new Util.Events.Event and Util.Beans.Basic.Readonly_Bean with record Kind : Event_Index := Event_Arrays.Invalid_Index; Props : Util.Beans.Objects.Maps.Map; Entity : ADO.Identifier := ADO.NO_IDENTIFIER; Entity_Type : ADO.Entity_Type := ADO.NO_ENTITY_TYPE; end record; -- The index of the last event definition. -- Last_Event : Event_Index := 0; -- Get the event type name. function Get_Event_Type_Name (Index : in Event_Index) return Name_Access renames Event_Arrays.Get_Element; -- Make and return a copy of the event. function Copy (Event : in Module_Event) return Module_Event_Access; end AWA.Events;
----------------------------------------------------------------------- -- awa-events -- AWA Events -- Copyright (C) 2012, 2015 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Strings; with Util.Events; with Util.Beans.Objects; with Util.Beans.Basic; with Util.Beans.Objects.Maps; with ADO; with AWA.Index_Arrays; -- == Introduction == -- The <b>AWA.Events</b> package defines an event framework for modules to post events -- and have Ada bean methods be invoked when these events are dispatched. Subscription to -- events is done through configuration files. This allows to configure the modules and -- integrate them together easily at configuration time. -- -- === Declaration === -- Modules define the events that they can generate by instantiating the <b>Definition</b> -- package. This is a static definition of the event. Each event is given a unique name. -- -- with AWA.Events.Definition; -- ... -- package Event_New_User is new AWA.Events.Definition ("new-user"); -- -- === Posting an event === -- The module can post an event to inform other modules or the system that a particular -- action occurred. The module creates the event instance of type <b>Module_Event</b> and -- populates that event with useful properties for event receivers. -- -- with AWA.Events; -- ... -- Event : AWA.Events.Module_Event; -- -- Event.Set_Event_Kind (Event_New_User.Kind); -- Event.Set_Parameter ("email", "[email protected]"); -- -- The module will post the event by using the <b>Send_Event</b> operation. -- -- Manager.Send_Event (Event); -- -- === Receiving an event === -- Modules or applications interested by a particular event will configure the event manager -- to dispatch the event to an Ada bean event action. The Ada bean is an object that must -- implement a procedure that matches the prototype: -- -- type Action_Bean is new Util.Beans.Basic.Readonly_Bean ...; -- procedure Action (Bean : in out Action_Bean; Event : in AWA.Events.Module_Event'Class); -- -- The Ada bean method and object are registered as other Ada beans. -- -- The configuration file indicates how to bind the Ada bean action and the event together. -- The action is specified using an EL Method Expression (See Ada EL or JSR 245). -- -- <on-event name="new_user"> -- <action>#{ada_bean.action}</action> -- </on-event> -- -- === Event queues and dispatchers === -- The *AWA.Events* framework posts events on queues and it uses a dispatcher to process them. -- There are two kinds of dispatchers: -- -- * Synchronous dispatcher process the event when it is posted. The task which posts -- the event invokes the Ada bean action. In this dispatching mode, there is no event queue. -- If the action method raises an exception, it will however be blocked. -- -- * Asynchronous dispatcher are executed by dedicated tasks. The event is put in an event -- queue. A dispatcher task processes the event and invokes the action method at a later -- time. -- -- When the event is queued, there are two types of event queues: -- -- * A Fifo memory queue manages the event and dispatches them in FIFO order. -- If the application is stopped, the events present in the Fifo queue are lost. -- -- * A persistent event queue manages the event in a similar way as the FIFO queue but -- saves them in the database. If the application is stopped, events that have not yet -- been processed will be dispatched when the application is started again. -- -- == Data Model == -- [images/awa_events_model.png] -- package AWA.Events is type Queue_Index is new Natural; type Event_Index is new Natural; package Event_Arrays is new AWA.Index_Arrays (Event_Index, String); use type Event_Arrays.Element_Type_Access; subtype Name_Access is Event_Arrays.Element_Type_Access; generic package Definition renames Event_Arrays.Definition; -- Exception raised if an event name is not found. Not_Found : exception renames Event_Arrays.Not_Found; -- Identifies an invalid event. -- Invalid_Event : constant Event_Index := 0; -- Find the event runtime index given the event name. -- Raises Not_Found exception if the event name is not recognized. function Find_Event_Index (Name : in String) return Event_Index renames Event_Arrays.Find; -- ------------------------------ -- Module event -- ------------------------------ type Module_Event is new Util.Events.Event and Util.Beans.Basic.Readonly_Bean with private; type Module_Event_Access is access all Module_Event'Class; -- Set the event type which identifies the event. procedure Set_Event_Kind (Event : in out Module_Event; Kind : in Event_Index); -- Get the event type which identifies the event. function Get_Event_Kind (Event : in Module_Event) return Event_Index; -- Set a parameter on the message. procedure Set_Parameter (Event : in out Module_Event; Name : in String; Value : in String); -- Get the parameter with the given name. function Get_Parameter (Event : in Module_Event; Name : in String) return String; -- Get the value that corresponds to the parameter with the given name. overriding function Get_Value (Event : in Module_Event; Name : in String) return Util.Beans.Objects.Object; -- Get the entity identifier associated with the event. function Get_Entity_Identifier (Event : in Module_Event) return ADO.Identifier; -- Set the entity identifier associated with the event. procedure Set_Entity_Identifier (Event : in out Module_Event; Id : in ADO.Identifier); -- Copy the event properties to the map passed in <tt>Into</tt>. procedure Copy (Event : in Module_Event; Into : in out Util.Beans.Objects.Maps.Map); private type Module_Event is new Util.Events.Event and Util.Beans.Basic.Readonly_Bean with record Kind : Event_Index := Event_Arrays.Invalid_Index; Props : Util.Beans.Objects.Maps.Map; Entity : ADO.Identifier := ADO.NO_IDENTIFIER; Entity_Type : ADO.Entity_Type := ADO.NO_ENTITY_TYPE; end record; -- The index of the last event definition. -- Last_Event : Event_Index := 0; -- Get the event type name. function Get_Event_Type_Name (Index : in Event_Index) return Name_Access renames Event_Arrays.Get_Element; -- Make and return a copy of the event. function Copy (Event : in Module_Event) return Module_Event_Access; end AWA.Events;
Update the documentation
Update the documentation
Ada
apache-2.0
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
b5118f76311b43ab7e7b9ccdb98717f44e4cb938
src/gen-commands-layout.adb
src/gen-commands-layout.adb
----------------------------------------------------------------------- -- gen-commands-layout -- Layout 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.Text_IO; with Gen.Artifacts; with Util.Strings; with Util.Files; package body Gen.Commands.Layout 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_Name return String; Dir : constant String := Generator.Get_Result_Directory; Layout_Dir : constant String := Util.Files.Compose (Dir, "web/WEB-INF/layouts"); function Get_Name return String is Name : constant String := (if Args.Get_Count > 0 then Args.Get_Argument (1) else ""); 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; Page_Name : constant String := Get_Name; begin if Page_Name'Length = 0 then Gen.Commands.Usage; return; end if; Generator.Set_Force_Save (False); Generator.Set_Result_Directory (Layout_Dir); Generator.Set_Global ("pageName", Page_Name); Gen.Generator.Generate_All (Generator, Gen.Artifacts.ITERATION_TABLE, "layout"); 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 ("add-layout: Add a new layout page to the application"); Put_Line ("Usage: add-layout NAME"); New_Line; Put_Line (" The layout page allows to give a common look to a set of pages."); Put_Line (" You can create several layouts for your application."); Put_Line (" Each layout can reference one or several building blocks that are defined"); Put_Line (" in the original page."); New_Line; Put_Line (" The following files are generated:"); Put_Line (" web/WEB-INF/layouts/<name>.xhtml"); end Help; end Gen.Commands.Layout;
----------------------------------------------------------------------- -- gen-commands-layout -- Layout creation command for dynamo -- Copyright (C) 2011, 2012, 2013, 2014, 2017 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Text_IO; with Gen.Artifacts; with Util.Strings; with Util.Files; package body Gen.Commands.Layout 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 (Name); use Ada.Strings.Unbounded; function Get_Name return String; Dir : constant String := Generator.Get_Result_Directory; Layout_Dir : constant String := Util.Files.Compose (Dir, "web/WEB-INF/layouts"); function Get_Name return String is Name : constant String := (if Args.Get_Count > 0 then Args.Get_Argument (1) else ""); 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; Page_Name : constant String := Get_Name; begin if Page_Name'Length = 0 then Cmd.Usage; return; end if; Generator.Set_Force_Save (False); Generator.Set_Result_Directory (Layout_Dir); Generator.Set_Global ("pageName", Page_Name); Gen.Generator.Generate_All (Generator, Gen.Artifacts.ITERATION_TABLE, "layout"); 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 ("add-layout: Add a new layout page to the application"); Put_Line ("Usage: add-layout NAME"); New_Line; Put_Line (" The layout page allows to give a common look to a set of pages."); Put_Line (" You can create several layouts for your application."); Put_Line (" Each layout can reference one or several building blocks that are defined"); Put_Line (" in the original page."); New_Line; Put_Line (" The following files are generated:"); Put_Line (" web/WEB-INF/layouts/<name>.xhtml"); end Help; end Gen.Commands.Layout;
Use the command usage procedure to report the program usage
Use the command usage procedure to report the program usage
Ada
apache-2.0
stcarrez/dynamo,stcarrez/dynamo,stcarrez/dynamo
5e6f9a75452283b64769b2a0c61f663ccf04785e
src/asf-validators-texts.adb
src/asf-validators-texts.adb
----------------------------------------------------------------------- -- asf-validators-texts -- ASF Texts Validators -- 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. ----------------------------------------------------------------------- -- The <b>ASF.Validators.Texts</b> defines various text oriented validators. package body ASF.Validators.Texts is -- ------------------------------ -- Length_Validator -- ------------------------------ -- ------------------------------ -- Create a length validator. -- ------------------------------ function Create_Length_Validator (Minimum : in Natural; Maximum : in Natural) return Validator_Access is Result : constant Length_Validator_Access := new Length_Validator; begin Result.Minimum := Minimum; Result.Maximum := Maximum; return Result.all'Access; end Create_Length_Validator; -- ------------------------------ -- Verify that the value's length is between the validator minimum and maximum -- boundaries. -- If some error are found, the procedure should create a <b>FacesMessage</b> -- describing the problem and add that message to the current faces context. -- The procedure can examine the state and modify the component tree. -- It must raise the <b>Invalid_Value</b> exception if the value is not valid. -- ------------------------------ procedure Validate (Valid : in Length_Validator; Context : in out ASF.Contexts.Faces.Faces_Context'Class; Component : in out ASF.Components.Base.UIComponent'Class; Value : in EL.Objects.Object) is begin if EL.Objects.Is_Null (Value) then return; end if; declare S : constant String := EL.Objects.To_String (Value); begin if S'Length > Valid.Maximum then Component.Add_Message (Name => "validatorMessage", Default => MAXIMUM_MESSAGE_ID, Context => Context); raise Invalid_Value; end if; if S'Length < Valid.Minimum then Component.Add_Message (Name => "validatorMessage", Default => MINIMUM_MESSAGE_ID, Context => Context); raise Invalid_Value; end if; end; end Validate; end ASF.Validators.Texts;
----------------------------------------------------------------------- -- asf-validators-texts -- ASF Texts Validators -- 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.Beans.Objects; -- The <b>ASF.Validators.Texts</b> defines various text oriented validators. package body ASF.Validators.Texts is -- ------------------------------ -- Length_Validator -- ------------------------------ -- ------------------------------ -- Create a length validator. -- ------------------------------ function Create_Length_Validator (Minimum : in Natural; Maximum : in Natural) return Validator_Access is Result : constant Length_Validator_Access := new Length_Validator; begin Result.Minimum := Minimum; Result.Maximum := Maximum; return Result.all'Access; end Create_Length_Validator; -- ------------------------------ -- Verify that the value's length is between the validator minimum and maximum -- boundaries. -- If some error are found, the procedure should create a <b>FacesMessage</b> -- describing the problem and add that message to the current faces context. -- The procedure can examine the state and modify the component tree. -- It must raise the <b>Invalid_Value</b> exception if the value is not valid. -- ------------------------------ procedure Validate (Valid : in Length_Validator; Context : in out ASF.Contexts.Faces.Faces_Context'Class; Component : in out ASF.Components.Base.UIComponent'Class; Value : in EL.Objects.Object) is begin if EL.Objects.Is_Null (Value) then return; end if; declare S : constant String := EL.Objects.To_String (Value); begin if S'Length > Valid.Maximum then Component.Add_Message (Name => ASF.Components.VALIDATOR_MESSAGE_NAME, Default => MAXIMUM_MESSAGE_ID, Arg1 => Util.Beans.Objects.To_Object (Valid.Maximum), Arg2 => Component.Get_Label (Context), Context => Context); raise Invalid_Value; end if; if S'Length < Valid.Minimum then Component.Add_Message (Name => ASF.Components.VALIDATOR_MESSAGE_NAME, Default => MINIMUM_MESSAGE_ID, Arg1 => Util.Beans.Objects.To_Object (Valid.Minimum), Arg2 => Component.Get_Label (Context), Context => Context); raise Invalid_Value; end if; end; end Validate; end ASF.Validators.Texts;
Add a message when the validation fails
Add a message when the validation fails
Ada
apache-2.0
stcarrez/ada-asf,stcarrez/ada-asf,stcarrez/ada-asf
c7acddbe3c94a89f889e321461c80203aeceb047
src/gen-model-operations.ads
src/gen-model-operations.ads
----------------------------------------------------------------------- -- gen-model-operations -- Operation declarations -- Copyright (C) 2012 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Strings.Unbounded; with Util.Beans.Objects; with Gen.Model.List; package Gen.Model.Operations is use Ada.Strings.Unbounded; -- ------------------------------ -- Parameter Definition -- ------------------------------ type Parameter_Definition is new Definition with private; type Parameter_Definition_Access is access all Parameter_Definition'Class; -- ------------------------------ -- Operation Definition -- ------------------------------ type Operation_Definition is new Definition with private; type Operation_Definition_Access is access all Operation_Definition'Class; -- Get the value identified by the name. -- If the name cannot be found, the method should return the Null object. overriding function Get_Value (From : in Operation_Definition; Name : in String) return Util.Beans.Objects.Object; -- Prepare the generation of the model. overriding procedure Prepare (O : in out Operation_Definition); -- Initialize the operation definition instance. overriding procedure Initialize (O : in out Operation_Definition); -- Add an operation parameter with the given name and type. procedure Add_Parameter (Into : in out Operation_Definition; Name : in Unbounded_String; Of_Type : in Unbounded_String; Parameter : out Parameter_Definition_Access); -- Create an operation with the given name. function Create_Operation (Name : in Unbounded_String) return Operation_Definition_Access; private type Parameter_Definition is new Definition with record -- The parameter type name. Type_Name : Unbounded_String; end record; package Parameter_List is new Gen.Model.List (T => Parameter_Definition, T_Access => Parameter_Definition_Access); type Operation_Definition is new Definition with record Parameters : aliased Parameter_List.List_Definition; Parameters_Bean : Util.Beans.Objects.Object; Return_Type : Unbounded_String; end record; end Gen.Model.Operations;
----------------------------------------------------------------------- -- gen-model-operations -- Operation declarations -- 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 Util.Beans.Objects; with Gen.Model.List; package Gen.Model.Operations is use Ada.Strings.Unbounded; type Operation_Type is (UNKNOWN, ASF_ACTION, ASF_UPLOAD); -- ------------------------------ -- Parameter Definition -- ------------------------------ type Parameter_Definition is new Definition with private; type Parameter_Definition_Access is access all Parameter_Definition'Class; -- ------------------------------ -- Operation Definition -- ------------------------------ type Operation_Definition is new Definition with private; type Operation_Definition_Access is access all Operation_Definition'Class; -- Get the value identified by the name. -- If the name cannot be found, the method should return the Null object. overriding function Get_Value (From : in Operation_Definition; Name : in String) return Util.Beans.Objects.Object; -- Prepare the generation of the model. overriding procedure Prepare (O : in out Operation_Definition); -- Initialize the operation definition instance. overriding procedure Initialize (O : in out Operation_Definition); -- Add an operation parameter with the given name and type. procedure Add_Parameter (Into : in out Operation_Definition; Name : in Unbounded_String; Of_Type : in Unbounded_String; Parameter : out Parameter_Definition_Access); -- Get the operation type. function Get_Type (From : in Operation_Definition) return Operation_Type; -- Create an operation with the given name. function Create_Operation (Name : in Unbounded_String) return Operation_Definition_Access; private type Parameter_Definition is new Definition with record -- The parameter type name. Type_Name : Unbounded_String; end record; package Parameter_List is new Gen.Model.List (T => Parameter_Definition, T_Access => Parameter_Definition_Access); type Operation_Definition is new Definition with record Parameters : aliased Parameter_List.List_Definition; Parameters_Bean : Util.Beans.Objects.Object; Return_Type : Unbounded_String; Kind : Operation_Type := UNKNOWN; end record; end Gen.Model.Operations;
Define Operation_Type type and add an attribute of that type for each operation Declare the Get_Type operation
Define Operation_Type type and add an attribute of that type for each operation Declare the Get_Type operation
Ada
apache-2.0
stcarrez/dynamo,stcarrez/dynamo,stcarrez/dynamo
783b92e31157e021783664991218668c21603999
awa/plugins/awa-images/src/awa-images-modules.adb
awa/plugins/awa-images/src/awa-images-modules.adb
----------------------------------------------------------------------- -- awa-images-modules -- Image management module -- Copyright (C) 2012, 2016 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Strings.Unbounded; with Util.Processes; with Util.Beans.Objects; with Util.Log.Loggers; with Util.Streams.Pipes; with Util.Streams.Texts; with Util.Strings; with ADO.Sessions; with EL.Variables.Default; with EL.Contexts.Default; with AWA.Modules.Get; with AWA.Applications; with AWA.Storages.Modules; with AWA.Services.Contexts; with AWA.Modules.Beans; with AWA.Images.Beans; package body AWA.Images.Modules is package ASC renames AWA.Services.Contexts; Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("AWA.Images.Module"); package Register is new AWA.Modules.Beans (Module => Image_Module, Module_Access => Image_Module_Access); -- ------------------------------ -- Job worker procedure to identify an image and generate its thumnbnail. -- ------------------------------ procedure Thumbnail_Worker (Job : in out AWA.Jobs.Services.Abstract_Job_Type'Class) is Module : constant Image_Module_Access := Get_Image_Module; begin Module.Do_Thumbnail_Job (Job); end Thumbnail_Worker; -- ------------------------------ -- Initialize the image module. -- ------------------------------ overriding procedure Initialize (Plugin : in out Image_Module; App : in AWA.Modules.Application_Access; Props : in ASF.Applications.Config) is begin Log.Info ("Initializing the image module"); -- Setup the resource bundles. App.Register ("imageMsg", "images"); Register.Register (Plugin => Plugin, Name => "AWA.Images.Beans.Image_List_Bean", Handler => AWA.Images.Beans.Create_Image_List_Bean'Access); Register.Register (Plugin => Plugin, Name => "AWA.Images.Beans.Image_Bean", Handler => AWA.Images.Beans.Create_Image_Bean'Access); App.Add_Servlet ("image", Plugin.Image_Servlet'Unchecked_Access); AWA.Modules.Module (Plugin).Initialize (App, Props); Plugin.Add_Listener (AWA.Storages.Modules.NAME, Plugin'Unchecked_Access); end Initialize; -- ------------------------------ -- Configures the module after its initialization and after having read its XML configuration. -- ------------------------------ overriding procedure Configure (Plugin : in out Image_Module; Props : in ASF.Applications.Config) is pragma Unreferenced (Props); use type AWA.Jobs.Modules.Job_Module_Access; begin Plugin.Job_Module := AWA.Jobs.Modules.Get_Job_Module; if Plugin.Job_Module = null then Log.Error ("Cannot find the AWA Job module for the image thumbnail generation"); else Plugin.Job_Module.Register (Definition => Thumbnail_Job_Definition.Factory); end if; Plugin.Thumbnail_Command := Plugin.Get_Config (PARAM_THUMBNAIL_COMMAND); end Configure; -- ------------------------------ -- Create a thumbnail job for the image. -- ------------------------------ procedure Make_Thumbnail_Job (Plugin : in Image_Module; Image : in AWA.Images.Models.Image_Ref'Class) is pragma Unreferenced (Plugin); J : AWA.Jobs.Services.Job_Type; begin J.Set_Parameter ("image_id", Image); J.Schedule (Thumbnail_Job_Definition.Factory.all); end Make_Thumbnail_Job; -- ------------------------------ -- Returns true if the storage file has an image mime type. -- ------------------------------ function Is_Image (File : in AWA.Storages.Models.Storage_Ref'Class) return Boolean is Mime : constant String := File.Get_Mime_Type; Pos : constant Natural := Util.Strings.Index (Mime, '/'); begin if Pos = 0 then return False; else return Mime (Mime'First .. Pos - 1) = "image"; end if; end Is_Image; -- ------------------------------ -- Create an image instance. -- ------------------------------ procedure Create_Image (Plugin : in Image_Module; File : in AWA.Storages.Models.Storage_Ref'Class) is begin if File.Get_Original.Is_Null then declare Ctx : constant ASC.Service_Context_Access := AWA.Services.Contexts.Current; DB : ADO.Sessions.Master_Session := ASC.Get_Master_Session (Ctx); Img : AWA.Images.Models.Image_Ref; begin Img.Set_Width (0); Img.Set_Height (0); Img.Set_Thumb_Height (0); Img.Set_Thumb_Width (0); Img.Set_Storage (File); Img.Set_Folder (File.Get_Folder); Img.Set_Owner (File.Get_Owner); Img.Save (DB); Plugin.Make_Thumbnail_Job (Img); end; end if; end Create_Image; -- ------------------------------ -- The `On_Create` procedure is called by `Notify_Create` to notify the creation of the item. -- ------------------------------ overriding procedure On_Create (Instance : in Image_Module; Item : in AWA.Storages.Models.Storage_Ref'Class) is begin if Is_Image (Item) then Image_Module'Class (Instance).Create_Image (Item); end if; end On_Create; -- ------------------------------ -- The `On_Update` procedure is called by `Notify_Update` to notify the update of the item. -- ------------------------------ overriding procedure On_Update (Instance : in Image_Module; Item : in AWA.Storages.Models.Storage_Ref'Class) is begin if Is_Image (Item) then Image_Module'Class (Instance).Create_Image (Item); else Image_Module'Class (Instance).Delete_Image (Item); end if; end On_Update; -- ------------------------------ -- The `On_Delete` procedure is called by `Notify_Delete` to notify the deletion of the item. -- ------------------------------ overriding procedure On_Delete (Instance : in Image_Module; Item : in AWA.Storages.Models.Storage_Ref'Class) is begin Image_Module'Class (Instance).Delete_Image (Item); end On_Delete; -- ------------------------------ -- Thumbnail job to identify the image dimension and produce a thumbnail. -- ------------------------------ procedure Do_Thumbnail_Job (Plugin : in Image_Module; Job : in out AWA.Jobs.Services.Abstract_Job_Type'Class) is Image_Id : constant ADO.Identifier := Job.Get_Parameter ("image_id"); begin Image_Module'Class (Plugin).Build_Thumbnail (Image_Id); end Do_Thumbnail_Job; -- ------------------------------ -- Get the image module instance associated with the current application. -- ------------------------------ function Get_Image_Module return Image_Module_Access is function Get is new AWA.Modules.Get (Image_Module, Image_Module_Access, NAME); begin return Get; end Get_Image_Module; procedure Create_Thumbnail (Service : in Image_Module; Source : in String; Into : in String; Width : in out Natural; Height : in out Natural) is Ctx : EL.Contexts.Default.Default_Context; Variables : aliased EL.Variables.Default.Default_Variable_Mapper; Proc : Util.Processes.Process; Pipe : aliased Util.Streams.Pipes.Pipe_Stream; begin Variables.Bind ("src", Util.Beans.Objects.To_Object (Source)); Variables.Bind ("dst", Util.Beans.Objects.To_Object (Into)); Variables.Bind ("width", Util.Beans.Objects.To_Object (Width)); Variables.Bind ("height", Util.Beans.Objects.To_Object (Height)); Ctx.Set_Variable_Mapper (Variables'Unchecked_Access); declare Cmd : constant Util.Beans.Objects.Object := Service.Thumbnail_Command.Get_Value (Ctx); Command : constant String := Util.Beans.Objects.To_String (Cmd); Input : Util.Streams.Texts.Reader_Stream; begin Width := 0; Height := 0; Pipe.Open (Command, Util.Processes.READ_ALL); Input.Initialize (Pipe'Unchecked_Access, 1024); while not Input.Is_Eof loop declare use Ada.Strings; Line : Ada.Strings.Unbounded.Unbounded_String; Pos : Natural; Sep : Natural; Last : Natural; begin Input.Read_Line (Into => Line, Strip => False); exit when Ada.Strings.Unbounded.Length (Line) = 0; Log.Info ("Received: {0}", Line); -- The '-verbose' option of ImageMagick reports information about the original -- image. Extract the picture width and height. -- image.png PNG 120x282 120x282+0+0 8-bit DirectClass 34.4KB 0.000u 0:00.018 Pos := Ada.Strings.Unbounded.Index (Line, " "); if Pos > 0 and Width = 0 then Pos := Ada.Strings.Unbounded.Index (Line, " ", Pos + 1); if Pos > 0 then Sep := Ada.Strings.Unbounded.Index (Line, "x", Pos + 1); Last := Ada.Strings.Unbounded.Index (Line, "=", Pos + 1); if Sep > 0 and Sep < Last then Log.Info ("Dimension {0} - {1}..{2}", Ada.Strings.Unbounded.Slice (Line, Pos, Last), Natural'Image (Pos), Natural'Image (Last)); Width := Natural'Value (Unbounded.Slice (Line, Pos + 1, Sep - 1)); Height := Natural'Value (Unbounded.Slice (Line, Sep + 1, Last - 1)); end if; end if; end if; end; end loop; Pipe.Close; Util.Processes.Wait (Proc); if Pipe.Get_Exit_Status /= 0 then Log.Error ("Command {0} exited with status {1}", Command, Integer'Image (Pipe.Get_Exit_Status)); end if; end; end Create_Thumbnail; -- Build a thumbnail for the image identified by the Id. procedure Build_Thumbnail (Service : in Image_Module; Id : in ADO.Identifier) is Storage_Service : constant AWA.Storages.Services.Storage_Service_Access := AWA.Storages.Modules.Get_Storage_Manager; Ctx : constant ASC.Service_Context_Access := ASC.Current; DB : ADO.Sessions.Master_Session := ASC.Get_Master_Session (Ctx); Img : AWA.Images.Models.Image_Ref; Thumb : AWA.Images.Models.Image_Ref; Target_File : AWA.Storages.Storage_File (AWA.Storages.TMP); Local_File : AWA.Storages.Storage_File (AWA.Storages.CACHE); Thumbnail : AWA.Storages.Models.Storage_Ref; Width : Natural := 64; Height : Natural := 64; begin Img.Load (DB, Id); declare Image_File : constant AWA.Storages.Models.Storage_Ref'Class := Img.Get_Storage; begin Storage_Service.Get_Local_File (From => Image_File.Get_Id, Into => Local_File); Storage_Service.Create_Local_File (Target_File); Service.Create_Thumbnail (AWA.Storages.Get_Path (Local_File), AWA.Storages.Get_Path (Target_File), Width, Height); Thumbnail.Set_Mime_Type ("image/jpeg"); Thumbnail.Set_Original (Image_File); Thumbnail.Set_Workspace (Image_File.Get_Workspace); Thumbnail.Set_Folder (Image_File.Get_Folder); Thumbnail.Set_Owner (Image_File.Get_Owner); Thumbnail.Set_Name (String '(Image_File.Get_Name)); Storage_Service.Save (Thumbnail, AWA.Storages.Get_Path (Target_File), AWA.Storages.Models.DATABASE); Thumb.Set_Width (64); Thumb.Set_Height (64); Thumb.Set_Owner (Image_File.Get_Owner); Thumb.Set_Folder (Image_File.Get_Folder); Thumb.Set_Storage (Thumbnail); Img.Set_Width (Width); Img.Set_Height (Height); Img.Set_Thumb_Width (64); Img.Set_Thumb_Height (64); Img.Set_Thumbnail (Thumbnail); Ctx.Start; Img.Save (DB); Thumb.Save (DB); Ctx.Commit; end; end Build_Thumbnail; -- Deletes the storage instance. procedure Delete_Image (Service : in Image_Module; File : in AWA.Storages.Models.Storage_Ref'Class) is begin null; end Delete_Image; -- ------------------------------ -- Scale the image dimension. -- ------------------------------ procedure Scale (Width : in Natural; Height : in Natural; To_Width : in out Natural; To_Height : in out Natural) is begin if To_Width = Natural'Last or To_Height = Natural'Last or (To_Width = 0 and To_Height = 0) then To_Width := Width; To_Height := Height; elsif To_Width = 0 then To_Width := (Width * To_Height) / Height; elsif To_Height = 0 then To_Height := (Height * To_Width) / Width; end if; end Scale; -- ------------------------------ -- Get the dimension represented by the string. The string has one of the following -- formats: -- original -> Width, Height := Natural'Last -- default -> Width, Height := 0 -- <width>x -> Width := <width>, Height := 0 -- x<height> -> Width := 0, Height := <height> -- <width>x<height> -> Width := <width>, Height := <height> -- ------------------------------ procedure Get_Sizes (Dimension : in String; Width : out Natural; Height : out Natural) is Pos : Natural; begin if Dimension = "original" then Width := Natural'Last; Height := Natural'Last; elsif Dimension = "default" then Width := 800; Height := 0; else Pos := Util.Strings.Index (Dimension, 'x'); if Pos > Dimension'First then Width := Natural'Value (Dimension (Dimension'First .. Pos - 1)); else Width := 0; end if; if Pos < Dimension'Last then Height := Natural'Value (Dimension (Pos + 1 .. Dimension'Last)); else Height := 0; end if; end if; end Get_Sizes; end AWA.Images.Modules;
----------------------------------------------------------------------- -- awa-images-modules -- Image management module -- Copyright (C) 2012, 2016, 2020 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Strings.Unbounded; with Util.Processes; with Util.Beans.Objects; with Util.Log.Loggers; with Util.Streams.Pipes; with Util.Streams.Texts; with Util.Strings; with ADO.Sessions; with EL.Variables.Default; with EL.Contexts.Default; with AWA.Modules.Get; with AWA.Applications; with AWA.Storages.Modules; with AWA.Services.Contexts; with AWA.Modules.Beans; with AWA.Images.Beans; package body AWA.Images.Modules is package ASC renames AWA.Services.Contexts; Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("AWA.Images.Module"); package Register is new AWA.Modules.Beans (Module => Image_Module, Module_Access => Image_Module_Access); -- ------------------------------ -- Job worker procedure to identify an image and generate its thumnbnail. -- ------------------------------ procedure Thumbnail_Worker (Job : in out AWA.Jobs.Services.Abstract_Job_Type'Class) is Module : constant Image_Module_Access := Get_Image_Module; begin Module.Do_Thumbnail_Job (Job); end Thumbnail_Worker; -- ------------------------------ -- Initialize the image module. -- ------------------------------ overriding procedure Initialize (Plugin : in out Image_Module; App : in AWA.Modules.Application_Access; Props : in ASF.Applications.Config) is begin Log.Info ("Initializing the image module"); -- Setup the resource bundles. App.Register ("imageMsg", "images"); Register.Register (Plugin => Plugin, Name => "AWA.Images.Beans.Image_List_Bean", Handler => AWA.Images.Beans.Create_Image_List_Bean'Access); Register.Register (Plugin => Plugin, Name => "AWA.Images.Beans.Image_Bean", Handler => AWA.Images.Beans.Create_Image_Bean'Access); App.Add_Servlet ("image", Plugin.Image_Servlet'Unchecked_Access); AWA.Modules.Module (Plugin).Initialize (App, Props); Plugin.Add_Listener (AWA.Storages.Modules.NAME, Plugin'Unchecked_Access); end Initialize; -- ------------------------------ -- Configures the module after its initialization and after having read its XML configuration. -- ------------------------------ overriding procedure Configure (Plugin : in out Image_Module; Props : in ASF.Applications.Config) is pragma Unreferenced (Props); use type AWA.Jobs.Modules.Job_Module_Access; begin Plugin.Job_Module := AWA.Jobs.Modules.Get_Job_Module; if Plugin.Job_Module = null then Log.Error ("Cannot find the AWA Job module for the image thumbnail generation"); else Plugin.Job_Module.Register (Definition => Thumbnail_Job_Definition.Factory); end if; Plugin.Thumbnail_Command := Plugin.Get_Config (PARAM_THUMBNAIL_COMMAND); end Configure; -- ------------------------------ -- Create a thumbnail job for the image. -- ------------------------------ procedure Make_Thumbnail_Job (Plugin : in Image_Module; Image : in AWA.Images.Models.Image_Ref'Class) is pragma Unreferenced (Plugin); J : AWA.Jobs.Services.Job_Type; begin J.Set_Parameter ("image_id", Image); J.Schedule (Thumbnail_Job_Definition.Factory.all); end Make_Thumbnail_Job; -- ------------------------------ -- Returns true if the storage file has an image mime type. -- ------------------------------ function Is_Image (File : in AWA.Storages.Models.Storage_Ref'Class) return Boolean is Mime : constant String := File.Get_Mime_Type; Pos : constant Natural := Util.Strings.Index (Mime, '/'); begin if Pos = 0 then return False; else return Mime (Mime'First .. Pos - 1) = "image"; end if; end Is_Image; -- ------------------------------ -- Create an image instance. -- ------------------------------ procedure Create_Image (Plugin : in Image_Module; File : in AWA.Storages.Models.Storage_Ref'Class) is begin if File.Get_Original.Is_Null then declare Ctx : constant ASC.Service_Context_Access := AWA.Services.Contexts.Current; DB : ADO.Sessions.Master_Session := ASC.Get_Master_Session (Ctx); Img : AWA.Images.Models.Image_Ref; begin Img.Set_Width (0); Img.Set_Height (0); Img.Set_Thumb_Height (0); Img.Set_Thumb_Width (0); Img.Set_Storage (File); Img.Set_Folder (File.Get_Folder); Img.Set_Owner (File.Get_Owner); Img.Save (DB); Plugin.Make_Thumbnail_Job (Img); end; end if; end Create_Image; -- ------------------------------ -- The `On_Create` procedure is called by `Notify_Create` to notify the creation of the item. -- ------------------------------ overriding procedure On_Create (Instance : in Image_Module; Item : in AWA.Storages.Models.Storage_Ref'Class) is begin if Is_Image (Item) then Image_Module'Class (Instance).Create_Image (Item); end if; end On_Create; -- ------------------------------ -- The `On_Update` procedure is called by `Notify_Update` to notify the update of the item. -- ------------------------------ overriding procedure On_Update (Instance : in Image_Module; Item : in AWA.Storages.Models.Storage_Ref'Class) is begin if Is_Image (Item) then Image_Module'Class (Instance).Create_Image (Item); else Image_Module'Class (Instance).Delete_Image (Item); end if; end On_Update; -- ------------------------------ -- The `On_Delete` procedure is called by `Notify_Delete` to notify the deletion of the item. -- ------------------------------ overriding procedure On_Delete (Instance : in Image_Module; Item : in AWA.Storages.Models.Storage_Ref'Class) is begin Image_Module'Class (Instance).Delete_Image (Item); end On_Delete; -- ------------------------------ -- Thumbnail job to identify the image dimension and produce a thumbnail. -- ------------------------------ procedure Do_Thumbnail_Job (Plugin : in Image_Module; Job : in out AWA.Jobs.Services.Abstract_Job_Type'Class) is Image_Id : constant ADO.Identifier := Job.Get_Parameter ("image_id"); begin Image_Module'Class (Plugin).Build_Thumbnail (Image_Id); end Do_Thumbnail_Job; -- ------------------------------ -- Get the image module instance associated with the current application. -- ------------------------------ function Get_Image_Module return Image_Module_Access is function Get is new AWA.Modules.Get (Image_Module, Image_Module_Access, NAME); begin return Get; end Get_Image_Module; procedure Create_Thumbnail (Service : in Image_Module; Source : in String; Into : in String; Width : in out Natural; Height : in out Natural) is Ctx : EL.Contexts.Default.Default_Context; Variables : aliased EL.Variables.Default.Default_Variable_Mapper; Proc : Util.Processes.Process; Pipe : aliased Util.Streams.Pipes.Pipe_Stream; begin Variables.Bind ("src", Util.Beans.Objects.To_Object (Source)); Variables.Bind ("dst", Util.Beans.Objects.To_Object (Into)); Variables.Bind ("width", Util.Beans.Objects.To_Object (Width)); Variables.Bind ("height", Util.Beans.Objects.To_Object (Height)); Ctx.Set_Variable_Mapper (Variables'Unchecked_Access); declare Cmd : constant Util.Beans.Objects.Object := Service.Thumbnail_Command.Get_Value (Ctx); Command : constant String := Util.Beans.Objects.To_String (Cmd); Input : Util.Streams.Texts.Reader_Stream; begin Width := 0; Height := 0; Pipe.Open (Command, Util.Processes.READ_ALL); Input.Initialize (Pipe'Unchecked_Access, 1024); while not Input.Is_Eof loop declare use Ada.Strings; Line : Ada.Strings.Unbounded.Unbounded_String; Pos : Natural; Sep : Natural; Last : Natural; begin Input.Read_Line (Into => Line, Strip => False); exit when Ada.Strings.Unbounded.Length (Line) = 0; Log.Info ("Received: {0}", Line); -- The '-verbose' option of ImageMagick reports information about the original -- image. Extract the picture width and height. -- image.png PNG 120x282 120x282+0+0 8-bit DirectClass 34.4KB 0.000u 0:00.018 Pos := Ada.Strings.Unbounded.Index (Line, " "); if Pos > 0 and Width = 0 then Pos := Ada.Strings.Unbounded.Index (Line, " ", Pos + 1); if Pos > 0 then Sep := Ada.Strings.Unbounded.Index (Line, "x", Pos + 1); Last := Ada.Strings.Unbounded.Index (Line, "=", Pos + 1); if Sep > 0 and Sep < Last then Log.Info ("Dimension {0} - {1}..{2}", Ada.Strings.Unbounded.Slice (Line, Pos, Last), Natural'Image (Pos), Natural'Image (Last)); Width := Natural'Value (Unbounded.Slice (Line, Pos + 1, Sep - 1)); Height := Natural'Value (Unbounded.Slice (Line, Sep + 1, Last - 1)); end if; end if; end if; end; end loop; Pipe.Close; Util.Processes.Wait (Proc); if Pipe.Get_Exit_Status /= 0 then Log.Error ("Command {0} exited with status {1}", Command, Integer'Image (Pipe.Get_Exit_Status)); end if; end; end Create_Thumbnail; -- Build a thumbnail for the image identified by the Id. procedure Build_Thumbnail (Service : in Image_Module; Id : in ADO.Identifier) is Storage_Service : constant AWA.Storages.Services.Storage_Service_Access := AWA.Storages.Modules.Get_Storage_Manager; Ctx : constant ASC.Service_Context_Access := ASC.Current; DB : ADO.Sessions.Master_Session := ASC.Get_Master_Session (Ctx); Img : AWA.Images.Models.Image_Ref; Thumb : AWA.Images.Models.Image_Ref; Target_File : AWA.Storages.Storage_File (AWA.Storages.TMP); Local_File : AWA.Storages.Storage_File (AWA.Storages.CACHE); Thumbnail : AWA.Storages.Models.Storage_Ref; Width : Natural := 64; Height : Natural := 64; begin Img.Load (DB, Id); declare Image_File : constant AWA.Storages.Models.Storage_Ref'Class := Img.Get_Storage; begin Storage_Service.Get_Local_File (From => Image_File.Get_Id, Into => Local_File); Storage_Service.Create_Local_File (Target_File); Service.Create_Thumbnail (AWA.Storages.Get_Path (Local_File), AWA.Storages.Get_Path (Target_File), Width, Height); Thumbnail.Set_Mime_Type ("image/jpeg"); Thumbnail.Set_Original (Image_File); Thumbnail.Set_Workspace (Image_File.Get_Workspace); Thumbnail.Set_Folder (Image_File.Get_Folder); Thumbnail.Set_Owner (Image_File.Get_Owner); Thumbnail.Set_Name (String '(Image_File.Get_Name)); Storage_Service.Save (Thumbnail, AWA.Storages.Get_Path (Target_File), AWA.Storages.Models.DATABASE); Thumb.Set_Width (64); Thumb.Set_Height (64); Thumb.Set_Owner (Image_File.Get_Owner); Thumb.Set_Folder (Image_File.Get_Folder); Thumb.Set_Storage (Thumbnail); Img.Set_Width (Width); Img.Set_Height (Height); Img.Set_Thumb_Width (64); Img.Set_Thumb_Height (64); Img.Set_Thumbnail (Thumbnail); Ctx.Start; Img.Save (DB); Thumb.Save (DB); Ctx.Commit; end; end Build_Thumbnail; -- Deletes the storage instance. procedure Delete_Image (Service : in Image_Module; File : in AWA.Storages.Models.Storage_Ref'Class) is begin null; end Delete_Image; -- ------------------------------ -- Scale the image dimension. -- ------------------------------ procedure Scale (Width : in Natural; Height : in Natural; To_Width : in out Natural; To_Height : in out Natural) is begin if To_Width = Natural'Last or To_Height = Natural'Last or (To_Width = 0 and To_Height = 0) then To_Width := Width; To_Height := Height; elsif To_Width = 0 then To_Width := (Width * To_Height) / Height; elsif To_Height = 0 then To_Height := (Height * To_Width) / Width; end if; end Scale; -- ------------------------------ -- Get the dimension represented by the string. The string has one of the following -- formats: -- original -> Width, Height := Natural'Last -- default -> Width, Height := 0 -- <width>x -> Width := <width>, Height := 0 -- x<height> -> Width := 0, Height := <height> -- <width>x<height> -> Width := <width>, Height := <height> -- ------------------------------ procedure Get_Sizes (Dimension : in String; Width : out Natural; Height : out Natural) is Pos : Natural; begin if Dimension = "original" then Width := Natural'Last; Height := Natural'Last; elsif Dimension = "default" then Width := 800; Height := 0; else Pos := Util.Strings.Index (Dimension, 'x'); if Pos > Dimension'First then begin Width := Natural'Value (Dimension (Dimension'First .. Pos - 1)); exception when Constraint_Error => Width := 0; end; else Width := 0; end if; if Pos < Dimension'Last then begin Height := Natural'Value (Dimension (Pos + 1 .. Dimension'Last)); exception when Constraint_Error => Height := 0; end; else Height := 0; end if; end if; end Get_Sizes; end AWA.Images.Modules;
Fix Get_Sizes to handle errors for width and height
Fix Get_Sizes to handle errors for width and height
Ada
apache-2.0
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
b592ad00d1b613d20676315065c6e5c8ee9c08b1
tools/druss-commands.ads
tools/druss-commands.ads
----------------------------------------------------------------------- -- druss-commands -- Commands available for Druss -- 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.Commands.Drivers; with Util.Commands.Consoles; with Util.Commands.Consoles.Text; with Druss.Gateways; package Druss.Commands is -- Exception raised to stop the interactive loop. Stop_Interactive : exception; -- Device selector to select all, active or inactive devices. type Device_Selector_Type is (DEVICE_ALL, DEVICE_ACTIVE, DEVICE_INACTIVE); -- The list of fields that are printed on the console. type Field_Type is (F_IP_ADDR, F_BBOX_IP_ADDR, F_WAN_IP, F_ETHERNET, F_INTERNET, F_VOIP, F_HOSTNAME, F_CONNECTION, F_DEVTYPE, F_ACTIVE, F_LINK, F_WIFI, F_WIFI5, F_ACCESS_CONTROL, F_DYNDNS, F_DEVICES, F_UPTIME, F_COUNT, F_BOOL, F_CHANNEL, F_PROTOCOL, F_ENCRYPTION, F_SSID); -- The type of notice that are reported. type Notice_Type is (N_HELP, N_USAGE, N_INFO); -- Make the generic abstract console interface. package Consoles is new Util.Commands.Consoles (Field_Type => Field_Type, Notice_Type => Notice_Type); -- And the text console to write on stdout (a Gtk console could be done someday). package Text_Consoles is new Consoles.Text; type Context_Type is limited record Gateways : Druss.Gateways.Gateway_Vector; Console : Consoles.Console_Access; end record; package Drivers is new Util.Commands.Drivers (Context_Type => Context_Type, Driver_Name => "druss-drivers"); subtype Argument_List is Util.Commands.Argument_List; Driver : Drivers.Driver_Type; procedure Gateway_Command (Command : in Drivers.Command_Type'Class; Args : in Util.Commands.Argument_List'Class; Arg_Pos : in Positive; Process : access procedure (Gateway : in out Gateways.Gateway_Type; Param : in String); Context : in out Context_Type); procedure Initialize; -- Enter in the interactive main loop waiting for user commands and executing them. procedure Interactive (Context : in out Context_Type); -- Print the bbox API status. procedure Print_Status (Console : in Consoles.Console_Access; Field : in Field_Type; Value : in String); -- Print a ON/OFF status. procedure Print_On_Off (Console : in Consoles.Console_Access; Field : in Field_Type; Value : in String); -- Print a uptime. procedure Print_Uptime (Console : in Consoles.Console_Access; Field : in Field_Type; Value : in String); -- Print a performance measure in us or ms. procedure Print_Perf (Console : in Consoles.Console_Access; Field : in Field_Type; Value : in String); end Druss.Commands;
----------------------------------------------------------------------- -- druss-commands -- Commands available for Druss -- Copyright (C) 2017, 2018 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Commands.Drivers; with Util.Commands.Parsers; with Util.Commands.Consoles; with Util.Commands.Consoles.Text; with Druss.Gateways; package Druss.Commands is -- Exception raised to stop the interactive loop. Stop_Interactive : exception; -- Device selector to select all, active or inactive devices. type Device_Selector_Type is (DEVICE_ALL, DEVICE_ACTIVE, DEVICE_INACTIVE); -- The list of fields that are printed on the console. type Field_Type is (F_IP_ADDR, F_BBOX_IP_ADDR, F_WAN_IP, F_ETHERNET, F_INTERNET, F_VOIP, F_HOSTNAME, F_CONNECTION, F_DEVTYPE, F_ACTIVE, F_LINK, F_WIFI, F_WIFI5, F_ACCESS_CONTROL, F_DYNDNS, F_DEVICES, F_UPTIME, F_COUNT, F_BOOL, F_CHANNEL, F_PROTOCOL, F_ENCRYPTION, F_SSID); -- The type of notice that are reported. type Notice_Type is (N_HELP, N_USAGE, N_INFO); -- Make the generic abstract console interface. package Consoles is new Util.Commands.Consoles (Field_Type => Field_Type, Notice_Type => Notice_Type); -- And the text console to write on stdout (a Gtk console could be done someday). package Text_Consoles is new Consoles.Text; type Context_Type is limited record Gateways : Druss.Gateways.Gateway_Vector; Console : Consoles.Console_Access; end record; package Drivers is new Util.Commands.Drivers (Context_Type => Context_Type, Config_Parser => Util.Commands.Parsers.No_Parser, Driver_Name => "druss-drivers"); subtype Argument_List is Util.Commands.Argument_List; Driver : Drivers.Driver_Type; procedure Gateway_Command (Command : in Drivers.Command_Type'Class; Args : in Util.Commands.Argument_List'Class; Arg_Pos : in Positive; Process : access procedure (Gateway : in out Gateways.Gateway_Type; Param : in String); Context : in out Context_Type); procedure Initialize; -- Enter in the interactive main loop waiting for user commands and executing them. procedure Interactive (Context : in out Context_Type); -- Print the bbox API status. procedure Print_Status (Console : in Consoles.Console_Access; Field : in Field_Type; Value : in String); -- Print a ON/OFF status. procedure Print_On_Off (Console : in Consoles.Console_Access; Field : in Field_Type; Value : in String); -- Print a uptime. procedure Print_Uptime (Console : in Consoles.Console_Access; Field : in Field_Type; Value : in String); -- Print a performance measure in us or ms. procedure Print_Perf (Console : in Consoles.Console_Access; Field : in Field_Type; Value : in String); end Druss.Commands;
Update the instantiation of Util.Commands.Drivers package
Update the instantiation of Util.Commands.Drivers package
Ada
apache-2.0
stcarrez/bbox-ada-api
92e75ebccb3f23181b1c941d42dc44d6edee2bf6
awa/src/awa-users-beans.adb
awa/src/awa-users-beans.adb
----------------------------------------------------------------------- -- awa-users-beans -- ASF Beans for user module -- Copyright (C) 2011 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with ASF.Sessions; with ASF.Events.Actions; with ASF.Contexts.Faces; with AWA.Users.Principals; package body AWA.Users.Beans is use AWA.Users.Models; -- ------------------------------ -- Action to register a user -- ------------------------------ procedure Register_User (Data : in out Authenticate_Bean; Outcome : in out Unbounded_String) is User : User_Ref; Email : Email_Ref; begin Email.Set_Email (Data.Email); User.Set_First_Name (Data.First_Name); User.Set_Last_Name (Data.Last_Name); User.Set_Password (Data.Password); Data.Manager.Create_User (User => User, Email => Email); Outcome := To_Unbounded_String ("success"); end Register_User; -- ------------------------------ -- Action to verify the user after the registration -- ------------------------------ procedure Verify_User (Data : in out Authenticate_Bean; Outcome : in out Unbounded_String) is User : User_Ref; Session : Session_Ref; begin Data.Manager.Verify_User (Key => To_String (Data.Access_Key), User => User, IpAddr => "", Session => Session); Outcome := To_Unbounded_String ("success"); end Verify_User; -- ------------------------------ -- Action to trigger the lost password email process. -- ------------------------------ procedure Lost_Password (Data : in out Authenticate_Bean; Outcome : in out Unbounded_String) is begin Data.Manager.Lost_Password (Email => To_String (Data.Email)); Outcome := To_Unbounded_String ("success"); end Lost_Password; -- ------------------------------ -- Action to validate the reset password key and set a new password. -- ------------------------------ procedure Reset_Password (Data : in out Authenticate_Bean; Outcome : in out Unbounded_String) is User : User_Ref; Session : Session_Ref; begin Data.Manager.Reset_Password (Key => To_String (Data.Access_Key), Password => To_String (Data.Password), IpAddr => "", User => User, Session => Session); Outcome := To_Unbounded_String ("success"); end Reset_Password; procedure Set_Session_Principal (Data : in Authenticate_Bean; User : in AWA.Users.Models.User_Ref; Sess : in AWA.Users.Models.Session_Ref) is Principal : constant Principals.Principal_Access := Principals.Create (User, Sess); Ctx : constant ASF.Contexts.Faces.Faces_Context_Access := ASF.Contexts.Faces.Current; Session : ASF.Sessions.Session := Ctx.Get_Session (Create => True); Name : constant String := "User: " & User.Get_Name; begin Session.Set_Principal (Principal.all'Access); end Set_Session_Principal; -- ------------------------------ -- Action to authenticate a user (password authentication). -- ------------------------------ procedure Authenticate_User (Data : in out Authenticate_Bean; Outcome : in out Unbounded_String) is User : User_Ref; Session : Session_Ref; begin Data.Manager.Authenticate (Email => To_String (Data.Email), Password => To_String (Data.Password), IpAddr => "", User => User, Session => Session); Outcome := To_Unbounded_String ("success"); Data.Set_Session_Principal (User, Session); end Authenticate_User; -- ------------------------------ -- Create an authenticate bean. -- ------------------------------ function Create_Authenticate_Bean (Module : in AWA.Users.Module.User_Module_Access) return Util.Beans.Basic.Readonly_Bean_Access is Object : Authenticate_Bean_Access := new Authenticate_Bean; begin Object.Module := Module; Object.Manager := AWA.Users.Module.Get_User_Manager; return Object.all'Access; end Create_Authenticate_Bean; -- The code below this line could be generated automatically by an Asis tool. package Authenticate_Binding is new ASF.Events.Actions.Action_Method.Bind (Bean => Authenticate_Bean, Method => Authenticate_User, Name => "authenticate"); package Register_Binding is new ASF.Events.Actions.Action_Method.Bind (Bean => Authenticate_Bean, Method => Register_User, Name => "register"); package Verify_Binding is new ASF.Events.Actions.Action_Method.Bind (Bean => Authenticate_Bean, Method => Verify_User, Name => "verify"); package Lost_Password_Binding is new ASF.Events.Actions.Action_Method.Bind (Bean => Authenticate_Bean, Method => Lost_Password, Name => "lostPassword"); package Reset_Password_Binding is new ASF.Events.Actions.Action_Method.Bind (Bean => Authenticate_Bean, Method => Reset_Password, Name => "resetPassword"); Binding_Array : aliased constant Util.Beans.Methods.Method_Binding_Array := (Authenticate_Binding.Proxy'Access, Register_Binding.Proxy'Access, Verify_Binding.Proxy'Access, Lost_Password_Binding.Proxy'Access, Reset_Password_Binding.Proxy'Access); -- ------------------------------ -- Get the value identified by the name. -- ------------------------------ overriding function Get_Value (From : in Authenticate_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 = "key" then return Util.Beans.Objects.To_Object (From.Access_Key); 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 Authenticate_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 = "key" then From.Access_Key := 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 Authenticate_Bean) return Util.Beans.Methods.Method_Binding_Array_Access is begin return Binding_Array'Access; end Get_Method_Bindings; end AWA.Users.Beans;
----------------------------------------------------------------------- -- awa-users-beans -- ASF Beans for user module -- Copyright (C) 2011 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with ASF.Sessions; with ASF.Events.Actions; with ASF.Contexts.Faces; with AWA.Users.Principals; package body AWA.Users.Beans is use AWA.Users.Models; -- ------------------------------ -- Action to register a user -- ------------------------------ procedure Register_User (Data : in out Authenticate_Bean; Outcome : in out Unbounded_String) is User : User_Ref; Email : Email_Ref; begin Email.Set_Email (Data.Email); User.Set_First_Name (Data.First_Name); User.Set_Last_Name (Data.Last_Name); User.Set_Password (Data.Password); Data.Manager.Create_User (User => User, Email => Email); Outcome := To_Unbounded_String ("success"); end Register_User; -- ------------------------------ -- Action to verify the user after the registration -- ------------------------------ procedure Verify_User (Data : in out Authenticate_Bean; Outcome : in out Unbounded_String) is User : User_Ref; Session : Session_Ref; begin Data.Manager.Verify_User (Key => To_String (Data.Access_Key), User => User, IpAddr => "", Session => Session); Data.Set_Session_Principal (User, Session); Outcome := To_Unbounded_String ("success"); end Verify_User; -- ------------------------------ -- Action to trigger the lost password email process. -- ------------------------------ procedure Lost_Password (Data : in out Authenticate_Bean; Outcome : in out Unbounded_String) is begin Data.Manager.Lost_Password (Email => To_String (Data.Email)); Outcome := To_Unbounded_String ("success"); end Lost_Password; -- ------------------------------ -- Action to validate the reset password key and set a new password. -- ------------------------------ procedure Reset_Password (Data : in out Authenticate_Bean; Outcome : in out Unbounded_String) is User : User_Ref; Session : Session_Ref; begin Data.Manager.Reset_Password (Key => To_String (Data.Access_Key), Password => To_String (Data.Password), IpAddr => "", User => User, Session => Session); Outcome := To_Unbounded_String ("success"); end Reset_Password; procedure Set_Session_Principal (Data : in Authenticate_Bean; User : in AWA.Users.Models.User_Ref; Sess : in AWA.Users.Models.Session_Ref) is Principal : constant Principals.Principal_Access := Principals.Create (User, Sess); Ctx : constant ASF.Contexts.Faces.Faces_Context_Access := ASF.Contexts.Faces.Current; Session : ASF.Sessions.Session := Ctx.Get_Session (Create => True); Name : constant String := "User: " & User.Get_Name; begin Session.Set_Principal (Principal.all'Access); end Set_Session_Principal; -- ------------------------------ -- Action to authenticate a user (password authentication). -- ------------------------------ procedure Authenticate_User (Data : in out Authenticate_Bean; Outcome : in out Unbounded_String) is User : User_Ref; Session : Session_Ref; begin Data.Manager.Authenticate (Email => To_String (Data.Email), Password => To_String (Data.Password), IpAddr => "", User => User, Session => Session); Outcome := To_Unbounded_String ("success"); Data.Set_Session_Principal (User, Session); end Authenticate_User; -- ------------------------------ -- Create an authenticate bean. -- ------------------------------ function Create_Authenticate_Bean (Module : in AWA.Users.Module.User_Module_Access) return Util.Beans.Basic.Readonly_Bean_Access is Object : Authenticate_Bean_Access := new Authenticate_Bean; begin Object.Module := Module; Object.Manager := AWA.Users.Module.Get_User_Manager; return Object.all'Access; end Create_Authenticate_Bean; -- The code below this line could be generated automatically by an Asis tool. package Authenticate_Binding is new ASF.Events.Actions.Action_Method.Bind (Bean => Authenticate_Bean, Method => Authenticate_User, Name => "authenticate"); package Register_Binding is new ASF.Events.Actions.Action_Method.Bind (Bean => Authenticate_Bean, Method => Register_User, Name => "register"); package Verify_Binding is new ASF.Events.Actions.Action_Method.Bind (Bean => Authenticate_Bean, Method => Verify_User, Name => "verify"); package Lost_Password_Binding is new ASF.Events.Actions.Action_Method.Bind (Bean => Authenticate_Bean, Method => Lost_Password, Name => "lostPassword"); package Reset_Password_Binding is new ASF.Events.Actions.Action_Method.Bind (Bean => Authenticate_Bean, Method => Reset_Password, Name => "resetPassword"); Binding_Array : aliased constant Util.Beans.Methods.Method_Binding_Array := (Authenticate_Binding.Proxy'Access, Register_Binding.Proxy'Access, Verify_Binding.Proxy'Access, Lost_Password_Binding.Proxy'Access, Reset_Password_Binding.Proxy'Access); -- ------------------------------ -- Get the value identified by the name. -- ------------------------------ overriding function Get_Value (From : in Authenticate_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 = "key" then return Util.Beans.Objects.To_Object (From.Access_Key); 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 Authenticate_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 = "key" then From.Access_Key := 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 Authenticate_Bean) return Util.Beans.Methods.Method_Binding_Array_Access is begin return Binding_Array'Access; end Get_Method_Bindings; end AWA.Users.Beans;
Set the user principal after the verification key is valid
Set the user principal after the verification key is valid
Ada
apache-2.0
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
eb7a95358b047134be6b464d44f45ae3dfaa8fde
src/gen-commands-project.adb
src/gen-commands-project.adb
----------------------------------------------------------------------- -- gen-commands-project -- Project creation command for dynamo -- Copyright (C) 2011, 2012, 2013, 2014, 2017, 2018 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Directories; with Ada.Text_IO; with Gen.Artifacts; with GNAT.Command_Line; with GNAT.OS_Lib; with Util.Log.Loggers; with Util.Strings.Transforms; package body Gen.Commands.Project is use Util.Log; Log : constant Loggers.Logger := Loggers.Create ("Gen.Commands.Project"); -- ------------------------------ -- Generator Command -- ------------------------------ function Get_Name_From_Email (Email : in String) return String; -- ------------------------------ -- Get the user name from the email address. -- Returns the possible user name from his email address. -- ------------------------------ function Get_Name_From_Email (Email : in String) return String is Pos : Natural := Util.Strings.Index (Email, '<'); begin if Pos > 0 then return Email (Email'First .. Pos - 1); end if; Pos := Util.Strings.Index (Email, '@'); if Pos > 0 then return Email (Email'First .. Pos - 1); else return Email; end if; end Get_Name_From_Email; -- ------------------------------ -- Execute the command with the arguments. -- ------------------------------ overriding procedure Execute (Cmd : in out Command; Name : in String; Args : in Argument_List'Class; Generator : in out Gen.Generator.Handler) is pragma Unreferenced (Name, Args); use GNAT.Command_Line; Web_Flag : aliased Boolean := False; Tool_Flag : aliased Boolean := False; Ado_Flag : aliased Boolean := False; Gtk_Flag : aliased Boolean := False; Lib_Flag : aliased Boolean := False; begin -- If a dynamo.xml file exists, read it. if Ada.Directories.Exists ("dynamo.xml") then Generator.Read_Project ("dynamo.xml"); else Generator.Set_Project_Property ("license", "apache"); Generator.Set_Project_Property ("author", "unknown"); Generator.Set_Project_Property ("author_email", "[email protected]"); end if; -- Parse the command line loop case Getopt ("l: ? -lib -web -tool -ado -gtk") is when ASCII.NUL => exit; when '-' => if Full_Switch = "-web" then Web_Flag := True; elsif Full_Switch = "-tool" then Tool_Flag := True; elsif Full_Switch = "-ado" then Ado_Flag := True; elsif Full_Switch = "-lib" then Lib_Flag := True; elsif Full_Switch = "-gtk" then Gtk_Flag := True; end if; when 'l' => declare L : constant String := Util.Strings.Transforms.To_Lower_Case (Parameter); begin Log.Info ("License {0}", L); if L = "apache" then Generator.Set_Project_Property ("license", "apache"); elsif L = "gpl" then Generator.Set_Project_Property ("license", "gpl"); elsif L = "gpl3" then Generator.Set_Project_Property ("license", "gpl3"); elsif L = "mit" then Generator.Set_Project_Property ("license", "mit"); elsif L = "bsd3" then Generator.Set_Project_Property ("license", "bsd3"); elsif L = "proprietary" then Generator.Set_Project_Property ("license", "proprietary"); else Generator.Error ("Invalid license: {0}", L); Generator.Error ("Valid licenses: apache, gpl, gpl3, mit, bsd3, proprietary"); return; end if; end; when others => null; end case; end loop; if not Web_Flag and not Ado_Flag and not Tool_Flag and not Gtk_Flag then Web_Flag := True; end if; declare Name : constant String := Get_Argument; Arg2 : constant String := Get_Argument; Arg3 : constant String := Get_Argument; begin if Name'Length = 0 then Generator.Error ("Missing project name"); Cmd.Usage (Name, Generator); return; end if; if Util.Strings.Index (Arg2, '@') > Arg2'First then Generator.Set_Project_Property ("author_email", Arg2); if Arg3'Length = 0 then Generator.Set_Project_Property ("author", Get_Name_From_Email (Arg2)); else Generator.Set_Project_Property ("author", Arg3); end if; elsif Util.Strings.Index (Arg3, '@') > Arg3'First then Generator.Set_Project_Property ("author", Arg2); Generator.Set_Project_Property ("author_email", Arg3); elsif Arg3'Length > 0 then Generator.Error ("The last argument should be the author's email address."); Cmd.Usage (Name, Generator); return; end if; Generator.Set_Project_Property ("is_web", Boolean'Image (Web_Flag)); Generator.Set_Project_Property ("is_tool", Boolean'Image (Tool_Flag)); Generator.Set_Project_Property ("is_ado", Boolean'Image (Ado_Flag)); Generator.Set_Project_Property ("is_gtk", Boolean'Image (Gtk_Flag)); Generator.Set_Project_Property ("is_lib", Boolean'Image (Lib_Flag)); Generator.Set_Project_Name (Name); Generator.Set_Force_Save (False); if Ado_Flag then Gen.Generator.Generate_All (Generator, Gen.Artifacts.ITERATION_TABLE, "project-ado"); elsif Gtk_Flag then Gen.Generator.Generate_All (Generator, Gen.Artifacts.ITERATION_TABLE, "project-gtk"); elsif Tool_Flag then Gen.Generator.Generate_All (Generator, Gen.Artifacts.ITERATION_TABLE, "project-tool"); elsif Lib_Flag then Gen.Generator.Generate_All (Generator, Gen.Artifacts.ITERATION_TABLE, "project-lib"); else Gen.Generator.Generate_All (Generator, Gen.Artifacts.ITERATION_TABLE, "project"); end if; Generator.Save_Project; declare use type GNAT.OS_Lib.String_Access; Path : constant GNAT.OS_Lib.String_Access := GNAT.OS_Lib.Locate_Exec_On_Path ("autoconf"); Args : GNAT.OS_Lib.Argument_List (1 .. 0); Status : Boolean; begin if Path = null then Generator.Error ("The 'autoconf' tool was not found. It is necessary to " & "generate the configure script."); Generator.Error ("Install 'autoconf' or launch it manually."); else Ada.Directories.Set_Directory (Generator.Get_Result_Directory); Log.Info ("Executing {0}", Path.all); GNAT.OS_Lib.Spawn (Path.all, Args, Status); if not Status then Generator.Error ("Execution of {0} failed", Path.all); end if; end if; end; end; end Execute; -- ------------------------------ -- Write the help associated with the command. -- ------------------------------ overriding procedure Help (Cmd : in out Command; Generator : in out Gen.Generator.Handler) is pragma Unreferenced (Cmd, Generator); use Ada.Text_IO; begin Put_Line ("create-project: Create a new Ada Web Application project"); Put_Line ("Usage: create-project [-l apache|gpl|gpl3|mit|bsd3|proprietary] [--web] [--tool]" & " [--lib] [--ado] [--gtk] NAME [AUTHOR] [EMAIL]"); New_Line; Put_Line (" Creates a new AWA application with the name passed in NAME."); Put_Line (" The application license is controlled with the -l option. "); Put_Line (" License headers can use either the Apache, the MIT license, the BSD 3 clauses"); Put_Line (" license, the GNU licenses or a proprietary license."); Put_Line (" The author's name and email addresses are also reported in generated files."); New_Line; Put_Line (" --web Generate a Web application (the default)"); Put_Line (" --tool Generate a command line tool"); Put_Line (" --ado Generate a database tool operation for ADO"); Put_Line (" --gtk Generate a GtkAda project"); Put_Line (" --lib Generate a library project"); end Help; end Gen.Commands.Project;
----------------------------------------------------------------------- -- gen-commands-project -- Project creation command for dynamo -- Copyright (C) 2011, 2012, 2013, 2014, 2017, 2018 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Directories; with Ada.Text_IO; with Gen.Artifacts; with GNAT.Command_Line; with GNAT.OS_Lib; with Util.Log.Loggers; with Util.Strings.Transforms; package body Gen.Commands.Project is use Util.Log; Log : constant Loggers.Logger := Loggers.Create ("Gen.Commands.Project"); -- ------------------------------ -- Generator Command -- ------------------------------ function Get_Name_From_Email (Email : in String) return String; -- ------------------------------ -- Get the user name from the email address. -- Returns the possible user name from his email address. -- ------------------------------ function Get_Name_From_Email (Email : in String) return String is Pos : Natural := Util.Strings.Index (Email, '<'); begin if Pos > 0 then return Email (Email'First .. Pos - 1); end if; Pos := Util.Strings.Index (Email, '@'); if Pos > 0 then return Email (Email'First .. Pos - 1); else return Email; end if; end Get_Name_From_Email; -- ------------------------------ -- Execute the command with the arguments. -- ------------------------------ overriding procedure Execute (Cmd : in out Command; Name : in String; Args : in Argument_List'Class; Generator : in out Gen.Generator.Handler) is pragma Unreferenced (Name, Args); use GNAT.Command_Line; Web_Flag : aliased Boolean := False; Tool_Flag : aliased Boolean := False; Ado_Flag : aliased Boolean := False; Gtk_Flag : aliased Boolean := False; Lib_Flag : aliased Boolean := False; begin -- If a dynamo.xml file exists, read it. if Ada.Directories.Exists ("dynamo.xml") then Generator.Read_Project ("dynamo.xml"); else Generator.Set_Project_Property ("license", "apache"); Generator.Set_Project_Property ("author", "unknown"); Generator.Set_Project_Property ("author_email", "[email protected]"); end if; -- Parse the command line loop case Getopt ("l: ? -lib -web -tool -ado -gtk") is when ASCII.NUL => exit; when '-' => if Full_Switch = "-web" then Web_Flag := True; elsif Full_Switch = "-tool" then Tool_Flag := True; elsif Full_Switch = "-ado" then Ado_Flag := True; elsif Full_Switch = "-lib" then Lib_Flag := True; elsif Full_Switch = "-gtk" then Gtk_Flag := True; end if; when 'l' => declare L : constant String := Util.Strings.Transforms.To_Lower_Case (Parameter); begin Log.Info ("License {0}", L); if L = "apache" then Generator.Set_Project_Property ("license", "apache"); elsif L = "gpl" then Generator.Set_Project_Property ("license", "gpl"); elsif L = "gpl3" then Generator.Set_Project_Property ("license", "gpl3"); elsif L = "mit" then Generator.Set_Project_Property ("license", "mit"); elsif L = "bsd3" then Generator.Set_Project_Property ("license", "bsd3"); elsif L = "proprietary" then Generator.Set_Project_Property ("license", "proprietary"); else Generator.Error ("Invalid license: {0}", L); Generator.Error ("Valid licenses: apache, gpl, gpl3, mit, bsd3, proprietary"); return; end if; end; when others => null; end case; end loop; if not Web_Flag and not Ado_Flag and not Tool_Flag and not Gtk_Flag then Web_Flag := True; end if; declare Name : constant String := Get_Argument; Arg2 : constant String := Get_Argument; Arg3 : constant String := Get_Argument; begin if Name'Length = 0 then Generator.Error ("Missing project name"); Cmd.Usage (Name, Generator); return; end if; if Util.Strings.Index (Arg2, '@') > Arg2'First then Generator.Set_Project_Property ("author_email", Arg2); if Arg3'Length = 0 then Generator.Set_Project_Property ("author", Get_Name_From_Email (Arg2)); else Generator.Set_Project_Property ("author", Arg3); end if; elsif Util.Strings.Index (Arg3, '@') > Arg3'First then Generator.Set_Project_Property ("author", Arg2); Generator.Set_Project_Property ("author_email", Arg3); elsif Arg3'Length > 0 then Generator.Error ("The last argument should be the author's email address."); Cmd.Usage (Name, Generator); return; end if; Generator.Set_Project_Property ("is_web", Boolean'Image (Web_Flag)); Generator.Set_Project_Property ("is_tool", Boolean'Image (Tool_Flag)); Generator.Set_Project_Property ("is_ado", Boolean'Image (Ado_Flag)); Generator.Set_Project_Property ("is_gtk", Boolean'Image (Gtk_Flag)); Generator.Set_Project_Property ("is_lib", Boolean'Image (Lib_Flag)); Generator.Set_Project_Name (Name); Generator.Set_Force_Save (False); if Ado_Flag then Gen.Generator.Generate_All (Generator, Gen.Artifacts.ITERATION_TABLE, "project-ado"); elsif Gtk_Flag then Gen.Generator.Generate_All (Generator, Gen.Artifacts.ITERATION_TABLE, "project-gtk"); elsif Tool_Flag then Gen.Generator.Generate_All (Generator, Gen.Artifacts.ITERATION_TABLE, "project-tool"); elsif Lib_Flag then Gen.Generator.Generate_All (Generator, Gen.Artifacts.ITERATION_TABLE, "project-lib"); else Gen.Generator.Generate_All (Generator, Gen.Artifacts.ITERATION_TABLE, "project"); end if; Generator.Save_Project; declare use type GNAT.OS_Lib.String_Access; Path : constant GNAT.OS_Lib.String_Access := GNAT.OS_Lib.Locate_Exec_On_Path ("autoconf"); Args : GNAT.OS_Lib.Argument_List (1 .. 0); Status : Boolean; begin if Path = null then Generator.Error ("The 'autoconf' tool was not found. It is necessary to " & "generate the configure script."); Generator.Error ("Install 'autoconf' or launch it manually."); else Ada.Directories.Set_Directory (Generator.Get_Result_Directory); Log.Info ("Executing {0}", Path.all); GNAT.OS_Lib.Spawn (Path.all, Args, Status); if not Status then Generator.Error ("Execution of {0} failed", Path.all); else Log.Info (""); Ada.Text_IO.Put_Line ("Your project is now created."); Ada.Text_IO.Put_Line ("Run the following commands to build it:"); Ada.Text_IO.Put_Line (" ./configure"); Ada.Text_IO.Put_Line (" make generate build"); end if; end if; end; end; end Execute; -- ------------------------------ -- Write the help associated with the command. -- ------------------------------ overriding procedure Help (Cmd : in out Command; Generator : in out Gen.Generator.Handler) is pragma Unreferenced (Cmd, Generator); use Ada.Text_IO; begin Put_Line ("create-project: Create a new Ada Web Application project"); Put_Line ("Usage: create-project [-l apache|gpl|gpl3|mit|bsd3|proprietary] [--web] [--tool]" & " [--lib] [--ado] [--gtk] NAME [AUTHOR] [EMAIL]"); New_Line; Put_Line (" Creates a new AWA application with the name passed in NAME."); Put_Line (" The application license is controlled with the -l option. "); Put_Line (" License headers can use either the Apache, the MIT license, the BSD 3 clauses"); Put_Line (" license, the GNU licenses or a proprietary license."); Put_Line (" The author's name and email addresses are also reported in generated files."); New_Line; Put_Line (" --web Generate a Web application (the default)"); Put_Line (" --tool Generate a command line tool"); Put_Line (" --ado Generate a database tool operation for ADO"); Put_Line (" --gtk Generate a GtkAda project"); Put_Line (" --lib Generate a library project"); end Help; end Gen.Commands.Project;
Add a hint message to build the application after it is generated
Add a hint message to build the application after it is generated
Ada
apache-2.0
stcarrez/dynamo,stcarrez/dynamo,stcarrez/dynamo
3f93fb2e70e5832bea4e883ce56951ffabbd2bb4
matp/src/symbols/mat-symbols-targets.ads
matp/src/symbols/mat-symbols-targets.ads
----------------------------------------------------------------------- -- mat-symbols-targets - Symbol files management -- Copyright (C) 2014, 2015 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Strings.Unbounded; with Ada.Containers.Ordered_Maps; with Bfd.Symbols; with Bfd.Files; with Bfd.Constants; with Util.Refs; with MAT.Types; with MAT.Memory.Targets; package MAT.Symbols.Targets is type Symbol_Info is record File : Ada.Strings.Unbounded.Unbounded_String; Name : Ada.Strings.Unbounded.Unbounded_String; Line : Natural; end record; -- The <tt>Region_Symbols</tt> holds the symbol table associated with the program or -- a shared library loaded by the program. The <tt>Region</tt> indicates -- the text segment address of the program or the loaded library. type Region_Symbols is new Util.Refs.Ref_Entity with record Region : MAT.Memory.Region_Info; Offset : MAT.Types.Target_Addr; File : Bfd.Files.File_Type; Symbols : Bfd.Symbols.Symbol_Table; end record; type Region_Symbols_Access is access all Region_Symbols; package Region_Symbols_Refs is new Util.Refs.References (Region_Symbols, Region_Symbols_Access); subtype Region_Symbols_Ref is Region_Symbols_Refs.Ref; -- The <tt>Symbols_Maps</tt> keeps a sorted list of symbol tables indexed -- by their mapping address. use type Region_Symbols_Refs.Ref; use type MAT.Types.Target_Addr; package Symbols_Maps is new Ada.Containers.Ordered_Maps (Key_Type => MAT.Types.Target_Addr, Element_Type => Region_Symbols_Ref); subtype Symbols_Map is Symbols_Maps.Map; subtype Symbols_Cursor is Symbols_Maps.Cursor; type Target_Symbols is new Util.Refs.Ref_Entity with record File : Bfd.Files.File_Type; Symbols : Bfd.Symbols.Symbol_Table; Libraries : Symbols_Maps.Map; Demangle : Bfd.Demangle_Flags := Bfd.Constants.DMGL_AUTO; end record; type Target_Symbols_Access is access all Target_Symbols; -- Open the binary and load the symbols from that file. procedure Open (Symbols : in out Target_Symbols; Path : in String); -- Load the symbols associated with a shared library described by the memory region. procedure Load_Symbols (Symbols : in out Target_Symbols; Region : in MAT.Memory.Region_Info; Offset_Addr : in MAT.Types.Target_Addr); -- Demangle the symbol. procedure Demangle (Symbols : in Target_Symbols; Symbol : in out Symbol_Info); -- Find the nearest source file and line for the given address. procedure Find_Nearest_Line (Symbols : in Target_Symbols; Addr : in MAT.Types.Target_Addr; Symbol : out Symbol_Info); package Target_Symbols_Refs is new Util.Refs.References (Target_Symbols, Target_Symbols_Access); subtype Target_Symbols_Ref is Target_Symbols_Refs.Ref; end MAT.Symbols.Targets;
----------------------------------------------------------------------- -- mat-symbols-targets - Symbol files management -- Copyright (C) 2014, 2015 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Strings.Unbounded; with Ada.Containers.Ordered_Maps; with Bfd.Symbols; with Bfd.Files; with Bfd.Constants; with Util.Refs; with MAT.Types; with MAT.Consoles; with MAT.Memory; package MAT.Symbols.Targets is type Symbol_Info is record File : Ada.Strings.Unbounded.Unbounded_String; Name : Ada.Strings.Unbounded.Unbounded_String; Line : Natural; end record; -- The <tt>Region_Symbols</tt> holds the symbol table associated with the program or -- a shared library loaded by the program. The <tt>Region</tt> indicates -- the text segment address of the program or the loaded library. type Region_Symbols is new Util.Refs.Ref_Entity with record Region : MAT.Memory.Region_Info; Offset : MAT.Types.Target_Addr; File : Bfd.Files.File_Type; Symbols : Bfd.Symbols.Symbol_Table; end record; type Region_Symbols_Access is access all Region_Symbols; -- Load the symbol table for the associated region. procedure Open (Symbols : in out Region_Symbols; Path : in String); package Region_Symbols_Refs is new Util.Refs.References (Region_Symbols, Region_Symbols_Access); subtype Region_Symbols_Ref is Region_Symbols_Refs.Ref; -- The <tt>Symbols_Maps</tt> keeps a sorted list of symbol tables indexed -- by their mapping address. use type Region_Symbols_Refs.Ref; use type MAT.Types.Target_Addr; package Symbols_Maps is new Ada.Containers.Ordered_Maps (Key_Type => MAT.Types.Target_Addr, Element_Type => Region_Symbols_Ref); subtype Symbols_Map is Symbols_Maps.Map; subtype Symbols_Cursor is Symbols_Maps.Cursor; type Target_Symbols is new Util.Refs.Ref_Entity with record Path : Ada.Strings.Unbounded.Unbounded_String; File : Bfd.Files.File_Type; Symbols : Bfd.Symbols.Symbol_Table; Libraries : Symbols_Maps.Map; Demangle : Bfd.Demangle_Flags := Bfd.Constants.DMGL_AUTO; Console : MAT.Consoles.Console_Access; end record; type Target_Symbols_Access is access all Target_Symbols; -- Open the binary and load the symbols from that file. procedure Open (Symbols : in out Target_Symbols; Path : in String); -- Load the symbols associated with a shared library described by the memory region. procedure Load_Symbols (Symbols : in out Target_Symbols; Region : in MAT.Memory.Region_Info; Offset_Addr : in MAT.Types.Target_Addr); -- Load the symbols associated with all the shared libraries described by -- the memory region map. procedure Load_Symbols (Symbols : in out Target_Symbols; Regions : in MAT.Memory.Region_Info_Map); -- Demangle the symbol. procedure Demangle (Symbols : in Target_Symbols; Symbol : in out Symbol_Info); -- Find the nearest source file and line for the given address. procedure Find_Nearest_Line (Symbols : in Target_Symbols; Addr : in MAT.Types.Target_Addr; Symbol : out Symbol_Info); package Target_Symbols_Refs is new Util.Refs.References (Target_Symbols, Target_Symbols_Access); subtype Target_Symbols_Ref is Target_Symbols_Refs.Ref; end MAT.Symbols.Targets;
Declare the Load_Symbols procedure with a memory region map to load all the symbols of shared libraries loaded by the program
Declare the Load_Symbols procedure with a memory region map to load all the symbols of shared libraries loaded by the program
Ada
apache-2.0
stcarrez/mat,stcarrez/mat,stcarrez/mat
43307a6b677a69ff0575aebadd53529da8850581
src/asf-servlets-ajax.ads
src/asf-servlets-ajax.ads
----------------------------------------------------------------------- -- asf.servlets.ajax -- AJAX servlet -- 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 ASF.Applications.Main; package ASF.Servlets.Ajax is -- ------------------------------ -- Ajax Servlet -- ------------------------------ -- The <b>Ajax_Servlet</b> defines a servlet used to process Ajax actions -- on ASF bean objects. -- URI have the following format: -- -- /<bean-name>/<method-name>[/<param-name>/<value>] type Ajax_Servlet is new Servlet with private; -- Called by the servlet container to indicate to a servlet that the servlet -- is being placed into service. overriding procedure Initialize (Server : in out Ajax_Servlet; Context : in Servlet_Registry'Class); -- Called by the server (via the service method) to allow a servlet to handle -- a GET request. -- -- GET requests are not permitted. -- -- Returns 403 error. procedure Do_Get (Server : in Ajax_Servlet; Request : in out Requests.Request'Class; Response : in out Responses.Response'Class); -- Called by the server (via the service method) to allow a servlet to handle -- a POST request. The HTTP POST method allows the client to send data of unlimited -- length to the Web server a single time and is useful when posting information -- such as credit card numbers. -- -- 1. Split the URI into a bean name, an action method name and a list of parameters. -- 2. Find the bean object in the application (create it if necessary). -- 3. For each parameter, invoke the <b>Set_Value</b> bean method. -- 4. Invoke the bean action method (specified in the second URI component). -- 5. Navigate to the result view according to the action outcome result. -- 6. Execute the navigation (render page, redirect, ... -- -- If an error is found, return SC_NOT_FOUND if an object or method cannot be found. procedure Do_Post (Server : in Ajax_Servlet; Request : in out Requests.Request'Class; Response : in out Responses.Response'Class); private type Ajax_Servlet is new Servlet with record App : ASF.Applications.Main.Application_Access; end record; end ASF.Servlets.Ajax;
----------------------------------------------------------------------- -- asf.servlets.ajax -- AJAX servlet -- Copyright (C) 2011, 2018 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with ASF.Applications.Main; with ASF.Requests; with ASF.Responses; package ASF.Servlets.Ajax is -- ------------------------------ -- Ajax Servlet -- ------------------------------ -- The <b>Ajax_Servlet</b> defines a servlet used to process Ajax actions -- on ASF bean objects. -- URI have the following format: -- -- /<bean-name>/<method-name>[/<param-name>/<value>] type Ajax_Servlet is new Servlet.Core.Servlet with private; -- Called by the servlet container to indicate to a servlet that the servlet -- is being placed into service. overriding procedure Initialize (Server : in out Ajax_Servlet; Context : in Servlet_Registry'Class); -- Called by the server (via the service method) to allow a servlet to handle -- a GET request. -- -- GET requests are not permitted. -- -- Returns 403 error. procedure Do_Get (Server : in Ajax_Servlet; Request : in out Requests.Request'Class; Response : in out Responses.Response'Class); -- Called by the server (via the service method) to allow a servlet to handle -- a POST request. The HTTP POST method allows the client to send data of unlimited -- length to the Web server a single time and is useful when posting information -- such as credit card numbers. -- -- 1. Split the URI into a bean name, an action method name and a list of parameters. -- 2. Find the bean object in the application (create it if necessary). -- 3. For each parameter, invoke the <b>Set_Value</b> bean method. -- 4. Invoke the bean action method (specified in the second URI component). -- 5. Navigate to the result view according to the action outcome result. -- 6. Execute the navigation (render page, redirect, ... -- -- If an error is found, return SC_NOT_FOUND if an object or method cannot be found. procedure Do_Post (Server : in Ajax_Servlet; Request : in out Requests.Request'Class; Response : in out Responses.Response'Class); private type Ajax_Servlet is new Servlet.Core.Servlet with record App : ASF.Applications.Main.Application_Access; end record; end ASF.Servlets.Ajax;
Package ASF.Servlets moved to Servlet.Core.
Package ASF.Servlets moved to Servlet.Core.
Ada
apache-2.0
stcarrez/ada-asf,stcarrez/ada-asf,stcarrez/ada-asf
f03d887942657713039e99df2dd39e82c420236b
awa/plugins/awa-storages/src/awa-storages-services.adb
awa/plugins/awa-storages/src/awa-storages-services.adb
----------------------------------------------------------------------- -- awa-storages-services -- Storage service -- Copyright (C) 2012 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Calendar; with Util.Log.Loggers; with ADO.Objects; with ADO.Queries; with ADO.Statements; with ADO.Sessions.Entities; with AWA.Services.Contexts; with AWA.Workspaces.Models; with AWA.Workspaces.Modules; with AWA.Permissions; with AWA.Storages.Stores.Files; package body AWA.Storages.Services is use AWA.Services; Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("AWA.Storages.Services"); -- ------------------------------ -- Get the persistent store that manages the data store identified by <tt>Kind</tt>. -- ------------------------------ function Get_Store (Service : in Storage_Service; Kind : in AWA.Storages.Models.Storage_Type) return AWA.Storages.Stores.Store_Access is begin return Service.Stores (Kind); end Get_Store; -- ------------------------------ -- Initializes the storage service. -- ------------------------------ overriding procedure Initialize (Service : in out Storage_Service; Module : in AWA.Modules.Module'Class) is Root : constant String := Module.Get_Config (Stores.Files.Root_Directory_Parameter.P); Tmp : constant String := Module.Get_Config (Stores.Files.Tmp_Directory_Parameter.P); begin AWA.Modules.Module_Manager (Service).Initialize (Module); Service.Stores (Storages.Models.DATABASE) := Service.Database_Store'Unchecked_Access; Service.Stores (Storages.Models.FILE) := AWA.Storages.Stores.Files.Create_File_Store (Root); Service.Stores (Storages.Models.TMP) := AWA.Storages.Stores.Files.Create_File_Store (Tmp); Service.Database_Store.Tmp := Service.Stores (Storages.Models.TMP); end Initialize; -- ------------------------------ -- Create or save the folder. -- ------------------------------ procedure Save_Folder (Service : in Storage_Service; Folder : in out AWA.Storages.Models.Storage_Folder_Ref'Class) is pragma Unreferenced (Service); Ctx : constant Contexts.Service_Context_Access := AWA.Services.Contexts.Current; DB : ADO.Sessions.Master_Session := AWA.Services.Contexts.Get_Master_Session (Ctx); Workspace : AWA.Workspaces.Models.Workspace_Ref; begin if not Folder.Is_Null then Workspace := AWA.Workspaces.Models.Workspace_Ref (Folder.Get_Workspace); end if; if Workspace.Is_Null then AWA.Workspaces.Modules.Get_Workspace (DB, Ctx, Workspace); Folder.Set_Workspace (Workspace); end if; -- Check that the user has the create folder permission on the given workspace. AWA.Permissions.Check (Permission => ACL_Create_Folder.Permission, Entity => Workspace.Get_Id); Ctx.Start; if not Folder.Is_Inserted then Folder.Set_Create_Date (Ada.Calendar.Clock); Folder.Set_Owner (Ctx.Get_User); end if; Folder.Save (DB); Ctx.Commit; end Save_Folder; -- ------------------------------ -- Load the folder instance identified by the given identifier. -- ------------------------------ procedure Load_Folder (Service : in Storage_Service; Folder : in out AWA.Storages.Models.Storage_Folder_Ref'Class; Id : in ADO.Identifier) is pragma Unreferenced (Service); Ctx : constant Contexts.Service_Context_Access := AWA.Services.Contexts.Current; DB : ADO.Sessions.Master_Session := AWA.Services.Contexts.Get_Master_Session (Ctx); begin Folder.Load (Session => DB, Id => Id); end Load_Folder; -- ------------------------------ -- Load the storage instance identified by the given identifier. -- ------------------------------ procedure Load_Storage (Service : in Storage_Service; Storage : in out AWA.Storages.Models.Storage_Ref'Class; Id : in ADO.Identifier) is pragma Unreferenced (Service); Ctx : constant Contexts.Service_Context_Access := AWA.Services.Contexts.Current; DB : ADO.Sessions.Session := AWA.Services.Contexts.Get_Session (Ctx); begin Storage.Load (Session => DB, Id => Id); end Load_Storage; -- ------------------------------ -- Save the data object contained in the <b>Data</b> part element into the -- target storage represented by <b>Into</b>. -- ------------------------------ procedure Save (Service : in Storage_Service; Into : in out AWA.Storages.Models.Storage_Ref'Class; Data : in ASF.Parts.Part'Class; Storage : in AWA.Storages.Models.Storage_Type) is begin Storage_Service'Class (Service).Save (Into, Data.Get_Local_Filename, Storage); end Save; -- ------------------------------ -- Save the file pointed to by the <b>Path</b> string in the storage -- object represented by <b>Into</b> and managed by the storage service. -- ------------------------------ procedure Save (Service : in Storage_Service; Into : in out AWA.Storages.Models.Storage_Ref'Class; Path : in String; Storage : in AWA.Storages.Models.Storage_Type) is use type AWA.Storages.Models.Storage_Type; use type Stores.Store_Access; Ctx : constant Contexts.Service_Context_Access := AWA.Services.Contexts.Current; DB : ADO.Sessions.Master_Session := AWA.Services.Contexts.Get_Master_Session (Ctx); Workspace : AWA.Workspaces.Models.Workspace_Ref; Store : Stores.Store_Access; Created : Boolean; begin Log.Info ("Save {0} in storage space", Path); Into.Set_Storage (Storage); Store := Storage_Service'Class (Service).Get_Store (Into.Get_Storage); if Store = null then Log.Error ("There is no store for storage {0}", Models.Storage_Type'Image (Storage)); end if; if not Into.Is_Null then Workspace := AWA.Workspaces.Models.Workspace_Ref (Into.Get_Workspace); end if; if Workspace.Is_Null then AWA.Workspaces.Modules.Get_Workspace (DB, Ctx, Workspace); Into.Set_Workspace (Workspace); end if; -- Check that the user has the create storage permission on the given workspace. AWA.Permissions.Check (Permission => ACL_Create_Storage.Permission, Entity => Workspace.Get_Id); Ctx.Start; Created := not Into.Is_Inserted; if Created then Into.Set_Create_Date (Ada.Calendar.Clock); Into.Set_Owner (Ctx.Get_User); end if; Into.Save (DB); Store.Save (DB, Into, Path); Into.Save (DB); -- Notify the listeners. if Created then Storage_Lifecycle.Notify_Create (Service, Into); else Storage_Lifecycle.Notify_Update (Service, Into); end if; Ctx.Commit; end Save; -- ------------------------------ -- Load the storage content identified by <b>From</b> into the blob descriptor <b>Into</b>. -- Raises the <b>NOT_FOUND</b> exception if there is no such storage. -- ------------------------------ procedure Load (Service : in Storage_Service; From : in ADO.Identifier; Name : out Ada.Strings.Unbounded.Unbounded_String; Mime : out Ada.Strings.Unbounded.Unbounded_String; Date : out Ada.Calendar.Time; Into : out ADO.Blob_Ref) is use type AWA.Storages.Models.Storage_Type; use type AWA.Storages.Stores.Store_Access; Ctx : constant Contexts.Service_Context_Access := AWA.Services.Contexts.Current; User : constant ADO.Identifier := Ctx.Get_User_Identifier; DB : ADO.Sessions.Session := AWA.Services.Contexts.Get_Session (Ctx); Query : ADO.Statements.Query_Statement := DB.Create_Statement (Models.Query_Storage_Get_Data); Kind : AWA.Storages.Models.Storage_Type; begin Query.Bind_Param ("store_id", From); Query.Bind_Param ("user_id", User); ADO.Sessions.Entities.Bind_Param (Query, "table", AWA.Workspaces.Models.WORKSPACE_TABLE, DB); Query.Execute; if not Query.Has_Elements then Log.Warn ("Storage entity {0} not found", ADO.Identifier'Image (From)); raise ADO.Objects.NOT_FOUND; end if; Mime := Query.Get_Unbounded_String (0); Date := Query.Get_Time (1); Name := Query.Get_Unbounded_String (2); Kind := AWA.Storages.Models.Storage_Type'Val (Query.Get_Integer (4)); if Kind = AWA.Storages.Models.DATABASE then Into := Query.Get_Blob (5); else declare Store : Stores.Store_Access; Storage : AWA.Storages.Models.Storage_Ref; File : AWA.Storages.Storage_File; Found : Boolean; begin Store := Storage_Service'Class (Service).Get_Store (Kind); if Store = null then Log.Error ("There is no store for storage {0}", Models.Storage_Type'Image (Kind)); end if; Storage.Load (DB, From, Found); if not Found then Log.Warn ("Storage entity {0} not found", ADO.Identifier'Image (From)); raise ADO.Objects.NOT_FOUND; end if; Store.Load (DB, Storage, File); Into := ADO.Create_Blob (AWA.Storages.Get_Path (File)); end; end if; end Load; -- Load the storage content into a file. If the data is not stored in a file, a temporary -- file is created with the data content fetched from the store (ex: the database). -- The `Mode` parameter indicates whether the file will be read or written. -- The `Expire` parameter allows to control the expiration of the temporary file. procedure Get_Local_File (Service : in Storage_Service; From : in ADO.Identifier; Mode : in Read_Mode := READ; Into : out Storage_File) is use type Stores.Store_Access; use type Models.Storage_Type; Ctx : constant Contexts.Service_Context_Access := AWA.Services.Contexts.Current; User : constant ADO.Identifier := Ctx.Get_User_Identifier; DB : ADO.Sessions.Master_Session := AWA.Services.Contexts.Get_Master_Session (Ctx); Query : ADO.Queries.Context; Found : Boolean; Storage : AWA.Storages.Models.Storage_Ref; Local : AWA.Storages.Models.Store_Local_Ref; Store : Stores.Store_Access; begin if Mode = READ then Query.Set_Query (AWA.Storages.Models.Query_Storage_Get_Local); Query.Bind_Param ("store_id", From); Query.Bind_Param ("user_id", User); ADO.Sessions.Entities.Bind_Param (Query, "table", AWA.Workspaces.Models.WORKSPACE_TABLE, DB); Local.Find (DB, Query, Found); if Found then Into.Path := Local.Get_Path; return; end if; end if; Query.Set_Query (AWA.Storages.Models.Query_Storage_Get_Storage); Query.Bind_Param ("store_id", From); Query.Bind_Param ("user_id", User); ADO.Sessions.Entities.Bind_Param (Query, "table", AWA.Workspaces.Models.WORKSPACE_TABLE, DB); Storage.Find (DB, Query, Found); if not Found then raise ADO.Objects.NOT_FOUND; end if; Ctx.Start; Store := Storage_Service'Class (Service).Get_Store (Storage.Get_Storage); Store.Load (Session => DB, From => Storage, Into => Into); Ctx.Commit; end Get_Local_File; procedure Create_Local_File (Service : in Storage_Service; Into : out Storage_File) is begin null; end Create_Local_File; -- ------------------------------ -- Deletes the storage instance. -- ------------------------------ procedure Delete (Service : in Storage_Service; Storage : in out AWA.Storages.Models.Storage_Ref'Class) is Ctx : constant Contexts.Service_Context_Access := AWA.Services.Contexts.Current; DB : ADO.Sessions.Master_Session := AWA.Services.Contexts.Get_Master_Session (Ctx); Id : constant ADO.Identifier := ADO.Objects.Get_Value (Storage.Get_Key); begin Log.Info ("Delete storage {0}", ADO.Identifier'Image (Id)); -- Check that the user has the delete storage permission on the given workspace. AWA.Permissions.Check (Permission => ACL_Delete_Storage.Permission, Entity => Id); Ctx.Start; Storage_Lifecycle.Notify_Delete (Service, Storage); Storage.Delete (DB); Ctx.Commit; end Delete; -- ------------------------------ -- Deletes the storage instance. -- ------------------------------ procedure Delete (Service : in Storage_Service; Storage : in ADO.Identifier) is use type Stores.Store_Access; Ctx : constant Contexts.Service_Context_Access := AWA.Services.Contexts.Current; DB : ADO.Sessions.Master_Session := AWA.Services.Contexts.Get_Master_Session (Ctx); S : AWA.Storages.Models.Storage_Ref; Query : ADO.Statements.Query_Statement := DB.Create_Statement (AWA.Storages.Models.Query_Storage_Delete_Local); Store : Stores.Store_Access; begin Log.Info ("Delete storage {0}", ADO.Identifier'Image (Storage)); -- Check that the user has the delete storage permission on the given workspace. AWA.Permissions.Check (Permission => ACL_Delete_Storage.Permission, Entity => Storage); Ctx.Start; S.Load (Id => Storage, Session => DB); Store := Storage_Service'Class (Service).Get_Store (S.Get_Storage); if Store = null then Log.Error ("There is no store associated with storage item {0}", ADO.Identifier'Image (Storage)); else Store.Delete (DB, S); end if; Storage_Lifecycle.Notify_Delete (Service, S); -- Delete the storage instance and all storage that refer to it. declare Stmt : ADO.Statements.Delete_Statement := DB.Create_Statement (AWA.Storages.Models.STORAGE_TABLE); begin Stmt.Set_Filter (Filter => "id = ? OR original_id = ?"); Stmt.Add_Param (Value => Storage); Stmt.Add_Param (Value => Storage); Stmt.Execute; end; -- Delete the local storage instances. Query.Bind_Param ("store_id", Storage); Query.Execute; S.Delete (DB); Ctx.Commit; end Delete; end AWA.Storages.Services;
----------------------------------------------------------------------- -- awa-storages-services -- 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 Ada.Calendar; with Util.Log.Loggers; with ADO.Objects; with ADO.Queries; with ADO.Statements; with ADO.Sessions.Entities; with AWA.Services.Contexts; with AWA.Workspaces.Models; with AWA.Workspaces.Modules; with AWA.Permissions; with AWA.Storages.Stores.Files; package body AWA.Storages.Services is use AWA.Services; Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("AWA.Storages.Services"); -- ------------------------------ -- Get the persistent store that manages the data store identified by <tt>Kind</tt>. -- ------------------------------ function Get_Store (Service : in Storage_Service; Kind : in AWA.Storages.Models.Storage_Type) return AWA.Storages.Stores.Store_Access is begin return Service.Stores (Kind); end Get_Store; -- ------------------------------ -- Initializes the storage service. -- ------------------------------ overriding procedure Initialize (Service : in out Storage_Service; Module : in AWA.Modules.Module'Class) is Root : constant String := Module.Get_Config (Stores.Files.Root_Directory_Parameter.P); Tmp : constant String := Module.Get_Config (Stores.Files.Tmp_Directory_Parameter.P); begin AWA.Modules.Module_Manager (Service).Initialize (Module); Service.Stores (Storages.Models.DATABASE) := Service.Database_Store'Unchecked_Access; Service.Stores (Storages.Models.FILE) := AWA.Storages.Stores.Files.Create_File_Store (Root); Service.Stores (Storages.Models.TMP) := AWA.Storages.Stores.Files.Create_File_Store (Tmp); Service.Database_Store.Tmp := Service.Stores (Storages.Models.TMP); end Initialize; -- ------------------------------ -- Create or save the folder. -- ------------------------------ procedure Save_Folder (Service : in Storage_Service; Folder : in out AWA.Storages.Models.Storage_Folder_Ref'Class) is pragma Unreferenced (Service); Ctx : constant Contexts.Service_Context_Access := AWA.Services.Contexts.Current; DB : ADO.Sessions.Master_Session := AWA.Services.Contexts.Get_Master_Session (Ctx); Workspace : AWA.Workspaces.Models.Workspace_Ref; begin if not Folder.Is_Null then Workspace := AWA.Workspaces.Models.Workspace_Ref (Folder.Get_Workspace); end if; if Workspace.Is_Null then AWA.Workspaces.Modules.Get_Workspace (DB, Ctx, Workspace); Folder.Set_Workspace (Workspace); end if; -- Check that the user has the create folder permission on the given workspace. AWA.Permissions.Check (Permission => ACL_Create_Folder.Permission, Entity => Workspace); Ctx.Start; if not Folder.Is_Inserted then Folder.Set_Create_Date (Ada.Calendar.Clock); Folder.Set_Owner (Ctx.Get_User); end if; Folder.Save (DB); Ctx.Commit; end Save_Folder; -- ------------------------------ -- Load the folder instance identified by the given identifier. -- ------------------------------ procedure Load_Folder (Service : in Storage_Service; Folder : in out AWA.Storages.Models.Storage_Folder_Ref'Class; Id : in ADO.Identifier) is pragma Unreferenced (Service); Ctx : constant Contexts.Service_Context_Access := AWA.Services.Contexts.Current; DB : ADO.Sessions.Master_Session := AWA.Services.Contexts.Get_Master_Session (Ctx); begin Folder.Load (Session => DB, Id => Id); end Load_Folder; -- ------------------------------ -- Load the storage instance identified by the given identifier. -- ------------------------------ procedure Load_Storage (Service : in Storage_Service; Storage : in out AWA.Storages.Models.Storage_Ref'Class; Id : in ADO.Identifier) is pragma Unreferenced (Service); Ctx : constant Contexts.Service_Context_Access := AWA.Services.Contexts.Current; DB : ADO.Sessions.Session := AWA.Services.Contexts.Get_Session (Ctx); begin Storage.Load (Session => DB, Id => Id); end Load_Storage; -- ------------------------------ -- Save the data object contained in the <b>Data</b> part element into the -- target storage represented by <b>Into</b>. -- ------------------------------ procedure Save (Service : in Storage_Service; Into : in out AWA.Storages.Models.Storage_Ref'Class; Data : in ASF.Parts.Part'Class; Storage : in AWA.Storages.Models.Storage_Type) is begin Storage_Service'Class (Service).Save (Into, Data.Get_Local_Filename, Storage); end Save; -- ------------------------------ -- Save the file pointed to by the <b>Path</b> string in the storage -- object represented by <b>Into</b> and managed by the storage service. -- ------------------------------ procedure Save (Service : in Storage_Service; Into : in out AWA.Storages.Models.Storage_Ref'Class; Path : in String; Storage : in AWA.Storages.Models.Storage_Type) is use type AWA.Storages.Models.Storage_Type; use type Stores.Store_Access; Ctx : constant Contexts.Service_Context_Access := AWA.Services.Contexts.Current; DB : ADO.Sessions.Master_Session := AWA.Services.Contexts.Get_Master_Session (Ctx); Workspace : AWA.Workspaces.Models.Workspace_Ref; Store : Stores.Store_Access; Created : Boolean; begin Log.Info ("Save {0} in storage space", Path); Into.Set_Storage (Storage); Store := Storage_Service'Class (Service).Get_Store (Into.Get_Storage); if Store = null then Log.Error ("There is no store for storage {0}", Models.Storage_Type'Image (Storage)); end if; if not Into.Is_Null then Workspace := AWA.Workspaces.Models.Workspace_Ref (Into.Get_Workspace); end if; if Workspace.Is_Null then AWA.Workspaces.Modules.Get_Workspace (DB, Ctx, Workspace); Into.Set_Workspace (Workspace); end if; -- Check that the user has the create storage permission on the given workspace. AWA.Permissions.Check (Permission => ACL_Create_Storage.Permission, Entity => Workspace); Ctx.Start; Created := not Into.Is_Inserted; if Created then Into.Set_Create_Date (Ada.Calendar.Clock); Into.Set_Owner (Ctx.Get_User); end if; Into.Save (DB); Store.Save (DB, Into, Path); Into.Save (DB); -- Notify the listeners. if Created then Storage_Lifecycle.Notify_Create (Service, Into); else Storage_Lifecycle.Notify_Update (Service, Into); end if; Ctx.Commit; end Save; -- ------------------------------ -- Load the storage content identified by <b>From</b> into the blob descriptor <b>Into</b>. -- Raises the <b>NOT_FOUND</b> exception if there is no such storage. -- ------------------------------ procedure Load (Service : in Storage_Service; From : in ADO.Identifier; Name : out Ada.Strings.Unbounded.Unbounded_String; Mime : out Ada.Strings.Unbounded.Unbounded_String; Date : out Ada.Calendar.Time; Into : out ADO.Blob_Ref) is use type AWA.Storages.Models.Storage_Type; use type AWA.Storages.Stores.Store_Access; Ctx : constant Contexts.Service_Context_Access := AWA.Services.Contexts.Current; User : constant ADO.Identifier := Ctx.Get_User_Identifier; DB : ADO.Sessions.Session := AWA.Services.Contexts.Get_Session (Ctx); Query : ADO.Statements.Query_Statement := DB.Create_Statement (Models.Query_Storage_Get_Data); Kind : AWA.Storages.Models.Storage_Type; begin Query.Bind_Param ("store_id", From); Query.Bind_Param ("user_id", User); ADO.Sessions.Entities.Bind_Param (Query, "table", AWA.Workspaces.Models.WORKSPACE_TABLE, DB); Query.Execute; if not Query.Has_Elements then Log.Warn ("Storage entity {0} not found", ADO.Identifier'Image (From)); raise ADO.Objects.NOT_FOUND; end if; Mime := Query.Get_Unbounded_String (0); Date := Query.Get_Time (1); Name := Query.Get_Unbounded_String (2); Kind := AWA.Storages.Models.Storage_Type'Val (Query.Get_Integer (4)); if Kind = AWA.Storages.Models.DATABASE then Into := Query.Get_Blob (5); else declare Store : Stores.Store_Access; Storage : AWA.Storages.Models.Storage_Ref; File : AWA.Storages.Storage_File; Found : Boolean; begin Store := Storage_Service'Class (Service).Get_Store (Kind); if Store = null then Log.Error ("There is no store for storage {0}", Models.Storage_Type'Image (Kind)); end if; Storage.Load (DB, From, Found); if not Found then Log.Warn ("Storage entity {0} not found", ADO.Identifier'Image (From)); raise ADO.Objects.NOT_FOUND; end if; Store.Load (DB, Storage, File); Into := ADO.Create_Blob (AWA.Storages.Get_Path (File)); end; end if; end Load; -- Load the storage content into a file. If the data is not stored in a file, a temporary -- file is created with the data content fetched from the store (ex: the database). -- The `Mode` parameter indicates whether the file will be read or written. -- The `Expire` parameter allows to control the expiration of the temporary file. procedure Get_Local_File (Service : in Storage_Service; From : in ADO.Identifier; Mode : in Read_Mode := READ; Into : out Storage_File) is use type Stores.Store_Access; use type Models.Storage_Type; Ctx : constant Contexts.Service_Context_Access := AWA.Services.Contexts.Current; User : constant ADO.Identifier := Ctx.Get_User_Identifier; DB : ADO.Sessions.Master_Session := AWA.Services.Contexts.Get_Master_Session (Ctx); Query : ADO.Queries.Context; Found : Boolean; Storage : AWA.Storages.Models.Storage_Ref; Local : AWA.Storages.Models.Store_Local_Ref; Store : Stores.Store_Access; begin if Mode = READ then Query.Set_Query (AWA.Storages.Models.Query_Storage_Get_Local); Query.Bind_Param ("store_id", From); Query.Bind_Param ("user_id", User); ADO.Sessions.Entities.Bind_Param (Query, "table", AWA.Workspaces.Models.WORKSPACE_TABLE, DB); Local.Find (DB, Query, Found); if Found then Into.Path := Local.Get_Path; return; end if; end if; Query.Set_Query (AWA.Storages.Models.Query_Storage_Get_Storage); Query.Bind_Param ("store_id", From); Query.Bind_Param ("user_id", User); ADO.Sessions.Entities.Bind_Param (Query, "table", AWA.Workspaces.Models.WORKSPACE_TABLE, DB); Storage.Find (DB, Query, Found); if not Found then raise ADO.Objects.NOT_FOUND; end if; Ctx.Start; Store := Storage_Service'Class (Service).Get_Store (Storage.Get_Storage); Store.Load (Session => DB, From => Storage, Into => Into); Ctx.Commit; end Get_Local_File; procedure Create_Local_File (Service : in Storage_Service; Into : out Storage_File) is begin null; end Create_Local_File; -- ------------------------------ -- Deletes the storage instance. -- ------------------------------ procedure Delete (Service : in Storage_Service; Storage : in out AWA.Storages.Models.Storage_Ref'Class) is Ctx : constant Contexts.Service_Context_Access := AWA.Services.Contexts.Current; DB : ADO.Sessions.Master_Session := AWA.Services.Contexts.Get_Master_Session (Ctx); Id : constant ADO.Identifier := ADO.Objects.Get_Value (Storage.Get_Key); begin Log.Info ("Delete storage {0}", ADO.Identifier'Image (Id)); -- Check that the user has the delete storage permission on the given workspace. AWA.Permissions.Check (Permission => ACL_Delete_Storage.Permission, Entity => Id); Ctx.Start; Storage_Lifecycle.Notify_Delete (Service, Storage); Storage.Delete (DB); Ctx.Commit; end Delete; -- ------------------------------ -- Deletes the storage instance. -- ------------------------------ procedure Delete (Service : in Storage_Service; Storage : in ADO.Identifier) is use type Stores.Store_Access; Ctx : constant Contexts.Service_Context_Access := AWA.Services.Contexts.Current; DB : ADO.Sessions.Master_Session := AWA.Services.Contexts.Get_Master_Session (Ctx); S : AWA.Storages.Models.Storage_Ref; Query : ADO.Statements.Query_Statement := DB.Create_Statement (AWA.Storages.Models.Query_Storage_Delete_Local); Store : Stores.Store_Access; begin Log.Info ("Delete storage {0}", ADO.Identifier'Image (Storage)); -- Check that the user has the delete storage permission on the given workspace. AWA.Permissions.Check (Permission => ACL_Delete_Storage.Permission, Entity => Storage); Ctx.Start; S.Load (Id => Storage, Session => DB); Store := Storage_Service'Class (Service).Get_Store (S.Get_Storage); if Store = null then Log.Error ("There is no store associated with storage item {0}", ADO.Identifier'Image (Storage)); else Store.Delete (DB, S); end if; Storage_Lifecycle.Notify_Delete (Service, S); -- Delete the storage instance and all storage that refer to it. declare Stmt : ADO.Statements.Delete_Statement := DB.Create_Statement (AWA.Storages.Models.STORAGE_TABLE); begin Stmt.Set_Filter (Filter => "id = ? OR original_id = ?"); Stmt.Add_Param (Value => Storage); Stmt.Add_Param (Value => Storage); Stmt.Execute; end; -- Delete the local storage instances. Query.Bind_Param ("store_id", Storage); Query.Execute; S.Delete (DB); Ctx.Commit; end Delete; end AWA.Storages.Services;
Use the Check permission by using the database object so that we can check for null object
Use the Check permission by using the database object so that we can check for null object
Ada
apache-2.0
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
193f5d46a063205f8f56f06b61d65790d8d2f168
src/lzma/util-encoders-lzma.adb
src/lzma/util-encoders-lzma.adb
----------------------------------------------------------------------- -- util-encoders-lzma -- LZMA compression and decompression -- Copyright (C) 2018 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Lzma.Check; with Lzma.Container; with Interfaces.C; package body Util.Encoders.Lzma is use type Interfaces.C.size_t; use type Ada.Streams.Stream_Element_Offset; use type Base.lzma_ret; subtype Offset is Ada.Streams.Stream_Element_Offset; -- ------------------------------ -- Compress the binary input stream represented by <b>Data</b> by using -- the LZMA compression into the output stream <b>Into</b>. -- -- If the transformer does not have enough room to write the result, -- it must return in <b>Encoded</b> the index of the last encoded -- position in the <b>Data</b> stream. -- -- The transformer returns in <b>Last</b> the last valid position -- in the output stream <b>Into</b>. -- -- The <b>Encoding_Error</b> exception is raised if the input -- stream cannot be transformed. -- ------------------------------ overriding procedure Transform (E : in out Compress; Data : in Ada.Streams.Stream_Element_Array; Into : out Ada.Streams.Stream_Element_Array; Last : out Ada.Streams.Stream_Element_Offset; Encoded : out Ada.Streams.Stream_Element_Offset) is Result : Base.lzma_ret; begin E.Stream.next_out := Into (Into'First)'Unchecked_Access; E.Stream.avail_out := Into'Length; E.Stream.next_in := Data (Data'First)'Unrestricted_Access; E.Stream.avail_in := Interfaces.C.size_t (Data'Length); loop Result := Base.lzma_code (E.Stream'Unchecked_Access, Base.LZMA_RUN); -- Write the output data when the buffer is full or we reached the end of stream. if E.Stream.avail_out = 0 or E.Stream.avail_in = 0 or Result = Base.LZMA_STREAM_END then Last := Into'First + Into'Length - Offset (E.Stream.avail_out) - 1; Encoded := Data'First + Data'Length - Offset (E.Stream.avail_in); return; end if; exit when Result /= Base.LZMA_OK; end loop; end Transform; -- ------------------------------ -- Finish compression of the input array. -- ------------------------------ overriding procedure Finish (E : in out Compress; Into : in out Ada.Streams.Stream_Element_Array; Last : in out Ada.Streams.Stream_Element_Offset) is Result : Base.lzma_ret; pragma Unreferenced (Result); begin E.Stream.next_out := Into (Into'First)'Unchecked_Access; E.Stream.avail_out := Into'Length; E.Stream.next_in := null; E.Stream.avail_in := 0; Result := Base.lzma_code (E.Stream'Unchecked_Access, Base.LZMA_FINISH); Last := Into'First + Into'Length - Offset (E.Stream.avail_out) - 1; end Finish; overriding procedure Initialize (E : in out Compress) is Result : Base.lzma_ret; pragma Unreferenced (Result); begin Result := Container.lzma_easy_encoder (E.Stream'Unchecked_Access, 6, Check.LZMA_CHECK_CRC64); end Initialize; overriding procedure Finalize (E : in out Compress) is begin Base.lzma_end (E.Stream'Unchecked_Access); end Finalize; end Util.Encoders.Lzma;
----------------------------------------------------------------------- -- util-encoders-lzma -- LZMA compression and decompression -- Copyright (C) 2018 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Lzma.Check; with Lzma.Container; with Interfaces.C; package body Util.Encoders.Lzma is use type Interfaces.C.size_t; use type Ada.Streams.Stream_Element_Offset; use type Base.lzma_ret; subtype Offset is Ada.Streams.Stream_Element_Offset; -- ------------------------------ -- Compress the binary input stream represented by <b>Data</b> by using -- the LZMA compression into the output stream <b>Into</b>. -- -- If the transformer does not have enough room to write the result, -- it must return in <b>Encoded</b> the index of the last encoded -- position in the <b>Data</b> stream. -- -- The transformer returns in <b>Last</b> the last valid position -- in the output stream <b>Into</b>. -- -- The <b>Encoding_Error</b> exception is raised if the input -- stream cannot be transformed. -- ------------------------------ overriding procedure Transform (E : in out Compress; Data : in Ada.Streams.Stream_Element_Array; Into : out Ada.Streams.Stream_Element_Array; Last : out Ada.Streams.Stream_Element_Offset; Encoded : out Ada.Streams.Stream_Element_Offset) is Result : Base.lzma_ret; begin E.Stream.next_out := Into (Into'First)'Unchecked_Access; E.Stream.avail_out := Into'Length; E.Stream.next_in := Data (Data'First)'Unrestricted_Access; E.Stream.avail_in := Interfaces.C.size_t (Data'Length); loop Result := Base.lzma_code (E.Stream'Unchecked_Access, Base.LZMA_RUN); -- Write the output data when the buffer is full or we reached the end of stream. if E.Stream.avail_out = 0 or E.Stream.avail_in = 0 or Result = Base.LZMA_STREAM_END then Last := Into'First + Into'Length - Offset (E.Stream.avail_out) - 1; Encoded := Data'First + Data'Length - Offset (E.Stream.avail_in); return; end if; exit when Result /= Base.LZMA_OK; end loop; Encoded := Into'First; end Transform; -- ------------------------------ -- Finish compression of the input array. -- ------------------------------ overriding procedure Finish (E : in out Compress; Into : in out Ada.Streams.Stream_Element_Array; Last : in out Ada.Streams.Stream_Element_Offset) is Result : Base.lzma_ret; pragma Unreferenced (Result); begin E.Stream.next_out := Into (Into'First)'Unchecked_Access; E.Stream.avail_out := Into'Length; E.Stream.next_in := null; E.Stream.avail_in := 0; Result := Base.lzma_code (E.Stream'Unchecked_Access, Base.LZMA_FINISH); Last := Into'First + Into'Length - Offset (E.Stream.avail_out) - 1; end Finish; overriding procedure Initialize (E : in out Compress) is Result : Base.lzma_ret; pragma Unreferenced (Result); begin Result := Container.lzma_easy_encoder (E.Stream'Unchecked_Access, 6, Check.LZMA_CHECK_CRC64); end Initialize; overriding procedure Finalize (E : in out Compress) is begin Base.lzma_end (E.Stream'Unchecked_Access); end Finalize; end Util.Encoders.Lzma;
Fix compilation warning in Transform
Fix compilation warning in Transform
Ada
apache-2.0
stcarrez/ada-util,stcarrez/ada-util
ca25d34844ed7a28938b68093af76ef6c5af0ef2
src/security-policies-urls.adb
src/security-policies-urls.adb
----------------------------------------------------------------------- -- security-policies-urls -- URL security policy -- Copyright (C) 2010, 2011, 2012 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Unchecked_Deallocation; with Ada.Strings.Unbounded; with Util.Refs; with Util.Beans.Objects; with Util.Beans.Objects.Vectors; with Util.Serialize.Mappers; with Util.Serialize.Mappers.Record_Mapper; with GNAT.Regexp; with Security.Controllers; package body Security.Policies.Urls is -- ------------------------------ -- URL policy -- ------------------------------ -- ------------------------------ -- Get the policy name. -- ------------------------------ overriding function Get_Name (From : in URL_Policy) return String is pragma Unreferenced (From); begin return NAME; end Get_Name; -- Returns True if the user has the permission to access the given URI permission. function Has_Permission (Manager : in URL_Policy; Context : in Security_Context_Access; Permission : in URI_Permission'Class) return Boolean is Name : constant String_Ref := To_String_Ref (Permission.URI); Ref : constant Rules_Ref.Ref := Manager.Cache.Get; Rules : constant Rules_Access := Ref.Value; Pos : constant Rules_Maps.Cursor := Rules.Map.Find (Name); Rule : Access_Rule_Ref; begin -- If the rule is not in the cache, search for the access rule that -- matches our URI. Update the cache. This cache update is thread-safe -- as the cache map is never modified: a new cache map is installed. if not Rules_Maps.Has_Element (Pos) then declare New_Ref : constant Rules_Ref.Ref := Rules_Ref.Create; begin Rule := Manager.Find_Access_Rule (Permission.URI); New_Ref.Value.all.Map := Rules.Map; New_Ref.Value.all.Map.Insert (Name, Rule); Manager.Cache.Set (New_Ref); end; else Rule := Rules_Maps.Element (Pos); end if; -- Check if the user has one of the required permission. declare P : constant Access_Rule_Access := Rule.Value; Granted : Boolean; begin if P /= null then for I in P.Permissions'Range loop -- Context.Has_Permission (P.Permissions (I), Granted); if Granted then return True; end if; end loop; end if; end; return False; end Has_Permission; -- Grant the permission to access to the given <b>URI</b> to users having the <b>To</b> -- permissions. procedure Grant_URI_Permission (Manager : in out URL_Policy; URI : in String; To : in String) is begin null; end Grant_URI_Permission; -- ------------------------------ -- Policy Configuration -- ------------------------------ type Policy_Config is record Id : Natural := 0; Permissions : Util.Beans.Objects.Vectors.Vector; Patterns : Util.Beans.Objects.Vectors.Vector; Manager : URL_Policy_Access; end record; type Policy_Config_Access is access all Policy_Config; -- Setup the XML parser to read the <b>policy</b> description. For example: -- Find the access rule of the policy that matches the given URI. -- Returns the No_Rule value (disable access) if no rule is found. function Find_Access_Rule (Manager : in URL_Policy; URI : in String) return Access_Rule_Ref is Matched : Boolean := False; Result : Access_Rule_Ref; procedure Match (P : in Policy); procedure Match (P : in Policy) is begin if GNAT.Regexp.Match (URI, P.Pattern) then Matched := True; Result := P.Rule; end if; end Match; Last : constant Natural := Manager.Policies.Last_Index; begin for I in 1 .. Last loop Manager.Policies.Query_Element (I, Match'Access); if Matched then return Result; end if; end loop; return Result; end Find_Access_Rule; -- ------------------------------ -- Initialize the permission manager. -- ------------------------------ overriding procedure Initialize (Manager : in out URL_Policy) is begin Manager.Cache := new Rules_Ref.Atomic_Ref; Manager.Cache.Set (Rules_Ref.Create); end Initialize; -- ------------------------------ -- Finalize the permission manager. -- ------------------------------ overriding procedure Finalize (Manager : in out URL_Policy) is use Ada.Strings.Unbounded; use Security.Controllers; procedure Free is new Ada.Unchecked_Deallocation (Rules_Ref.Atomic_Ref, Rules_Ref_Access); procedure Free is new Ada.Unchecked_Deallocation (Security.Controllers.Controller'Class, Security.Controllers.Controller_Access); procedure Free is new Ada.Unchecked_Deallocation (Controller_Access_Array, Controller_Access_Array_Access); begin Free (Manager.Cache); -- for I in Manager.Names'Range loop -- exit when Manager.Names (I) = null; -- Ada.Strings.Unbounded.Free (Manager.Names (I)); -- end loop; end Finalize; type Policy_Fields is (FIELD_ID, FIELD_PERMISSION, FIELD_URL_PATTERN, FIELD_POLICY); procedure Set_Member (P : in out Policy_Config; Field : in Policy_Fields; Value : in Util.Beans.Objects.Object); procedure Process (Policy : in Policy_Config); procedure Set_Member (P : in out Policy_Config; Field : in Policy_Fields; Value : in Util.Beans.Objects.Object) is begin case Field is when FIELD_ID => P.Id := Util.Beans.Objects.To_Integer (Value); when FIELD_PERMISSION => P.Permissions.Append (Value); when FIELD_URL_PATTERN => P.Patterns.Append (Value); when FIELD_POLICY => Process (P); P.Id := 0; P.Permissions.Clear; P.Patterns.Clear; end case; end Set_Member; procedure Process (Policy : in Policy_Config) is Pol : Security.Policies.URLs.Policy; Count : constant Natural := Natural (Policy.Permissions.Length); Rule : constant Access_Rule_Ref := Access_Rule_Refs.Create (new Access_Rule (Count)); Iter : Util.Beans.Objects.Vectors.Cursor := Policy.Permissions.First; Pos : Positive := 1; begin Pol.Rule := Rule; -- Step 1: Initialize the list of permission index in Access_Rule from the permission names. while Util.Beans.Objects.Vectors.Has_Element (Iter) loop declare Perm : constant Util.Beans.Objects.Object := Util.Beans.Objects.Vectors.Element (Iter); Name : constant String := Util.Beans.Objects.To_String (Perm); begin Rule.Value.all.Permissions (Pos) := Permissions.Get_Permission_Index (Name); Pos := Pos + 1; exception when Invalid_Name => raise Util.Serialize.Mappers.Field_Error with "Invalid permission: " & Name; end; Util.Beans.Objects.Vectors.Next (Iter); end loop; -- Step 2: Create one policy for each URL pattern Iter := Policy.Patterns.First; while Util.Beans.Objects.Vectors.Has_Element (Iter) loop declare Pattern : constant Util.Beans.Objects.Object := Util.Beans.Objects.Vectors.Element (Iter); begin Pol.Id := Policy.Id; Pol.Pattern := GNAT.Regexp.Compile (Util.Beans.Objects.To_String (Pattern)); Policy.Manager.Policies.Append (Pol); end; Util.Beans.Objects.Vectors.Next (Iter); end loop; end Process; package Policy_Mapper is new Util.Serialize.Mappers.Record_Mapper (Element_Type => Policy_Config, Element_Type_Access => Policy_Config_Access, Fields => Policy_Fields, Set_Member => Set_Member); Policy_Mapping : aliased Policy_Mapper.Mapper; -- ------------------------------ -- Setup the XML parser to read the <b>policy</b> description. -- ------------------------------ overriding procedure Prepare_Config (Policy : in out URL_Policy; Reader : in out Util.Serialize.IO.XML.Parser) is Config : Policy_Config_Access := new Policy_Config; begin Reader.Add_Mapping ("policy-rules", Policy_Mapping'Access); Reader.Add_Mapping ("module", Policy_Mapping'Access); Config.Manager := Policy'Unchecked_Access; Policy_Mapper.Set_Context (Reader, Config); end Prepare_Config; -- ------------------------------ -- Finish reading the XML policy configuration. The security policy implementation can use -- this procedure to perform any configuration setup after the configuration is parsed. -- ------------------------------ overriding procedure Finish_Config (Into : in out URL_Policy; Reader : in out Util.Serialize.IO.XML.Parser) is begin null; end Finish_Config; begin Policy_Mapping.Add_Mapping ("policy", FIELD_POLICY); Policy_Mapping.Add_Mapping ("policy/@id", FIELD_ID); Policy_Mapping.Add_Mapping ("policy/permission", FIELD_PERMISSION); Policy_Mapping.Add_Mapping ("policy/url-pattern", FIELD_URL_PATTERN); end Security.Policies.Urls;
----------------------------------------------------------------------- -- security-policies-urls -- URL security policy -- Copyright (C) 2010, 2011, 2012 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Unchecked_Deallocation; with Ada.Strings.Unbounded; with Util.Refs; with Util.Beans.Objects; with Util.Beans.Objects.Vectors; with Util.Serialize.Mappers; with Util.Serialize.Mappers.Record_Mapper; with GNAT.Regexp; with Security.Controllers; package body Security.Policies.Urls is -- ------------------------------ -- URL policy -- ------------------------------ -- ------------------------------ -- Get the policy name. -- ------------------------------ overriding function Get_Name (From : in URL_Policy) return String is pragma Unreferenced (From); begin return NAME; end Get_Name; -- Returns True if the user has the permission to access the given URI permission. function Has_Permission (Manager : in URL_Policy; Context : in Security_Context_Access; Permission : in URI_Permission'Class) return Boolean is Name : constant String_Ref := To_String_Ref (Permission.URI); Ref : constant Rules_Ref.Ref := Manager.Cache.Get; Rules : constant Rules_Access := Ref.Value; Pos : constant Rules_Maps.Cursor := Rules.Map.Find (Name); Rule : Access_Rule_Ref; begin -- If the rule is not in the cache, search for the access rule that -- matches our URI. Update the cache. This cache update is thread-safe -- as the cache map is never modified: a new cache map is installed. if not Rules_Maps.Has_Element (Pos) then declare New_Ref : constant Rules_Ref.Ref := Rules_Ref.Create; begin Rule := Manager.Find_Access_Rule (Permission.URI); New_Ref.Value.all.Map := Rules.Map; New_Ref.Value.all.Map.Insert (Name, Rule); Manager.Cache.Set (New_Ref); end; else Rule := Rules_Maps.Element (Pos); end if; -- Check if the user has one of the required permission. declare P : constant Access_Rule_Access := Rule.Value; Granted : Boolean; begin if P /= null then for I in P.Permissions'Range loop -- Context.Has_Permission (P.Permissions (I), Granted); if Granted then return True; end if; end loop; end if; end; return False; end Has_Permission; -- Grant the permission to access to the given <b>URI</b> to users having the <b>To</b> -- permissions. procedure Grant_URI_Permission (Manager : in out URL_Policy; URI : in String; To : in String) is begin null; end Grant_URI_Permission; -- ------------------------------ -- Policy Configuration -- ------------------------------ type Policy_Config is record Id : Natural := 0; Permissions : Util.Beans.Objects.Vectors.Vector; Patterns : Util.Beans.Objects.Vectors.Vector; Manager : URL_Policy_Access; end record; type Policy_Config_Access is access all Policy_Config; -- Setup the XML parser to read the <b>policy</b> description. For example: -- Find the access rule of the policy that matches the given URI. -- Returns the No_Rule value (disable access) if no rule is found. function Find_Access_Rule (Manager : in URL_Policy; URI : in String) return Access_Rule_Ref is Matched : Boolean := False; Result : Access_Rule_Ref; procedure Match (P : in Policy); procedure Match (P : in Policy) is begin if GNAT.Regexp.Match (URI, P.Pattern) then Matched := True; Result := P.Rule; end if; end Match; Last : constant Natural := Manager.Policies.Last_Index; begin for I in 1 .. Last loop Manager.Policies.Query_Element (I, Match'Access); if Matched then return Result; end if; end loop; return Result; end Find_Access_Rule; -- ------------------------------ -- Initialize the permission manager. -- ------------------------------ overriding procedure Initialize (Manager : in out URL_Policy) is begin Manager.Cache := new Rules_Ref.Atomic_Ref; Manager.Cache.Set (Rules_Ref.Create); end Initialize; -- ------------------------------ -- Finalize the permission manager. -- ------------------------------ overriding procedure Finalize (Manager : in out URL_Policy) is use Ada.Strings.Unbounded; use Security.Controllers; procedure Free is new Ada.Unchecked_Deallocation (Rules_Ref.Atomic_Ref, Rules_Ref_Access); begin Free (Manager.Cache); -- for I in Manager.Names'Range loop -- exit when Manager.Names (I) = null; -- Ada.Strings.Unbounded.Free (Manager.Names (I)); -- end loop; end Finalize; type Policy_Fields is (FIELD_ID, FIELD_PERMISSION, FIELD_URL_PATTERN, FIELD_POLICY); procedure Set_Member (P : in out Policy_Config; Field : in Policy_Fields; Value : in Util.Beans.Objects.Object); procedure Process (Policy : in Policy_Config); procedure Set_Member (P : in out Policy_Config; Field : in Policy_Fields; Value : in Util.Beans.Objects.Object) is begin case Field is when FIELD_ID => P.Id := Util.Beans.Objects.To_Integer (Value); when FIELD_PERMISSION => P.Permissions.Append (Value); when FIELD_URL_PATTERN => P.Patterns.Append (Value); when FIELD_POLICY => Process (P); P.Id := 0; P.Permissions.Clear; P.Patterns.Clear; end case; end Set_Member; procedure Process (Policy : in Policy_Config) is Pol : Security.Policies.URLs.Policy; Count : constant Natural := Natural (Policy.Permissions.Length); Rule : constant Access_Rule_Ref := Access_Rule_Refs.Create (new Access_Rule (Count)); Iter : Util.Beans.Objects.Vectors.Cursor := Policy.Permissions.First; Pos : Positive := 1; begin Pol.Rule := Rule; -- Step 1: Initialize the list of permission index in Access_Rule from the permission names. while Util.Beans.Objects.Vectors.Has_Element (Iter) loop declare Perm : constant Util.Beans.Objects.Object := Util.Beans.Objects.Vectors.Element (Iter); Name : constant String := Util.Beans.Objects.To_String (Perm); begin Rule.Value.all.Permissions (Pos) := Permissions.Get_Permission_Index (Name); Pos := Pos + 1; exception when Invalid_Name => raise Util.Serialize.Mappers.Field_Error with "Invalid permission: " & Name; end; Util.Beans.Objects.Vectors.Next (Iter); end loop; -- Step 2: Create one policy for each URL pattern Iter := Policy.Patterns.First; while Util.Beans.Objects.Vectors.Has_Element (Iter) loop declare Pattern : constant Util.Beans.Objects.Object := Util.Beans.Objects.Vectors.Element (Iter); begin Pol.Id := Policy.Id; Pol.Pattern := GNAT.Regexp.Compile (Util.Beans.Objects.To_String (Pattern)); Policy.Manager.Policies.Append (Pol); end; Util.Beans.Objects.Vectors.Next (Iter); end loop; end Process; package Policy_Mapper is new Util.Serialize.Mappers.Record_Mapper (Element_Type => Policy_Config, Element_Type_Access => Policy_Config_Access, Fields => Policy_Fields, Set_Member => Set_Member); Policy_Mapping : aliased Policy_Mapper.Mapper; -- ------------------------------ -- Setup the XML parser to read the <b>policy</b> description. -- ------------------------------ overriding procedure Prepare_Config (Policy : in out URL_Policy; Reader : in out Util.Serialize.IO.XML.Parser) is Config : Policy_Config_Access := new Policy_Config; begin Reader.Add_Mapping ("policy-rules", Policy_Mapping'Access); Reader.Add_Mapping ("module", Policy_Mapping'Access); Config.Manager := Policy'Unchecked_Access; Policy_Mapper.Set_Context (Reader, Config); end Prepare_Config; -- ------------------------------ -- Finish reading the XML policy configuration. The security policy implementation can use -- this procedure to perform any configuration setup after the configuration is parsed. -- ------------------------------ overriding procedure Finish_Config (Into : in out URL_Policy; Reader : in out Util.Serialize.IO.XML.Parser) is begin null; end Finish_Config; begin Policy_Mapping.Add_Mapping ("policy", FIELD_POLICY); Policy_Mapping.Add_Mapping ("policy/@id", FIELD_ID); Policy_Mapping.Add_Mapping ("policy/permission", FIELD_PERMISSION); Policy_Mapping.Add_Mapping ("policy/url-pattern", FIELD_URL_PATTERN); end Security.Policies.Urls;
Remove unused Free instantiations
Remove unused Free instantiations
Ada
apache-2.0
Letractively/ada-security
b1b4435e8034904e73f9d640825e20dd50e35827
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, 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.Streams; with Util.Streams.Texts; with Util.Stacks; with Util.Beans.Objects; 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; Sink : in out Reader'Class); -- Get the current location (file and line) to report an error message. function Get_Location (Handler : in Parser) return String; -- Read a JSON file and return an object. function Read (Path : in String) return Util.Beans.Objects.Object; 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; procedure Write_Field_Name (Stream : in out Output_Stream; Name : in String); 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, 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.Streams; with Util.Streams.Texts; with Util.Stacks; with Util.Beans.Objects; 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; Sink : in out Reader'Class); -- Get the current location (file and line) to report an error message. function Get_Location (Handler : in Parser) return String; -- Read a JSON file and return an object. function Read (Path : in String) return Util.Beans.Objects.Object; private type Node_Info is record Is_Array : Boolean := False; Is_Root : 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; procedure Write_Field_Name (Stream : in out Output_Stream; Name : in String); 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;
Add a Is_Root field to the Node_Info record
Add a Is_Root field to the Node_Info record
Ada
apache-2.0
stcarrez/ada-util,stcarrez/ada-util
ad4597226dfe36120180ac9bdbfe16ede9617b53
awa/src/awa-oauth-filters.ads
awa/src/awa-oauth-filters.ads
----------------------------------------------------------------------- -- awa-oauth-filters -- OAuth filter -- Copyright (C) 2017 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Strings.Unbounded; with ASF.Requests; with ASF.Responses; with ASF.Sessions; with ASF.Principals; with ASF.Filters; with ASF.Servlets; with ASF.Security.Filters; with AWA.Users.Principals; with AWA.OAuth.Services; package AWA.OAuth.Filters is -- ------------------------------ -- OAuth Authentication filter -- ------------------------------ -- The <b>Auth_Filter</b> verifies that the access token passed for the OAuth -- operation is valid and it extracts the user to configure the request principal. type Auth_Filter is new ASF.Filters.Filter with private; -- Initialize the filter. overriding procedure Initialize (Filter : in out Auth_Filter; Config : in ASF.Servlets.Filter_Config); -- The Do_Filter method of the Filter is called by the container each time -- a request/response pair is passed through the chain due to a client request -- for a resource at the end of the chain. The Filter_Chain passed in to this -- method allows the Filter to pass on the request and response to the next -- entity in the chain. -- -- Before passing the control to the next filter, initialize the service -- context to give access to the current application, current user and -- manage possible transaction rollbacks. overriding procedure Do_Filter (F : in Auth_Filter; Request : in out ASF.Requests.Request'Class; Response : in out ASF.Responses.Response'Class; Chain : in out ASF.Servlets.Filter_Chain); private use Ada.Strings.Unbounded; type Auth_Filter is new ASF.Filters.Filter with record Realm : AWA.OAuth.Services.Auth_Manager_Access; end record; end AWA.OAuth.Filters;
----------------------------------------------------------------------- -- awa-oauth-filters -- OAuth filter -- Copyright (C) 2017, 2018 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with ASF.Requests; with ASF.Responses; with ASF.Sessions; with ASF.Filters; with ASF.Servlets; with AWA.OAuth.Services; package AWA.OAuth.Filters is -- ------------------------------ -- OAuth Authentication filter -- ------------------------------ -- The <b>Auth_Filter</b> verifies that the access token passed for the OAuth -- operation is valid and it extracts the user to configure the request principal. type Auth_Filter is new ASF.Filters.Filter with private; -- Initialize the filter. overriding procedure Initialize (Filter : in out Auth_Filter; Config : in ASF.Servlets.Filter_Config); -- The Do_Filter method of the Filter is called by the container each time -- a request/response pair is passed through the chain due to a client request -- for a resource at the end of the chain. The Filter_Chain passed in to this -- method allows the Filter to pass on the request and response to the next -- entity in the chain. -- -- Before passing the control to the next filter, initialize the service -- context to give access to the current application, current user and -- manage possible transaction rollbacks. overriding procedure Do_Filter (F : in Auth_Filter; Request : in out ASF.Requests.Request'Class; Response : in out ASF.Responses.Response'Class; Chain : in out ASF.Servlets.Filter_Chain); private type Auth_Filter is new ASF.Filters.Filter with record Realm : AWA.OAuth.Services.Auth_Manager_Access; end record; end AWA.OAuth.Filters;
Remove unused with clauses
Remove unused with clauses
Ada
apache-2.0
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
f899fe6c7acfd24e794f2ad4588ce82ce86813fb
samples/cut.adb
samples/cut.adb
----------------------------------------------------------------------- -- cut -- Text Transformations -- Copyright (C) 2012 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Text_IO; with Ada.Command_Line; with Util.Strings; with Util.Strings.Tokenizers; procedure Cut is procedure Print_Token (Token : in String; Done : out Boolean) is begin Ada.Text_IO.Put_Line (Token); Done := False; end Print_Token; Count : constant Natural := Ada.Command_Line.Argument_Count; begin if Count <= 1 then Ada.Text_IO.Put_Line ("Usage: cut pattern ..."); Ada.Text_IO.Put_Line ("Example: cut : $PATH"); return; end if; declare Pattern : constant String := Ada.Command_Line.Argument (1); begin for I in 2 .. Count loop Util.Strings.Tokenizers.Iterate_Tokens (Content => Ada.Command_Line.Argument (I), Pattern => Pattern, Process => Print_Token'Access); end loop; end; end Cut;
----------------------------------------------------------------------- -- cut -- Text Transformations -- Copyright (C) 2012, 2022 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Text_IO; with Ada.Command_Line; with Util.Strings; with Util.Strings.Tokenizers; procedure Cut is procedure Print_Token (Token : in String; Done : out Boolean); procedure Print_Token (Token : in String; Done : out Boolean) is begin Ada.Text_IO.Put_Line (Token); Done := False; end Print_Token; Count : constant Natural := Ada.Command_Line.Argument_Count; begin if Count <= 1 then Ada.Text_IO.Put_Line ("Usage: cut pattern ..."); Ada.Text_IO.Put_Line ("Example: cut : $PATH"); return; end if; declare Pattern : constant String := Ada.Command_Line.Argument (1); begin for I in 2 .. Count loop Util.Strings.Tokenizers.Iterate_Tokens (Content => Ada.Command_Line.Argument (I), Pattern => Pattern, Process => Print_Token'Access); end loop; end; end Cut;
Fix compilation warning
Fix compilation warning
Ada
apache-2.0
stcarrez/ada-util,stcarrez/ada-util
1bff297698ea1b5027e1cadddb90998aa6a785ab
awa/plugins/awa-images/src/awa-images-services.ads
awa/plugins/awa-images/src/awa-images-services.ads
----------------------------------------------------------------------- -- awa-images-services -- Image service -- Copyright (C) 2012 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Security.Permissions; with ADO; with AWA.Modules; with EL.Expressions; with AWA.Storages.Models; -- == Storage Service == -- The <tt>Storage_Service</tt> provides the operations to access and use the persisent storage. -- It controls the permissions that grant access to the service for users. -- -- Other modules can be notified of storage changes by registering a listener -- on the storage module. package AWA.Images.Services is package ACL_Create_Storage is new Security.Permissions.Permission_ACL ("storage-create"); package ACL_Delete_Storage is new Security.Permissions.Permission_ACL ("storage-delete"); package ACL_Create_Folder is new Security.Permissions.Permission_ACL ("folder-create"); PARAM_THUMBNAIL_COMMAND : constant String := "thumbnail_command"; -- ------------------------------ -- Image Service -- ------------------------------ -- The <b>Image_Service</b> works closely with the storage service. It extracts the -- information of an image, creates the image thumbnail. type Image_Service is new AWA.Modules.Module_Manager with private; type Image_Service_Access is access all Image_Service'Class; -- Initializes the image service. overriding procedure Initialize (Service : in out Image_Service; Module : in AWA.Modules.Module'Class); procedure Create_Thumbnail (Service : in Image_Service; Source : in String; Into : in String; Width : out Natural; Height : out Natural); -- Save the data object contained in the <b>Data</b> part element into the -- target storage represented by <b>Into</b>. procedure Create_Image (Service : in Image_Service; File : in AWA.Storages.Models.Storage_Ref'Class); -- Deletes the storage instance. procedure Delete_Image (Service : in Image_Service; File : in AWA.Storages.Models.Storage_Ref'Class); private type Image_Service is new AWA.Modules.Module_Manager with record Thumbnail_Command : EL.Expressions.Expression; end record; end AWA.Images.Services;
----------------------------------------------------------------------- -- awa-images-services -- Image service -- Copyright (C) 2012 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Security.Permissions; with ADO; with AWA.Modules; with EL.Expressions; with AWA.Storages.Models; -- == Storage Service == -- The <tt>Storage_Service</tt> provides the operations to access and use the persisent storage. -- It controls the permissions that grant access to the service for users. -- -- Other modules can be notified of storage changes by registering a listener -- on the storage module. package AWA.Images.Services is package ACL_Create_Storage is new Security.Permissions.Definition ("storage-create"); package ACL_Delete_Storage is new Security.Permissions.Definition ("storage-delete"); package ACL_Create_Folder is new Security.Permissions.Definition ("folder-create"); PARAM_THUMBNAIL_COMMAND : constant String := "thumbnail_command"; -- ------------------------------ -- Image Service -- ------------------------------ -- The <b>Image_Service</b> works closely with the storage service. It extracts the -- information of an image, creates the image thumbnail. type Image_Service is new AWA.Modules.Module_Manager with private; type Image_Service_Access is access all Image_Service'Class; -- Initializes the image service. overriding procedure Initialize (Service : in out Image_Service; Module : in AWA.Modules.Module'Class); procedure Create_Thumbnail (Service : in Image_Service; Source : in String; Into : in String; Width : out Natural; Height : out Natural); -- Save the data object contained in the <b>Data</b> part element into the -- target storage represented by <b>Into</b>. procedure Create_Image (Service : in Image_Service; File : in AWA.Storages.Models.Storage_Ref'Class); -- Deletes the storage instance. procedure Delete_Image (Service : in Image_Service; File : in AWA.Storages.Models.Storage_Ref'Class); private type Image_Service is new AWA.Modules.Module_Manager with record Thumbnail_Command : EL.Expressions.Expression; end record; end AWA.Images.Services;
Use the Permissions.Definition generic package
Use the Permissions.Definition generic package
Ada
apache-2.0
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
138cd9c892475903e25fabff0800481f519716aa
src/babel-strategies.ads
src/babel-strategies.ads
----------------------------------------------------------------------- -- 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.Listeners; with Babel.Files; with Babel.Files.Queues; with Babel.Files.Buffers; with Babel.Stores; with Babel.Filters; package Babel.Strategies is type Strategy_Type is abstract tagged limited private; type Strategy_Type_Access is access all Strategy_Type'Class; -- Allocate a buffer to read the file content. function Allocate_Buffer (Strategy : in Strategy_Type) return Babel.Files.Buffers.Buffer_Access; -- Release the buffer that was allocated by Allocate_Buffer. procedure Release_Buffer (Strategy : in Strategy_Type; Buffer : in out Babel.Files.Buffers.Buffer_Access); -- Returns true if there is a directory that must be processed by the current strategy. function Has_Directory (Strategy : in Strategy_Type) return Boolean is abstract; -- Get the next directory that must be processed by the strategy. procedure Peek_Directory (Strategy : in out Strategy_Type; Directory : out Babel.Files.Directory_Type) is abstract; -- Scan the directory procedure Scan (Strategy : in out Strategy_Type; Directory : in Babel.Files.Directory_Type; Container : in out Babel.Files.File_Container'Class); -- 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); -- 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); -- 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); -- 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); procedure Execute (Strategy : in out Strategy_Type) is abstract; -- 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); -- 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); -- 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); -- Set the listeners to inform about changes. procedure Set_Listeners (Strategy : in out Strategy_Type; Listeners : access Util.Listeners.List); private type Strategy_Type is abstract tagged limited record Read_Store : Babel.Stores.Store_Type_Access; Write_Store : Babel.Stores.Store_Type_Access; Filters : Babel.Filters.Filter_Type_Access; Buffers : Babel.Files.Buffers.Buffer_Pool_Access; Listeners : access Util.Listeners.List; end record; 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.Listeners; with Babel.Files; with Babel.Files.Queues; with Babel.Files.Buffers; with Babel.Stores; with Babel.Filters; with Babel.Base; package Babel.Strategies is type Strategy_Type is abstract tagged limited private; type Strategy_Type_Access is access all Strategy_Type'Class; -- Allocate a buffer to read the file content. function Allocate_Buffer (Strategy : in Strategy_Type) return Babel.Files.Buffers.Buffer_Access; -- Release the buffer that was allocated by Allocate_Buffer. procedure Release_Buffer (Strategy : in Strategy_Type; Buffer : in out Babel.Files.Buffers.Buffer_Access); -- Returns true if there is a directory that must be processed by the current strategy. function Has_Directory (Strategy : in Strategy_Type) return Boolean is abstract; -- Get the next directory that must be processed by the strategy. procedure Peek_Directory (Strategy : in out Strategy_Type; Directory : out Babel.Files.Directory_Type) is abstract; -- Scan the directory procedure Scan (Strategy : in out Strategy_Type; Directory : in Babel.Files.Directory_Type; Container : in out Babel.Files.File_Container'Class); -- 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); -- 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); -- 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); -- 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); procedure Execute (Strategy : in out Strategy_Type) is abstract; -- 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); -- 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); -- 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); -- Set the listeners to inform about changes. procedure Set_Listeners (Strategy : in out Strategy_Type; Listeners : access Util.Listeners.List); -- Set the database for use by the strategy. procedure Set_Database (Strategy : in out Strategy_Type; Database : in Babel.Base.Database_Access); private type Strategy_Type is abstract tagged limited record Read_Store : Babel.Stores.Store_Type_Access; Write_Store : Babel.Stores.Store_Type_Access; Filters : Babel.Filters.Filter_Type_Access; Buffers : Babel.Files.Buffers.Buffer_Pool_Access; Listeners : access Util.Listeners.List; Database : Babel.Base.Database_Access; end record; end Babel.Strategies;
Define the Set_Database operation
Define the Set_Database operation
Ada
apache-2.0
stcarrez/babel
ccce1e48612c41ac5f1cf927a9117c0f5b3e24a8
samples/import.adb
samples/import.adb
----------------------------------------------------------------------- -- import -- Import some HTML content and generate Wiki text -- Copyright (C) 2015, 2016 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Text_IO; with Ada.IO_Exceptions; with Ada.Strings.Unbounded; with Ada.Characters.Conversions; with GNAT.Command_Line; with Util.Files; with Util.Streams.Pipes; with Util.Streams.Buffered; with Util.Strings.Transforms; with Wiki.Filters.Html; with Wiki.Filters.TOC; with Wiki.Streams.Builders; with Wiki.Streams.Html.Builders; with Wiki.Render.Html; with Wiki.Render.Text; with Wiki.Render.Wiki; with Wiki.Documents; with Wiki.Parsers; procedure Import is use GNAT.Command_Line; use Ada.Strings.Unbounded; use Ada.Characters.Conversions; procedure Usage; function Is_Url (Name : in String) return Boolean; procedure Parse_Url (Url : in String); procedure Parse (Content : in String); Html_Filter : aliased Wiki.Filters.Html.Html_Filter_Type; TOC : aliased Wiki.Filters.TOC.TOC_Filter; Count : Natural := 0; Html_Mode : Boolean := True; Wiki_Mode : Boolean := False; Syntax : Wiki.Wiki_Syntax := Wiki.SYNTAX_MARKDOWN; procedure Usage is begin Ada.Text_IO.Put_Line ("Import HTML into a target Wiki format"); Ada.Text_IO.Put_Line ("Usage: import [-t] [-m] [-M] [-d] [-c] {URL | file}"); Ada.Text_IO.Put_Line (" -t Convert to text only"); Ada.Text_IO.Put_Line (" -m Convert to Markdown"); Ada.Text_IO.Put_Line (" -M Convert to Mediawiki"); Ada.Text_IO.Put_Line (" -d Convert to Dotclear"); Ada.Text_IO.Put_Line (" -c Convert to Creole"); end Usage; procedure Parse (Content : in String) is Doc : Wiki.Documents.Document; Engine : Wiki.Parsers.Parser; begin Engine.Add_Filter (TOC'Unchecked_Access); Engine.Add_Filter (Html_Filter'Unchecked_Access); if Wiki_Mode then declare Stream : aliased Wiki.Streams.Builders.Output_Builder_Stream; Renderer : aliased Wiki.Render.Wiki.Wiki_Renderer; begin Engine.Set_Syntax (Wiki.SYNTAX_HTML); Engine.Parse (To_Wide_Wide_String (Content), Doc); Renderer.Set_Output_Stream (Stream'Unchecked_Access, Syntax); Renderer.Render (Doc); Ada.Text_IO.Put_Line (Stream.To_String); end; elsif Html_Mode then declare Stream : aliased Wiki.Streams.Html.Builders.Html_Output_Builder_Stream; Renderer : aliased Wiki.Render.Html.Html_Renderer; begin Engine.Set_Syntax (Syntax); Engine.Parse (To_Wide_Wide_String (Content), Doc); Renderer.Set_Output_Stream (Stream'Unchecked_Access); Renderer.Render (Doc); Ada.Text_IO.Put_Line (Stream.To_String); end; else declare Stream : aliased Wiki.Streams.Builders.Output_Builder_Stream; Renderer : aliased Wiki.Render.Text.Text_Renderer; begin Engine.Set_Syntax (Syntax); Engine.Parse (To_Wide_Wide_String (Content), Doc); Renderer.Set_Output_Stream (Stream'Unchecked_Access); Renderer.Render (Doc); Ada.Text_IO.Put_Line (Stream.To_String); end; end if; end Parse; procedure Parse_Url (Url : in String) is Command : constant String := "wget -q -O - " & Url; Pipe : aliased Util.Streams.Pipes.Pipe_Stream; Buffer : Util.Streams.Buffered.Buffered_Stream; Content : Ada.Strings.Unbounded.Unbounded_String; begin Pipe.Open (Command); Buffer.Initialize (null, Pipe'Unchecked_Access, 1024 * 1024); Buffer.Read (Content); Pipe.Close; if Pipe.Get_Exit_Status /= 0 then Ada.Text_IO.Put_Line (Command & " exited with status " & Integer'Image (Pipe.Get_Exit_Status)); else Parse (To_String (Content)); end if; end Parse_Url; function Is_Url (Name : in String) return Boolean is begin if Name'Length <= 9 then return False; else return Name (Name'First .. Name'First + 6) = "http://" or Name (Name'First .. Name'First + 7) = "https://"; end if; end Is_Url; begin loop case Getopt ("m M d c t f:") is when 'm' => Syntax := Wiki.SYNTAX_MARKDOWN; Wiki_Mode := True; when 'M' => Syntax := Wiki.SYNTAX_MEDIA_WIKI; Wiki_Mode := True; when 'c' => Syntax := Wiki.SYNTAX_CREOLE; Wiki_Mode := True; when 'd' => Syntax := Wiki.SYNTAX_DOTCLEAR; Wiki_Mode := True; when 't' => Html_Mode := False; when 'f' => declare Value : constant String := Util.Strings.Transforms.To_Upper_Case (Parameter); begin Html_Filter.Hide (Wiki.Html_Tag'Value (Value & "_TAG")); exception when Constraint_Error => Ada.Text_IO.Put_Line ("Invalid tag " & Value); end; when others => exit; end case; end loop; loop declare Name : constant String := GNAT.Command_Line.Get_Argument; Data : Unbounded_String; begin if Name = "" then if Count = 0 then Usage; end if; return; end if; Count := Count + 1; if Is_Url (Name) then Parse_Url (Name); else Util.Files.Read_File (Name, Data); Parse (To_String (Data)); end if; exception when Ada.IO_Exceptions.Name_Error => Ada.Text_IO.Put_Line ("Cannot read file '" & Name & "'"); end; end loop; exception when Invalid_Switch => Ada.Text_IO.Put_Line ("Invalid option."); Usage; end Import;
----------------------------------------------------------------------- -- import -- Import some HTML content and generate Wiki text -- Copyright (C) 2015, 2016 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Text_IO; with Ada.IO_Exceptions; with Ada.Strings.Unbounded; with Ada.Characters.Conversions; with GNAT.Command_Line; with Util.Files; with Util.Streams.Pipes; with Util.Streams.Buffered; with Util.Strings.Transforms; with Wiki.Filters.Html; with Wiki.Filters.TOC; with Wiki.Streams.Builders; with Wiki.Streams.Html.Builders; with Wiki.Render.Html; with Wiki.Render.Text; with Wiki.Render.Wiki; with Wiki.Documents; with Wiki.Parsers; procedure Import is use GNAT.Command_Line; use Ada.Strings.Unbounded; use Ada.Characters.Conversions; procedure Usage; function Is_Url (Name : in String) return Boolean; procedure Parse_Url (Url : in String); procedure Parse (Content : in String); Html_Filter : aliased Wiki.Filters.Html.Html_Filter_Type; TOC : aliased Wiki.Filters.TOC.TOC_Filter; Count : Natural := 0; Html_Mode : Boolean := True; Wiki_Mode : Boolean := False; Syntax : Wiki.Wiki_Syntax := Wiki.SYNTAX_MARKDOWN; procedure Usage is begin Ada.Text_IO.Put_Line ("Import HTML into a target Wiki format"); Ada.Text_IO.Put_Line ("Usage: import [-t] [-m] [-M] [-d] [-c] {URL | file}"); Ada.Text_IO.Put_Line (" -t Convert to text only"); Ada.Text_IO.Put_Line (" -m Convert to Markdown"); Ada.Text_IO.Put_Line (" -M Convert to Mediawiki"); Ada.Text_IO.Put_Line (" -d Convert to Dotclear"); Ada.Text_IO.Put_Line (" -c Convert to Creole"); end Usage; procedure Parse (Content : in String) is Doc : Wiki.Documents.Document; Engine : Wiki.Parsers.Parser; begin Engine.Add_Filter (TOC'Unchecked_Access); Engine.Add_Filter (Html_Filter'Unchecked_Access); if Wiki_Mode then declare Stream : aliased Wiki.Streams.Builders.Output_Builder_Stream; Renderer : aliased Wiki.Render.Wiki.Wiki_Renderer; begin Engine.Set_Syntax (Wiki.SYNTAX_HTML); Engine.Parse (To_Wide_Wide_String (Content), Doc); Renderer.Set_Output_Stream (Stream'Unchecked_Access, Syntax); Renderer.Render (Doc); Ada.Text_IO.Put_Line (Stream.To_String); end; elsif Html_Mode then declare Stream : aliased Wiki.Streams.Html.Builders.Html_Output_Builder_Stream; Renderer : aliased Wiki.Render.Html.Html_Renderer; begin Engine.Set_Syntax (Syntax); Engine.Parse (To_Wide_Wide_String (Content), Doc); Renderer.Set_Output_Stream (Stream'Unchecked_Access); Renderer.Render (Doc); Ada.Text_IO.Put_Line (Stream.To_String); end; else declare Stream : aliased Wiki.Streams.Builders.Output_Builder_Stream; Renderer : aliased Wiki.Render.Text.Text_Renderer; begin Engine.Set_Syntax (Syntax); Engine.Parse (To_Wide_Wide_String (Content), Doc); Renderer.Set_Output_Stream (Stream'Unchecked_Access); Renderer.Render (Doc); Ada.Text_IO.Put_Line (Stream.To_String); end; end if; end Parse; procedure Parse_Url (Url : in String) is Command : constant String := "wget -q -O - " & Url; Pipe : aliased Util.Streams.Pipes.Pipe_Stream; Buffer : Util.Streams.Buffered.Input_Buffer_Stream; Content : Ada.Strings.Unbounded.Unbounded_String; begin Pipe.Open (Command); Buffer.Initialize (Pipe'Unchecked_Access, 1024 * 1024); Buffer.Read (Content); Pipe.Close; if Pipe.Get_Exit_Status /= 0 then Ada.Text_IO.Put_Line (Command & " exited with status " & Integer'Image (Pipe.Get_Exit_Status)); else Parse (To_String (Content)); end if; end Parse_Url; function Is_Url (Name : in String) return Boolean is begin if Name'Length <= 9 then return False; else return Name (Name'First .. Name'First + 6) = "http://" or Name (Name'First .. Name'First + 7) = "https://"; end if; end Is_Url; begin loop case Getopt ("m M d c t f:") is when 'm' => Syntax := Wiki.SYNTAX_MARKDOWN; Wiki_Mode := True; when 'M' => Syntax := Wiki.SYNTAX_MEDIA_WIKI; Wiki_Mode := True; when 'c' => Syntax := Wiki.SYNTAX_CREOLE; Wiki_Mode := True; when 'd' => Syntax := Wiki.SYNTAX_DOTCLEAR; Wiki_Mode := True; when 't' => Html_Mode := False; when 'f' => declare Value : constant String := Util.Strings.Transforms.To_Upper_Case (Parameter); begin Html_Filter.Hide (Wiki.Html_Tag'Value (Value & "_TAG")); exception when Constraint_Error => Ada.Text_IO.Put_Line ("Invalid tag " & Value); end; when others => exit; end case; end loop; loop declare Name : constant String := GNAT.Command_Line.Get_Argument; Data : Unbounded_String; begin if Name = "" then if Count = 0 then Usage; end if; return; end if; Count := Count + 1; if Is_Url (Name) then Parse_Url (Name); else Util.Files.Read_File (Name, Data); Parse (To_String (Data)); end if; exception when Ada.IO_Exceptions.Name_Error => Ada.Text_IO.Put_Line ("Cannot read file '" & Name & "'"); end; end loop; exception when Invalid_Switch => Ada.Text_IO.Put_Line ("Invalid option."); Usage; end Import;
Update to use latest Ada Util library
Update to use latest Ada Util library
Ada
apache-2.0
stcarrez/ada-wiki,stcarrez/ada-wiki
0047f755fa8317e93ac6217faaebe176d13c4372
matp/src/events/mat-events-timelines.adb
matp/src/events/mat-events-timelines.adb
----------------------------------------------------------------------- -- mat-events-timelines - Timelines -- 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 MAT.Frames; package body MAT.Events.Timelines is use MAT.Events.Targets; ITERATE_COUNT : constant MAT.Events.Event_Id_Type := 10_000; procedure Extract (Target : in out MAT.Events.Targets.Target_Events'Class; Level : in Positive; Into : in out Timeline_Info_Vector) is use type MAT.Types.Target_Time; use type MAT.Types.Target_Size; procedure Collect (Event : in MAT.Events.Target_Event_Type); First_Event : MAT.Events.Target_Event_Type; Last_Event : MAT.Events.Target_Event_Type; Prev_Event : MAT.Events.Target_Event_Type; Info : Timeline_Info; First_Id : MAT.Events.Event_Id_Type; Limit : MAT.Types.Target_Time := MAT.Types.Target_Time (Level * 1_000_000); procedure Collect (Event : in MAT.Events.Target_Event_Type) is Dt : constant MAT.Types.Target_Time := Event.Time - Prev_Event.Time; begin if Dt > Limit then Into.Append (Info); Info.Malloc_Count := 0; Info.Realloc_Count := 0; Info.Free_Count := 0; Info.First_Event := Event; Info.Free_Size := 0; Info.Alloc_Size := 0; Prev_Event := Event; end if; Info.Last_Event := Event; if Event.Event = 2 then Info.Malloc_Count := Info.Malloc_Count + 1; Info.Alloc_Size := Info.Alloc_Size + Event.Size; elsif Event.Event = 3 then Info.Realloc_Count := Info.Realloc_Count + 1; Info.Alloc_Size := Info.Alloc_Size + Event.Size; Info.Free_Size := Info.Free_Size + Event.Old_Size; elsif Event.Event = 4 then Info.Free_Count := Info.Free_Count + 1; Info.Free_Size := Info.Free_Size + Event.Size; end if; end Collect; begin Target.Get_Limits (First_Event, Last_Event); Prev_Event := First_Event; Info.First_Event := First_Event; First_Id := First_Event.Id; while First_Id < Last_Event.Id loop Target.Iterate (Start => First_Id, Finish => First_Id + ITERATE_COUNT, Process => Collect'Access); First_Id := First_Id + ITERATE_COUNT; end loop; end Extract; -- ------------------------------ -- Find in the events stream the events which are associated with a given event. -- When the <tt>Event</tt> is a memory allocation, find the associated reallocation -- and free events. When the event is a free, find the associated allocations. -- Collect at most <tt>Max</tt> events. -- ------------------------------ procedure Find_Related (Target : in out MAT.Events.Targets.Target_Events'Class; Event : in MAT.Events.Target_Event_Type; Max : in Positive; List : in out MAT.Events.Tools.Target_Event_Vector) is procedure Collect_Free (Event : in MAT.Events.Target_Event_Type); procedure Collect_Alloc (Event : in MAT.Events.Target_Event_Type); First_Id : MAT.Events.Event_Id_Type; Last_Id : MAT.Events.Event_Id_Type; First_Event : MAT.Events.Target_Event_Type; Last_Event : MAT.Events.Target_Event_Type; Addr : MAT.Types.Target_Addr := Event.Addr; Done : exception; procedure Collect_Free (Event : in MAT.Events.Target_Event_Type) is begin if Event.Index = MAT.Events.MSG_FREE and then Event.Addr = Addr then List.Append (Event); raise Done; end if; if Event.Index = MAT.Events.MSG_REALLOC and then Event.Old_Addr = Addr then List.Append (Event); if Positive (List.Length) >= Max then raise Done; end if; Addr := Event.Addr; end if; end Collect_Free; procedure Collect_Alloc (Event : in MAT.Events.Target_Event_Type) is begin if Event.Index = MAT.Events.MSG_MALLOC and then Event.Addr = Addr then List.Append (Event); raise Done; end if; if Event.Index = MAT.Events.MSG_REALLOC and then Event.Addr = Addr then List.Append (Event); if Positive (List.Length) >= Max then raise Done; end if; Addr := Event.Old_Addr; end if; end Collect_Alloc; begin Target.Get_Limits (First_Event, Last_Event); First_Id := Event.Id; if Event.Index = MAT.Events.MSG_FREE then -- Search backward for MSG_MALLOC and MSG_REALLOC. First_Id := First_Id - 1; while First_Id > First_Event.Id loop if First_Id > ITERATE_COUNT then Last_Id := First_Id - ITERATE_COUNT; else Last_Id := First_Event.Id; end if; Target.Iterate (Start => First_Id, Finish => Last_Id, Process => Collect_Alloc'Access); First_Id := Last_Id; end loop; else -- Search forward for MSG_REALLOC and MSG_FREE First_Id := First_Id + 1; while First_Id < Last_Event.Id loop Target.Iterate (Start => First_Id, Finish => First_Id + ITERATE_COUNT, Process => Collect_Free'Access); First_Id := First_Id + ITERATE_COUNT; end loop; end if; exception when Done => null; end Find_Related; -- ------------------------------ -- Find the sizes of malloc and realloc events which is selected by the given filter. -- Update the <tt>Sizes</tt> map to keep track of the first event and last event and -- the number of events found for the corresponding size. -- ------------------------------ procedure Find_Sizes (Target : in out MAT.Events.Targets.Target_Events'Class; Filter : in MAT.Expressions.Expression_Type; Sizes : in out MAT.Events.Tools.Size_Event_Info_Map) is procedure Collect_Event (Event : in MAT.Events.Target_Event_Type); procedure Collect_Event (Event : in MAT.Events.Target_Event_Type) is procedure Update_Size (Size : in MAT.Types.Target_Size; Info : in out MAT.Events.Tools.Event_Info_Type); procedure Update_Size (Size : in MAT.Types.Target_Size; Info : in out MAT.Events.Tools.Event_Info_Type) is pragma Unreferenced (Size); begin MAT.Events.Tools.Collect_Info (Info, Event); end Update_Size; begin -- Look for malloc or realloc events which are selected by the filter. if (Event.Index /= MAT.Events.MSG_MALLOC and Event.Index /= MAT.Events.MSG_FREE and Event.Index /= MAT.Events.MSG_REALLOC) or else not Filter.Is_Selected (Event) then return; end if; declare Pos : constant MAT.Events.Tools.Size_Event_Info_Cursor := Sizes.Find (Event.Size); begin if MAT.Events.Tools.Size_Event_Info_Maps.Has_Element (Pos) then -- Increment the count and update the last event. Sizes.Update_Element (Pos, Update_Size'Access); else declare Info : MAT.Events.Tools.Event_Info_Type; begin -- Insert a new size with the event. Info.First_Event := Event; MAT.Events.Tools.Collect_Info (Info, Event); Sizes.Insert (Event.Size, Info); end; end if; end; end Collect_Event; begin Target.Iterate (Process => Collect_Event'Access); end Find_Sizes; -- ------------------------------ -- Find the function address from the call event frames for the events which is selected -- by the given filter. The function addresses are collected up to the given frame depth. -- Update the <tt>Frames</tt> map to keep track of the first event and last event and -- the number of events found for the corresponding frame address. -- ------------------------------ procedure Find_Frames (Target : in out MAT.Events.Targets.Target_Events'Class; Filter : in MAT.Expressions.Expression_Type; Depth : in Positive; Exact : in Boolean; Frames : in out MAT.Events.Tools.Frame_Event_Info_Map) is procedure Collect_Event (Event : in MAT.Events.Target_Event_Type); procedure Collect_Event (Event : in MAT.Events.Target_Event_Type) is procedure Update_Size (Key : in MAT.Events.Tools.Frame_Key_Type; Info : in out MAT.Events.Tools.Event_Info_Type); procedure Update_Size (Key : in MAT.Events.Tools.Frame_Key_Type; Info : in out MAT.Events.Tools.Event_Info_Type) is pragma Unreferenced (Key); begin MAT.Events.Tools.Collect_Info (Info, Event); end Update_Size; begin -- Look for events which are selected by the filter. if not Filter.Is_Selected (Event) then return; end if; declare Backtrace : constant MAT.Frames.Frame_Table := MAT.Frames.Backtrace (Event.Frame); Key : MAT.Events.Tools.Frame_Key_Type; First : Natural; Last : Natural; begin if Exact then First := Depth; else First := Backtrace'First; end if; if Depth < Backtrace'Last then Last := Depth; else Last := Backtrace'Last; end if; for I in First .. Last loop Key.Addr := Backtrace (Backtrace'Last - I + 1); Key.Level := I; declare Pos : constant MAT.Events.Tools.Frame_Event_Info_Cursor := Frames.Find (Key); begin if MAT.Events.Tools.Frame_Event_Info_Maps.Has_Element (Pos) then -- Increment the count and update the last event. Frames.Update_Element (Pos, Update_Size'Access); else declare Info : MAT.Events.Tools.Event_Info_Type; begin -- Insert a new size with the event. Info.First_Event := Event; Info.Count := 0; MAT.Events.Tools.Collect_Info (Info, Event); Frames.Insert (Key, Info); end; end if; end; end loop; end; end Collect_Event; begin Target.Iterate (Process => Collect_Event'Access); end Find_Frames; end MAT.Events.Timelines;
----------------------------------------------------------------------- -- mat-events-timelines - Timelines -- 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 MAT.Frames; package body MAT.Events.Timelines is use MAT.Events.Targets; ITERATE_COUNT : constant MAT.Events.Event_Id_Type := 10_000; procedure Extract (Target : in out MAT.Events.Targets.Target_Events'Class; Level : in Positive; Into : in out Timeline_Info_Vector) is use type MAT.Types.Target_Time; use type MAT.Types.Target_Size; procedure Collect (Event : in MAT.Events.Target_Event_Type); First_Event : MAT.Events.Target_Event_Type; Last_Event : MAT.Events.Target_Event_Type; Prev_Event : MAT.Events.Target_Event_Type; Info : Timeline_Info; First_Id : MAT.Events.Event_Id_Type; Limit : MAT.Types.Target_Time := MAT.Types.Target_Time (Level * 1_000_000); procedure Collect (Event : in MAT.Events.Target_Event_Type) is Dt : constant MAT.Types.Target_Time := Event.Time - Prev_Event.Time; begin if Dt > Limit then Into.Append (Info); Info.Malloc_Count := 0; Info.Realloc_Count := 0; Info.Free_Count := 0; Info.First_Event := Event; Info.Free_Size := 0; Info.Alloc_Size := 0; Prev_Event := Event; end if; Info.Last_Event := Event; if Event.Event = 2 then Info.Malloc_Count := Info.Malloc_Count + 1; Info.Alloc_Size := Info.Alloc_Size + Event.Size; elsif Event.Event = 3 then Info.Realloc_Count := Info.Realloc_Count + 1; Info.Alloc_Size := Info.Alloc_Size + Event.Size; Info.Free_Size := Info.Free_Size + Event.Old_Size; elsif Event.Event = 4 then Info.Free_Count := Info.Free_Count + 1; Info.Free_Size := Info.Free_Size + Event.Size; end if; end Collect; begin Target.Get_Limits (First_Event, Last_Event); Prev_Event := First_Event; Info.First_Event := First_Event; First_Id := First_Event.Id; while First_Id < Last_Event.Id loop Target.Iterate (Start => First_Id, Finish => First_Id + ITERATE_COUNT, Process => Collect'Access); First_Id := First_Id + ITERATE_COUNT; end loop; end Extract; -- ------------------------------ -- Find in the events stream the events which are associated with a given event. -- When the <tt>Event</tt> is a memory allocation, find the associated reallocation -- and free events. When the event is a free, find the associated allocations. -- Collect at most <tt>Max</tt> events. -- ------------------------------ procedure Find_Related (Target : in out MAT.Events.Targets.Target_Events'Class; Event : in MAT.Events.Target_Event_Type; Max : in Positive; List : in out MAT.Events.Tools.Target_Event_Vector) is procedure Collect_Free (Event : in MAT.Events.Target_Event_Type); procedure Collect_Alloc (Event : in MAT.Events.Target_Event_Type); First_Id : MAT.Events.Event_Id_Type; Last_Id : MAT.Events.Event_Id_Type; First_Event : MAT.Events.Target_Event_Type; Last_Event : MAT.Events.Target_Event_Type; Addr : MAT.Types.Target_Addr := Event.Addr; Done : exception; procedure Collect_Free (Event : in MAT.Events.Target_Event_Type) is begin if Event.Index = MAT.Events.MSG_FREE and then Event.Addr = Addr then List.Append (Event); raise Done; end if; if Event.Index = MAT.Events.MSG_REALLOC and then Event.Old_Addr = Addr then List.Append (Event); if Positive (List.Length) >= Max then raise Done; end if; Addr := Event.Addr; end if; end Collect_Free; procedure Collect_Alloc (Event : in MAT.Events.Target_Event_Type) is begin if Event.Index = MAT.Events.MSG_MALLOC and then Event.Addr = Addr then List.Append (Event); raise Done; end if; if Event.Index = MAT.Events.MSG_REALLOC and then Event.Addr = Addr then List.Append (Event); if Positive (List.Length) >= Max then raise Done; end if; Addr := Event.Old_Addr; end if; end Collect_Alloc; begin Target.Get_Limits (First_Event, Last_Event); First_Id := Event.Id; if Event.Index = MAT.Events.MSG_FREE then -- Search backward for MSG_MALLOC and MSG_REALLOC. First_Id := First_Id - 1; while First_Id > First_Event.Id loop if First_Id > ITERATE_COUNT then Last_Id := First_Id - ITERATE_COUNT; else Last_Id := First_Event.Id; end if; Target.Iterate (Start => First_Id, Finish => Last_Id, Process => Collect_Alloc'Access); First_Id := Last_Id; end loop; else -- Search forward for MSG_REALLOC and MSG_FREE First_Id := First_Id + 1; while First_Id < Last_Event.Id loop Target.Iterate (Start => First_Id, Finish => First_Id + ITERATE_COUNT, Process => Collect_Free'Access); First_Id := First_Id + ITERATE_COUNT; end loop; end if; exception when Done => null; end Find_Related; -- ------------------------------ -- Find the sizes of malloc and realloc events which is selected by the given filter. -- Update the <tt>Sizes</tt> map to keep track of the first event and last event and -- the number of events found for the corresponding size. -- ------------------------------ procedure Find_Sizes (Target : in out MAT.Events.Targets.Target_Events'Class; Filter : in MAT.Expressions.Expression_Type; Sizes : in out MAT.Events.Tools.Size_Event_Info_Map) is procedure Collect_Event (Event : in MAT.Events.Target_Event_Type); procedure Collect_Event (Event : in MAT.Events.Target_Event_Type) is procedure Update_Size (Size : in MAT.Types.Target_Size; Info : in out MAT.Events.Tools.Event_Info_Type); procedure Update_Size (Size : in MAT.Types.Target_Size; Info : in out MAT.Events.Tools.Event_Info_Type) is pragma Unreferenced (Size); begin MAT.Events.Tools.Collect_Info (Info, Event); end Update_Size; begin -- Look for malloc or realloc events which are selected by the filter. if (Event.Index /= MAT.Events.MSG_MALLOC and Event.Index /= MAT.Events.MSG_FREE and Event.Index /= MAT.Events.MSG_REALLOC) or else not Filter.Is_Selected (Event) then return; end if; declare Pos : constant MAT.Events.Tools.Size_Event_Info_Cursor := Sizes.Find (Event.Size); begin if MAT.Events.Tools.Size_Event_Info_Maps.Has_Element (Pos) then -- Increment the count and update the last event. Sizes.Update_Element (Pos, Update_Size'Access); else declare Info : MAT.Events.Tools.Event_Info_Type; begin -- Insert a new size with the event. Info.First_Event := Event; MAT.Events.Tools.Collect_Info (Info, Event); Sizes.Insert (Event.Size, Info); end; end if; end; end Collect_Event; begin Target.Iterate (Process => Collect_Event'Access); end Find_Sizes; -- ------------------------------ -- Find the function address from the call event frames for the events which is selected -- by the given filter. The function addresses are collected up to the given frame depth. -- Update the <tt>Frames</tt> map to keep track of the first event and last event and -- the number of events found for the corresponding frame address. -- ------------------------------ procedure Find_Frames (Target : in out MAT.Events.Targets.Target_Events'Class; Filter : in MAT.Expressions.Expression_Type; Depth : in Positive; Exact : in Boolean; Frames : in out MAT.Events.Tools.Frame_Event_Info_Map) is procedure Collect_Event (Event : in MAT.Events.Target_Event_Type); procedure Collect_Event (Event : in MAT.Events.Target_Event_Type) is procedure Update_Size (Key : in MAT.Events.Tools.Frame_Key_Type; Info : in out MAT.Events.Tools.Event_Info_Type); procedure Update_Size (Key : in MAT.Events.Tools.Frame_Key_Type; Info : in out MAT.Events.Tools.Event_Info_Type) is pragma Unreferenced (Key); begin MAT.Events.Tools.Collect_Info (Info, Event); end Update_Size; begin -- Look for events which are selected by the filter. if not Filter.Is_Selected (Event) then return; end if; declare Backtrace : constant MAT.Frames.Frame_Table := MAT.Frames.Backtrace (Event.Frame); Key : MAT.Events.Tools.Frame_Key_Type; First : Natural; Last : Natural; begin if Exact then First := Depth; else First := Backtrace'First; end if; if Depth < Backtrace'Last then Last := Depth; else Last := Backtrace'Last; end if; for I in First .. Last loop Key.Addr := Backtrace (Backtrace'Last - I + 1); Key.Level := I; declare Pos : constant MAT.Events.Tools.Frame_Event_Info_Cursor := Frames.Find (Key); begin if MAT.Events.Tools.Frame_Event_Info_Maps.Has_Element (Pos) then -- Increment the count and update the last event. Frames.Update_Element (Pos, Update_Size'Access); else declare Info : MAT.Events.Tools.Event_Info_Type; begin -- Insert a new size with the event. Info.First_Event := Event; Info.Count := 0; MAT.Events.Tools.Collect_Info (Info, Event); Frames.Insert (Key, Info); end; end if; end; end loop; end; end Collect_Event; begin Target.Iterate (Process => Collect_Event'Access); end Find_Frames; -- ------------------------------ -- Collect the events that match the filter and append them to the events vector. -- ------------------------------ procedure Filter_Events (Target : in out MAT.Events.Targets.Target_Events'Class; Filter : in MAT.Expressions.Expression_Type; Events : in out MAT.Events.Tools.Target_Event_Vector) is procedure Collect_Event (Event : in MAT.Events.Target_Event_Type); procedure Collect_Event (Event : in MAT.Events.Target_Event_Type) is begin if Filter.Is_Selected (Event) then Events.Append (Event); end if; end Collect_Event; begin Target.Iterate (Process => Collect_Event'Access); end Filter_Events; end MAT.Events.Timelines;
Implement the Filter_Events procedure
Implement the Filter_Events procedure
Ada
apache-2.0
stcarrez/mat,stcarrez/mat,stcarrez/mat
26ced4b9a2dc4a6e39b18a6b4282a59c35feb090
src/wiki-parsers-html.adb
src/wiki-parsers-html.adb
----------------------------------------------------------------------- -- wiki-parsers-html -- Wiki HTML parser -- Copyright (C) 2015, 2016 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Wiki.Helpers; with Wiki.Parsers.Html.Entities; package body Wiki.Parsers.Html is -- Parse an HTML attribute procedure Parse_Attribute_Name (P : in out Parser; Name : in out Wiki.Strings.UString); -- Parse a HTML/XML comment to strip it. procedure Parse_Comment (P : in out Parser); -- Parse a simple DOCTYPE declaration and ignore it. procedure Parse_Doctype (P : in out Parser); procedure Collect_Attributes (P : in out Parser); function Is_Letter (C : in Wiki.Strings.WChar) return Boolean; procedure Collect_Attribute_Value (P : in out Parser; Value : in out Wiki.Strings.UString); function Is_Letter (C : in Wiki.Strings.WChar) return Boolean is begin return C > ' ' and C /= ':' and C /= '>' and C /= ''' and C /= '"' and C /= '/' and C /= '=' and C /= '<'; end Is_Letter; -- ------------------------------ -- Parse an HTML attribute -- ------------------------------ procedure Parse_Attribute_Name (P : in out Parser; Name : in out Wiki.Strings.UString) is C : Wiki.Strings.WChar; begin Name := Wiki.Strings.To_UString (""); Skip_Spaces (P); while not P.Is_Eof loop Peek (P, C); if not Is_Letter (C) then Put_Back (P, C); return; end if; Wiki.Strings.Append (Name, C); end loop; end Parse_Attribute_Name; procedure Collect_Attribute_Value (P : in out Parser; Value : in out Wiki.Strings.UString) is C : Wiki.Strings.WChar; Token : Wiki.Strings.WChar; begin Value := Wiki.Strings.To_UString (""); Peek (P, Token); if Wiki.Helpers.Is_Space (Token) then return; elsif Token = '>' then Put_Back (P, Token); return; elsif Token /= ''' and Token /= '"' then Wiki.Strings.Append (Value, Token); while not P.Is_Eof loop Peek (P, C); if C = ''' or C = '"' or C = ' ' or C = '=' or C = '>' or C = '<' or C = '`' then Put_Back (P, C); return; end if; Wiki.Strings.Append (Value, C); end loop; else while not P.Is_Eof loop Peek (P, C); if C = Token then return; end if; Wiki.Strings.Append (Value, C); end loop; end if; end Collect_Attribute_Value; -- ------------------------------ -- Parse a list of HTML attributes up to the first '>'. -- attr-name -- attr-name= -- attr-name=value -- attr-name='value' -- attr-name="value" -- <name name='value' ...> -- ------------------------------ procedure Collect_Attributes (P : in out Parser) is C : Wiki.Strings.WChar; Name : Wiki.Strings.UString; Value : Wiki.Strings.UString; begin Wiki.Attributes.Clear (P.Attributes); while not P.Is_Eof loop Parse_Attribute_Name (P, Name); Skip_Spaces (P); Peek (P, C); if C = '>' or C = '<' or C = '/' then Put_Back (P, C); exit; end if; if C = '=' then Collect_Attribute_Value (P, Value); Attributes.Append (P.Attributes, Name, Value); elsif Wiki.Helpers.Is_Space (C) and Wiki.Strings.Length (Name) > 0 then Attributes.Append (P.Attributes, Name, Wiki.Strings.Null_UString); end if; end loop; -- Peek (P, C); -- Add any pending attribute. if Wiki.Strings.Length (Name) > 0 then Attributes.Append (P.Attributes, Name, Wiki.Strings.Null_UString); end if; end Collect_Attributes; -- ------------------------------ -- Parse a HTML/XML comment to strip it. -- ------------------------------ procedure Parse_Comment (P : in out Parser) is C : Wiki.Strings.WChar; begin Peek (P, C); while not P.Is_Eof loop Peek (P, C); if C = '-' then declare Count : Natural := 1; begin Peek (P, C); while not P.Is_Eof and C = '-' loop Peek (P, C); Count := Count + 1; end loop; exit when C = '>' and Count >= 2; end; end if; end loop; end Parse_Comment; -- ------------------------------ -- Parse a simple DOCTYPE declaration and ignore it. -- ------------------------------ procedure Parse_Doctype (P : in out Parser) is C : Wiki.Strings.WChar; begin while not P.Is_Eof loop Peek (P, C); exit when C = '>'; end loop; end Parse_Doctype; -- ------------------------------ -- Parse a HTML element <XXX attributes> -- or parse an end of HTML element </XXX> -- ------------------------------ procedure Parse_Element (P : in out Parser) is Name : Wiki.Strings.UString; C : Wiki.Strings.WChar; Tag : Wiki.Html_Tag; begin Peek (P, C); if C = '!' then Peek (P, C); if C = '-' then Parse_Comment (P); else Parse_Doctype (P); end if; return; end if; if C /= '/' then Put_Back (P, C); end if; Parse_Attribute_Name (P, Name); declare Token : constant Wiki.Strings.WString := Wiki.Strings.To_WString (Name); begin Tag := Wiki.Find_Tag (Token); if C = '/' then Skip_Spaces (P); Peek (P, C); if C /= '>' then Put_Back (P, C); end if; Flush_Text (P); if Tag = Wiki.UNKNOWN_TAG then if Token = "noinclude" then P.Is_Hidden := False; end if; else End_Element (P, Tag); end if; else Collect_Attributes (P); Peek (P, C); if C = '/' then Peek (P, C); if C = '>' then Start_Element (P, Tag, P.Attributes); End_Element (P, Tag); return; end if; elsif C /= '>' then Put_Back (P, C); end if; if Tag = UNKNOWN_TAG then if Token = "noinclude" then P.Is_Hidden := True; end if; else Start_Element (P, Tag, P.Attributes); end if; end if; end; end Parse_Element; -- ------------------------------ -- Parse an HTML entity such as &nbsp; and replace it with the corresponding code. -- ------------------------------ procedure Parse_Entity (P : in out Parser; Token : in Wiki.Strings.WChar) is pragma Unreferenced (Token); Name : String (1 .. 10); Len : Natural := 0; High : Natural := Wiki.Parsers.Html.Entities.Keywords'Last; Low : Natural := Wiki.Parsers.Html.Entities.Keywords'First; Pos : Natural; C : Wiki.Strings.WChar; begin while Len < Name'Last loop Peek (P, C); exit when C = ';' or else P.Is_Eof; Len := Len + 1; Name (Len) := Wiki.Strings.To_Char (C); end loop; while Low <= High loop Pos := (Low + High) / 2; if Wiki.Parsers.Html.Entities.Keywords (Pos).all = Name (1 .. Len) then Parse_Text (P, Entities.Mapping (Pos)); return; elsif Entities.Keywords (Pos).all < Name (1 .. Len) then Low := Pos + 1; else High := Pos - 1; end if; end loop; -- The HTML entity is not recognized: we must treat it as plain wiki text. Parse_Text (P, '&'); for I in 1 .. Len loop Parse_Text (P, Wiki.Strings.To_WChar (Name (I))); end loop; end Parse_Entity; end Wiki.Parsers.Html;
----------------------------------------------------------------------- -- wiki-parsers-html -- Wiki HTML parser -- Copyright (C) 2015, 2016 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Wiki.Helpers; with Wiki.Parsers.Html.Entities; package body Wiki.Parsers.Html is -- Parse an HTML attribute procedure Parse_Attribute_Name (P : in out Parser; Name : in out Wiki.Strings.BString); -- Parse a HTML/XML comment to strip it. procedure Parse_Comment (P : in out Parser); -- Parse a simple DOCTYPE declaration and ignore it. procedure Parse_Doctype (P : in out Parser); procedure Collect_Attributes (P : in out Parser); function Is_Letter (C : in Wiki.Strings.WChar) return Boolean; procedure Collect_Attribute_Value (P : in out Parser; Value : in out Wiki.Strings.BString); function Is_Letter (C : in Wiki.Strings.WChar) return Boolean is begin return C > ' ' and C /= ':' and C /= '>' and C /= ''' and C /= '"' and C /= '/' and C /= '=' and C /= '<'; end Is_Letter; -- ------------------------------ -- Parse an HTML attribute -- ------------------------------ procedure Parse_Attribute_Name (P : in out Parser; Name : in out Wiki.Strings.BString) is C : Wiki.Strings.WChar; begin Skip_Spaces (P); while not P.Is_Eof loop Peek (P, C); if not Is_Letter (C) then Put_Back (P, C); return; end if; Wiki.Strings.Wide_Wide_Builders.Append (Name, C); end loop; end Parse_Attribute_Name; procedure Collect_Attribute_Value (P : in out Parser; Value : in out Wiki.Strings.BString) is C : Wiki.Strings.WChar; Token : Wiki.Strings.WChar; begin -- Value := Wiki.Strings.To_UString (""); Peek (P, Token); if Wiki.Helpers.Is_Space (Token) then return; elsif Token = '>' then Put_Back (P, Token); return; elsif Token /= ''' and Token /= '"' then Wiki.Strings.Wide_Wide_Builders.Append (Value, Token); while not P.Is_Eof loop Peek (P, C); if C = ''' or C = '"' or C = ' ' or C = '=' or C = '>' or C = '<' or C = '`' then Put_Back (P, C); return; end if; Wiki.Strings.Wide_Wide_Builders.Append (Value, C); end loop; else while not P.Is_Eof loop Peek (P, C); if C = Token then return; end if; Wiki.Strings.Wide_Wide_Builders.Append (Value, C); end loop; end if; end Collect_Attribute_Value; -- ------------------------------ -- Parse a list of HTML attributes up to the first '>'. -- attr-name -- attr-name= -- attr-name=value -- attr-name='value' -- attr-name="value" -- <name name='value' ...> -- ------------------------------ procedure Collect_Attributes (P : in out Parser) is procedure Append_Attribute (Name : in Wiki.Strings.WString); C : Wiki.Strings.WChar; Name : Wiki.Strings.BString (64); Value : Wiki.Strings.BString (256); procedure Append_Attribute (Name : in Wiki.Strings.WString) is procedure Attribute_Value (Value : in Wiki.Strings.WString); procedure Attribute_Value (Value : in Wiki.Strings.WString) is begin Attributes.Append (P.Attributes, Name, Value); end Attribute_Value; procedure Attribute_Value is new Wiki.Strings.Wide_Wide_Builders.Get (Attribute_Value); begin Attribute_Value (Value); end Append_Attribute; pragma Inline_Always (Append_Attribute); procedure Append_Attribute is new Wiki.Strings.Wide_Wide_Builders.Get (Append_Attribute); begin Wiki.Attributes.Clear (P.Attributes); while not P.Is_Eof loop Parse_Attribute_Name (P, Name); Skip_Spaces (P); Peek (P, C); if C = '>' or C = '<' or C = '/' then Put_Back (P, C); exit; end if; if C = '=' then Collect_Attribute_Value (P, Value); Append_Attribute (Name); Wiki.Strings.Wide_Wide_Builders.Clear (Name); Wiki.Strings.Wide_Wide_Builders.Clear (Value); elsif Wiki.Strings.Wide_Wide_Builders.Length (Name) > 0 then Put_Back (P, C); Append_Attribute (Name); Wiki.Strings.Wide_Wide_Builders.Clear (Name); end if; end loop; -- Add any pending attribute. if Wiki.Strings.Wide_Wide_Builders.Length (Name) > 0 then Append_Attribute (Name); end if; end Collect_Attributes; -- ------------------------------ -- Parse a HTML/XML comment to strip it. -- ------------------------------ procedure Parse_Comment (P : in out Parser) is C : Wiki.Strings.WChar; begin Peek (P, C); while not P.Is_Eof loop Peek (P, C); if C = '-' then declare Count : Natural := 1; begin Peek (P, C); while not P.Is_Eof and C = '-' loop Peek (P, C); Count := Count + 1; end loop; exit when C = '>' and Count >= 2; end; end if; end loop; end Parse_Comment; -- ------------------------------ -- Parse a simple DOCTYPE declaration and ignore it. -- ------------------------------ procedure Parse_Doctype (P : in out Parser) is C : Wiki.Strings.WChar; begin while not P.Is_Eof loop Peek (P, C); exit when C = '>'; end loop; end Parse_Doctype; -- ------------------------------ -- Parse a HTML element <XXX attributes> -- or parse an end of HTML element </XXX> -- ------------------------------ procedure Parse_Element (P : in out Parser) is C : Wiki.Strings.WChar; procedure Add_Element (Token : in Wiki.Strings.WString); procedure Add_Element (Token : in Wiki.Strings.WString) is Tag : Wiki.Html_Tag; begin Tag := Wiki.Find_Tag (Token); if C = '/' then Skip_Spaces (P); Peek (P, C); if C /= '>' then Put_Back (P, C); end if; Flush_Text (P); if Tag = Wiki.UNKNOWN_TAG then if Token = "noinclude" then P.Is_Hidden := False; end if; else End_Element (P, Tag); end if; else Collect_Attributes (P); Peek (P, C); if C = '/' then Peek (P, C); if C = '>' then Start_Element (P, Tag, P.Attributes); End_Element (P, Tag); return; end if; elsif C /= '>' then Put_Back (P, C); end if; if Tag = UNKNOWN_TAG then if Token = "noinclude" then P.Is_Hidden := True; end if; else Start_Element (P, Tag, P.Attributes); end if; end if; end Add_Element; pragma Inline_Always (Add_Element); procedure Add_Element is new Wiki.Strings.Wide_Wide_Builders.Get (Add_Element); pragma Inline_Always (Add_Element); Name : Wiki.Strings.BString (64); begin Peek (P, C); if C = '!' then Peek (P, C); if C = '-' then Parse_Comment (P); else Parse_Doctype (P); end if; return; end if; if C /= '/' then Put_Back (P, C); end if; Parse_Attribute_Name (P, Name); Add_Element (Name); end Parse_Element; -- ------------------------------ -- Parse an HTML entity such as &nbsp; and replace it with the corresponding code. -- ------------------------------ procedure Parse_Entity (P : in out Parser; Token : in Wiki.Strings.WChar) is pragma Unreferenced (Token); Name : String (1 .. 10); Len : Natural := 0; High : Natural := Wiki.Parsers.Html.Entities.Keywords'Last; Low : Natural := Wiki.Parsers.Html.Entities.Keywords'First; Pos : Natural; C : Wiki.Strings.WChar; begin while Len < Name'Last loop Peek (P, C); exit when C = ';' or else P.Is_Eof; Len := Len + 1; Name (Len) := Wiki.Strings.To_Char (C); end loop; while Low <= High loop Pos := (Low + High) / 2; if Wiki.Parsers.Html.Entities.Keywords (Pos).all = Name (1 .. Len) then Parse_Text (P, Entities.Mapping (Pos)); return; elsif Entities.Keywords (Pos).all < Name (1 .. Len) then Low := Pos + 1; else High := Pos - 1; end if; end loop; -- The HTML entity is not recognized: we must treat it as plain wiki text. Parse_Text (P, '&'); for I in 1 .. Len loop Parse_Text (P, Wiki.Strings.To_WChar (Name (I))); end loop; end Parse_Entity; end Wiki.Parsers.Html;
Use Wiki.Strings.BString for the attribute name and attribute value (reduce dynamic memory allocation)
Use Wiki.Strings.BString for the attribute name and attribute value (reduce dynamic memory allocation)
Ada
apache-2.0
stcarrez/ada-wiki,stcarrez/ada-wiki